From db7c54ff56bc5a9c79031fba34322be3a4b1214c Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Wed, 28 May 2025 12:55:21 -0700 Subject: [PATCH 01/10] Fix commands, add configurable sounds for messages --- .../java/simplexity/simplepms/SimplePMs.java | 7 +- .../simplexity/simplepms/commands/Block.java | 4 +- .../simplepms/commands/Exceptions.java | 75 +++++++++++ .../simplepms/commands/MessageChecks.java | 73 +++++++++++ .../simplepms/commands/MessageToggle.java | 3 +- .../simplepms/commands/PrivateMessage.java | 80 ++++++------ .../simplexity/simplepms/commands/Reply.java | 59 ++++----- .../simplepms/commands/SocialSpy.java | 2 +- .../commands/arguments/MessageArgument.java | 24 ++++ .../commands/arguments/TargetArgument.java | 76 +++++++++++ .../simplepms/config/ConfigHandler.java | 13 +- .../simplepms/events/PrivateMessageEvent.java | 58 ++++++--- .../simplepms/listeners/LoginListener.java | 2 +- .../listeners/PreCommandListener.java | 4 +- .../simplexity/simplepms/logic/Constants.java | 18 +++ .../logic/{Util.java => MessageUtils.java} | 10 +- .../logic/{Messaging.java => PMHandler.java} | 45 ++++--- .../simplepms/logic/PreProcessing.java | 119 ------------------ .../simplepms/objects/PlayerBlock.java | 1 + .../simplepms/objects/PlayerSettings.java | 7 +- .../simplexity/simplepms/objects/Target.java | 6 + .../simplepms/saving/SqlHandler.java | 4 +- 22 files changed, 445 insertions(+), 245 deletions(-) create mode 100644 src/main/java/simplexity/simplepms/commands/Exceptions.java create mode 100644 src/main/java/simplexity/simplepms/commands/MessageChecks.java create mode 100644 src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java create mode 100644 src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java create mode 100644 src/main/java/simplexity/simplepms/logic/Constants.java rename src/main/java/simplexity/simplepms/logic/{Util.java => MessageUtils.java} (95%) rename src/main/java/simplexity/simplepms/logic/{Messaging.java => PMHandler.java} (68%) delete mode 100644 src/main/java/simplexity/simplepms/logic/PreProcessing.java create mode 100644 src/main/java/simplexity/simplepms/objects/Target.java diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index 36492fa..ef7e51c 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -1,5 +1,6 @@ package simplexity.simplepms; +import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; @@ -56,6 +57,10 @@ public void onEnable() { getConfig().options().copyDefaults(true); saveConfig(); ConfigHandler.getInstance().loadConfigValues(); + this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { + commands.registrar().register(PrivateMessage.createCommand()); + commands.registrar().register(Reply.createCommand()); + }); } public static MiniMessage getMiniMessage() { @@ -75,8 +80,6 @@ public static ConsoleCommandSender getPMConsoleSender() { } private void registerCommands() { - Objects.requireNonNull(this.getCommand("msg")).setExecutor(new PrivateMessage()); - Objects.requireNonNull(this.getCommand("reply")).setExecutor(new Reply()); Objects.requireNonNull(this.getCommand("socialspy")).setExecutor(new SocialSpy()); Objects.requireNonNull(this.getCommand("spmreload")).setExecutor(new Reload()); Objects.requireNonNull(this.getCommand("block")).setExecutor(new Block()); diff --git a/src/main/java/simplexity/simplepms/commands/Block.java b/src/main/java/simplexity/simplepms/commands/Block.java index 455b270..4e9453c 100644 --- a/src/main/java/simplexity/simplepms/commands/Block.java +++ b/src/main/java/simplexity/simplepms/commands/Block.java @@ -7,7 +7,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.config.Message; -import simplexity.simplepms.logic.Util; +import simplexity.simplepms.logic.MessageUtils; import simplexity.simplepms.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; @@ -25,7 +25,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return false; } String playerToBlockString = args[0]; - Player playerToBlock = Util.getInstance().getPlayer(playerToBlockString); + Player playerToBlock = MessageUtils.getInstance().getPlayer(playerToBlockString); if (playerToBlock == null) { sender.sendRichMessage(Message.RECIPIENT_NOT_EXIST.getMessage(), Placeholder.parsed("name", playerToBlockString)); diff --git a/src/main/java/simplexity/simplepms/commands/Exceptions.java b/src/main/java/simplexity/simplepms/commands/Exceptions.java new file mode 100644 index 0000000..d74a665 --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/Exceptions.java @@ -0,0 +1,75 @@ +package simplexity.simplepms.commands; + +import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import io.papermc.paper.command.brigadier.MessageComponentSerializer; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; +import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.config.Message; + +@SuppressWarnings("UnstableApiUsage") +public class Exceptions { + + private static final MiniMessage miniMessage = SimplePMs.getMiniMessage(); + + public static final SimpleCommandExceptionType ERROR_EMPTY_MESSAGE = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.BLANK_MESSAGE.getMessage() + ) + ) + ); + + public static final SimpleCommandExceptionType ERROR_NO_PERMISSION = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.NO_PERMISSION.getMessage() + ) + ) + ); + + public static final DynamicCommandExceptionType ERROR_INVALID_USER = new DynamicCommandExceptionType(input -> { + return MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.RECIPIENT_NOT_EXIST.getMessage(), + Placeholder.unparsed("name", input.toString()) + ) + ); + }); + + public static final SimpleCommandExceptionType ERROR_YOUR_MESSAGES_ARE_DISABLED = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.YOUR_MESSAGES_CURRENTLY_DISABLED.getMessage() + ) + ) + ); + + public static final SimpleCommandExceptionType ERROR_TARGET_CANNOT_RECEIVE_MESSAGE = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.TARGET_CANNOT_RECIEVE_MESSAGE.getMessage() + ) + ) + ); + + public static final SimpleCommandExceptionType ERROR_CANNOT_MESSAGE_SOMEONE_YOU_HAVE_BLOCKED = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED.getMessage() + ) + ) + ); + + public static final SimpleCommandExceptionType ERROR_NOBODY_TO_REPLY_TO = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + Message.CANNOT_REPLY.getMessage() + ) + ) + ); + + + +} diff --git a/src/main/java/simplexity/simplepms/commands/MessageChecks.java b/src/main/java/simplexity/simplepms/commands/MessageChecks.java new file mode 100644 index 0000000..c422099 --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/MessageChecks.java @@ -0,0 +1,73 @@ +package simplexity.simplepms.commands; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import simplexity.simplepms.config.ConfigHandler; +import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.saving.Cache; + +import java.util.List; + +public class MessageChecks { + + + public static void userChecks(CommandSender initiator, CommandSender target, String providedName) throws CommandSyntaxException { + if (target instanceof Player playerTarget) { + if (!initiator.hasPermission(Constants.ADMIN_OVERRIDE)) { + targetCanGetMessageCheck(playerTarget); + } + if (initiator instanceof Player playerInitiator) { + MessageChecks.ownMessagesDisabledCheck(playerInitiator); + MessageChecks.initiatorBlockedTargetCheck(playerInitiator, playerTarget); + if (!initiator.hasPermission(Constants.ADMIN_OVERRIDE)) { + MessageChecks.targetBlockedInitiatorCheck(playerInitiator, playerTarget); + MessageChecks.vanishCheck(playerInitiator, playerTarget, providedName); + } + } + } + } + + private static void vanishCheck(Player initiator, Player target, String providedName) throws CommandSyntaxException { + if (ConfigHandler.getInstance().canPlayersSendToHiddenPlayers()) return; + if (!initiator.canSee(target)) throw Exceptions.ERROR_INVALID_USER.create(providedName); + } + + private static void ownMessagesDisabledCheck(Player initiatingPlayer) throws CommandSyntaxException { + PlayerSettings settings = Cache.getPlayerSettings(initiatingPlayer.getUniqueId()); + if (settings == null) return; + if (settings.areMessagesDisabled()) throw Exceptions.ERROR_YOUR_MESSAGES_ARE_DISABLED.create(); + } + + private static void targetCanGetMessageCheck(Player targetPlayer) throws CommandSyntaxException { + if (!targetPlayer.hasPermission(Constants.MESSAGE_RECEIVE)) + throw Exceptions.ERROR_TARGET_CANNOT_RECEIVE_MESSAGE.create(); + PlayerSettings settings = Cache.getPlayerSettings(targetPlayer.getUniqueId()); + if (settings == null) return; + if (settings.areMessagesDisabled()) throw Exceptions.ERROR_TARGET_CANNOT_RECEIVE_MESSAGE.create(); + } + + private static void targetBlockedInitiatorCheck(Player initiatingPlayer, Player targetPlayer) throws CommandSyntaxException { + if (userBlocked(targetPlayer, initiatingPlayer)) throw Exceptions.ERROR_TARGET_CANNOT_RECEIVE_MESSAGE.create(); + } + + private static void initiatorBlockedTargetCheck(Player initiatingPlayer, Player targetPlayer) throws CommandSyntaxException { + if (userBlocked(initiatingPlayer, targetPlayer)) + throw Exceptions.ERROR_CANNOT_MESSAGE_SOMEONE_YOU_HAVE_BLOCKED.create(); + } + + private static boolean userBlocked(Player blocklistPlayer, Player potentialBlock) { + List playerBlocks = Cache.blockList.get(blocklistPlayer.getUniqueId()); + if (playerBlocks == null) { + return false; + } + for (PlayerBlock playerBlock : playerBlocks) { + if (playerBlock.blockedPlayerUUID().equals(potentialBlock.getUniqueId())) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/simplexity/simplepms/commands/MessageToggle.java b/src/main/java/simplexity/simplepms/commands/MessageToggle.java index 4bb8f4f..9048087 100644 --- a/src/main/java/simplexity/simplepms/commands/MessageToggle.java +++ b/src/main/java/simplexity/simplepms/commands/MessageToggle.java @@ -8,7 +8,6 @@ import simplexity.simplepms.config.Message; import simplexity.simplepms.objects.PlayerSettings; import simplexity.simplepms.saving.Cache; -import simplexity.simplepms.saving.SqlHandler; import java.util.UUID; @@ -21,7 +20,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } UUID uuid = player.getUniqueId(); PlayerSettings playerSettings = Cache.getPlayerSettings(uuid); - if (playerSettings.messagesDisabled()) { + if (playerSettings.areMessagesDisabled()) { Cache.updateMessageSettings(uuid, false); player.sendRichMessage(Message.MESSAGES_ENABLED.getMessage()); return true; diff --git a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java index e5c57a8..b116d4a 100644 --- a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java +++ b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java @@ -1,48 +1,48 @@ package simplexity.simplepms.commands; -import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; -import org.bukkit.command.Command; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import simplexity.simplepms.config.Message; -import simplexity.simplepms.logic.PreProcessing; - -import java.util.Arrays; -import java.util.List; - -public class PrivateMessage implements TabExecutor { - - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args.length < 1) { - sender.sendRichMessage(Message.NO_RECIPIENT_PROVIDED.getMessage()); - return false; - } - if (args.length < 2) { - sender.sendRichMessage(Message.BLANK_MESSAGE.getMessage()); - return false; - } - CommandSender target = PreProcessing.getInstance().getTarget(args); - if (target == null) { - sender.sendRichMessage(Message.RECIPIENT_NOT_EXIST.getMessage(), - Placeholder.unparsed("name", args[0])); - return false; - } - if (PreProcessing.getInstance().messagingBlocked(sender, target, args[0])) { - return false; - } - String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - PreProcessing.getInstance().callPMEvent(sender, target, message); - return true; +import org.bukkit.entity.Player; +import simplexity.simplepms.commands.arguments.MessageArgument; +import simplexity.simplepms.commands.arguments.TargetArgument; +import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.logic.PMHandler; +import simplexity.simplepms.objects.Target; + +@SuppressWarnings("UnstableApiUsage") +public class PrivateMessage { + + + public static LiteralCommandNode createCommand() { + TargetArgument targetArg = new TargetArgument(); + MessageArgument messageArg = new MessageArgument(); + + return Commands.literal("msg") + .requires(PrivateMessage::canExecute) + .then(Commands.argument("target", targetArg) + .suggests(targetArg::suggestOnlinePlayers) + .then(Commands.argument("message", messageArg) + .executes(PrivateMessage::execute))).build(); } + private static boolean canExecute(CommandSourceStack css) { + return css.getSender().hasPermission(Constants.MESSAGE_SEND); + } - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args.length > 1) return List.of(); - return null; + private static int execute(CommandContext ctx) throws CommandSyntaxException { + CommandSender sender = ctx.getSource().getSender(); + Target argTarget = ctx.getArgument("target", Target.class); + CommandSender target = argTarget.sender(); + MessageChecks.userChecks(sender, target, argTarget.providedName()); + String message = ctx.getArgument("message", String.class); + PMHandler.handlePrivateMessage(sender, target, message); + return Command.SINGLE_SUCCESS; } + } diff --git a/src/main/java/simplexity/simplepms/commands/Reply.java b/src/main/java/simplexity/simplepms/commands/Reply.java index 4a9a27f..eee50dc 100644 --- a/src/main/java/simplexity/simplepms/commands/Reply.java +++ b/src/main/java/simplexity/simplepms/commands/Reply.java @@ -1,37 +1,40 @@ package simplexity.simplepms.commands; -import org.bukkit.command.Command; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import simplexity.simplepms.config.Message; -import simplexity.simplepms.logic.PreProcessing; +import simplexity.simplepms.commands.arguments.MessageArgument; +import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.logic.PMHandler; -import java.util.List; +@SuppressWarnings("UnstableApiUsage") +public class Reply { -public class Reply implements TabExecutor { - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args.length < 1) { - sender.sendRichMessage(Message.BLANK_MESSAGE.getMessage()); - return false; - } - CommandSender recipient = PreProcessing.lastMessaged.get(sender); - if (recipient == null) { - sender.sendRichMessage(Message.CANNOT_REPLY.getMessage()); - return false; - } - if (PreProcessing.getInstance().messagingBlocked(sender, recipient, recipient.getName())) { - return false; - } - String message = String.join(" ", args); - PreProcessing.getInstance().callPMEvent(sender, recipient, message); - return true; + public static LiteralCommandNode createCommand() { + MessageArgument messageArgument = new MessageArgument(); + + return Commands.literal("reply") + .requires(Reply::canExecute) + .then(Commands.argument("message", messageArgument) + .executes(Reply::execute)).build(); + } + + private static boolean canExecute(CommandSourceStack css) { + return css.getSender().hasPermission(Constants.MESSAGE_SEND); } - @Override - public @Nullable List onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { - return List.of(); + private static int execute(CommandContext ctx) throws CommandSyntaxException { + CommandSender sender = ctx.getSource().getSender(); + CommandSender target = PMHandler.lastMessaged.get(sender); + if (target == null) throw Exceptions.ERROR_NOBODY_TO_REPLY_TO.create(); + MessageChecks.userChecks(sender, target, target.getName()); + String message = ctx.getArgument("message", String.class); + PMHandler.handlePrivateMessage(sender, target, message); + return Command.SINGLE_SUCCESS; } + } diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index 631a976..04da26c 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -24,7 +24,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } UUID uuid = player.getUniqueId(); PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); - if (settings == null || settings.socialSpyEnabled()) { + if (settings == null || settings.isSocialSpyEnabled()) { Cache.updateSocialSpySettings(uuid, false); sender.sendRichMessage(Message.SOCIAL_SPY_DISABLED.getMessage()); SimplePMs.getSpyingPlayers().remove(player); diff --git a/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java new file mode 100644 index 0000000..7cb4be4 --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java @@ -0,0 +1,24 @@ +package simplexity.simplepms.commands.arguments; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import io.papermc.paper.command.brigadier.argument.CustomArgumentType; +import org.jetbrains.annotations.NotNull; +import simplexity.simplepms.commands.Exceptions; + +@SuppressWarnings("UnstableApiUsage") +public class MessageArgument implements CustomArgumentType { + @Override + public @NotNull String parse(@NotNull StringReader stringReader) throws CommandSyntaxException { + String message = stringReader.getRemaining(); + if (message.isEmpty()) throw Exceptions.ERROR_EMPTY_MESSAGE.create(); + return message; + } + + @Override + public @NotNull ArgumentType getNativeType() { + return StringArgumentType.greedyString(); + } +} diff --git a/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java new file mode 100644 index 0000000..88f7490 --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java @@ -0,0 +1,76 @@ +package simplexity.simplepms.commands.arguments; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.MessageComponentSerializer; +import io.papermc.paper.command.brigadier.argument.CustomArgumentType; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.config.ConfigHandler; +import simplexity.simplepms.objects.Target; + +import java.util.concurrent.CompletableFuture; + +@SuppressWarnings("UnstableApiUsage") +public class TargetArgument implements CustomArgumentType { + + private static final CommandSender consoleSender = SimplePMs.getPMConsoleSender(); + + @Override + public @NotNull Target parse(@NotNull StringReader reader) throws CommandSyntaxException { + String targetName = reader.readString(); + if (ConfigHandler.getInstance().getValidNamesForConsole().contains(targetName.toLowerCase())) return new Target(consoleSender, targetName); + Player targetPlayer = Bukkit.getPlayerExact(targetName); + if (targetPlayer != null) return new Target(targetPlayer, targetName); + throw Exceptions.ERROR_INVALID_USER.create(targetName); + } + + @Override + public @NotNull ArgumentType getNativeType() { + return StringArgumentType.word(); + } + + + /** + * Provides suggestions for players based on the online player list. + * Will also provide a hover-able element that shows their current nickname. + * + * @param context Command Context + * @param builder SuggestionsBuilder object for adding suggestions to + * @param For Paper, generally CommandSourceStack + * @return Suggestions as a CompletableFuture + */ + public @NotNull CompletableFuture suggestOnlinePlayers(@NotNull CommandContext context, @NotNull SuggestionsBuilder builder) { + if (!(context.getSource() instanceof CommandSourceStack css)) return builder.buildFuture(); + CommandSender sender = css.getSender(); + Player playerSender = null; + if (sender instanceof Player) playerSender = (Player) sender; + for (Player player : Bukkit.getOnlinePlayers()) { + if (playerSender != null) { + if (!playerSender.canSee(player) && + !ConfigHandler.getInstance().canPlayersSendToHiddenPlayers()) continue; + } + String suggestion = player.getName(); + if (suggestion.toLowerCase().contains(builder.getRemainingLowerCase())) { + builder.suggest( + suggestion, + MessageComponentSerializer.message().serialize( + player.displayName() + ) + ); + } + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/simplexity/simplepms/config/ConfigHandler.java b/src/main/java/simplexity/simplepms/config/ConfigHandler.java index dfdd0e0..0a0eb8d 100644 --- a/src/main/java/simplexity/simplepms/config/ConfigHandler.java +++ b/src/main/java/simplexity/simplepms/config/ConfigHandler.java @@ -24,7 +24,7 @@ public static ConfigHandler getInstance() { private Sound receiveSound, sendSound, spySound; private float receivePitch, receiveVolume, sendPitch, sendVolume, spyPitch, spyVolume; private String mysqlIp, mysqlName, mysqlUsername, mysqlPassword, normalFormat, socialSpyFormat; - private List validNamesForConsole = new ArrayList<>(); + private final List validNamesForConsole = new ArrayList<>(); private final HashSet commandsToSpy = new HashSet<>(); public void loadConfigValues() { @@ -32,9 +32,10 @@ public void loadConfigValues() { FileConfiguration config = SimplePMs.getInstance().getConfig(); SqlHandler.getInstance().init(); LocaleHandler.getInstance().reloadLocale(); - validNamesForConsole.clear(); List commands = config.getStringList("command-spy.commands"); + List consoleNames = config.getStringList("valid-console-names"); updateHashSet(commandsToSpy, commands); + validateConsoleNames(consoleNames); normalFormat = config.getString("format.normal", ""); socialSpyFormat = config.getString("format.social-spy", ""); mysqlEnabled = config.getBoolean("mysql.enabled", false); @@ -45,7 +46,6 @@ public void loadConfigValues() { mysqlPassword = config.getString("mysql.password", "badpassword!"); playersSendToConsole = config.getBoolean("allow-messaging.console", true); playersSendToHiddenPlayers = config.getBoolean("allow-messaging.hidden-players", false); - validNamesForConsole = config.getStringList("valid-console-names"); consoleHasSocialSpy = config.getBoolean("console-has-social-spy", true); consoleHasCommandSpy = config.getBoolean("console-has-command-spy", false); receiveSoundEnabled = config.getBoolean("sounds.received.enabled", false); @@ -104,6 +104,13 @@ private float getValidFloat(double numberToCheck){ return 1.0f; } + private void validateConsoleNames(List list) { + validNamesForConsole.clear(); + for (String name : list) { + validNamesForConsole.add(name.toLowerCase()); + } + } + public boolean isMysqlEnabled() { return mysqlEnabled; diff --git a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java index 6be2176..cd85e46 100644 --- a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java +++ b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java @@ -15,10 +15,10 @@ */ public class PrivateMessageEvent extends Event implements Cancellable { - private final CommandSender initiator; - private final CommandSender recipient; - private final String messageContent; - private final Set spyingPlayers; + private CommandSender initiator; + private CommandSender recipient; + private String messageContent; + private Set spyingPlayers; private boolean cancelled; private static final HandlerList handlers = new HandlerList(); @@ -29,19 +29,6 @@ public PrivateMessageEvent(CommandSender initiator, CommandSender recipient, Str this.spyingPlayers = spyingPlayers; } - public @NotNull HandlerList getHandlers() { - return handlers; - } - - /** - * Gets the handlerList for this event - * - * @return HandlerList - */ - public static HandlerList getHandlerList() { - return handlers; - } - /** * Gets the CommandSender who sent the message * @@ -51,6 +38,14 @@ public CommandSender getInitiator() { return initiator; } + /** + * Sets the CommandSender who sent the message + */ + + public void setInitiator(CommandSender initiator) { + this.initiator = initiator; + } + /** * Gets the CommandSender who is to receive the message * @@ -60,6 +55,14 @@ public CommandSender getRecipient() { return recipient; } + /** + * Sets the CommandSender who will receive the message + */ + + public void setRecipient(CommandSender recipient){ + this.recipient = recipient; + } + /** * Gets the content of the message being sent * @@ -69,6 +72,14 @@ public String getMessageContent() { return messageContent; } + /** + * Sets the message content + */ + + public void setMessageContent(String messageContent){ + this.messageContent = messageContent; + } + /** * Gets the list of players who currently have SocialSpy toggled on * @@ -96,5 +107,18 @@ public void setCancelled(boolean cancel) { cancelled = cancel; } + + public @NotNull HandlerList getHandlers() { + return handlers; + } + + /** + * Gets the handlerList for this event + * + * @return HandlerList + */ + public static HandlerList getHandlerList() { + return handlers; + } } diff --git a/src/main/java/simplexity/simplepms/listeners/LoginListener.java b/src/main/java/simplexity/simplepms/listeners/LoginListener.java index 598085e..1cad10a 100644 --- a/src/main/java/simplexity/simplepms/listeners/LoginListener.java +++ b/src/main/java/simplexity/simplepms/listeners/LoginListener.java @@ -14,7 +14,7 @@ public class LoginListener implements Listener { public void onLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); PlayerSettings playerSettings = SqlHandler.getInstance().getSettings(player.getUniqueId()); - if (playerSettings.socialSpyEnabled()) { + if (playerSettings.isSocialSpyEnabled()) { SimplePMs.getSpyingPlayers().add(player); } SimplePMs.getPlayers().add(player); diff --git a/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java b/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java index 5633a20..583e60c 100644 --- a/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java +++ b/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java @@ -5,7 +5,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.logic.Messaging; +import simplexity.simplepms.logic.PMHandler; public class PreCommandListener implements Listener { @EventHandler(priority= EventPriority.MONITOR, ignoreCancelled = true) @@ -16,6 +16,6 @@ public void onCommand(PlayerCommandPreprocessEvent event) { if (!ConfigHandler.getInstance().getCommandsToSpy().contains(args[0])) return; String command = args[0].toLowerCase(); String message = event.getMessage(); - Messaging.sendCommandSpy(event.getPlayer(), command, message); + PMHandler.sendCommandSpy(event.getPlayer(), command, message); } } diff --git a/src/main/java/simplexity/simplepms/logic/Constants.java b/src/main/java/simplexity/simplepms/logic/Constants.java new file mode 100644 index 0000000..7c4dd65 --- /dev/null +++ b/src/main/java/simplexity/simplepms/logic/Constants.java @@ -0,0 +1,18 @@ +package simplexity.simplepms.logic; + +import org.bukkit.permissions.Permission; + +public class Constants { + public static Permission MESSAGE_BASIC = new Permission("message.basic"); + public static Permission MESSAGE_SEND = new Permission("message.basic.send"); + public static Permission MESSAGE_RECEIVE = new Permission("message.basic.receive"); + public static Permission MESSAGE_TOGGLE = new Permission("message.basic.toggle"); + public static Permission MESSAGE_BLOCK = new Permission("message.basic.block"); + public static Permission RELOAD = new Permission("message.reload"); + public static Permission MESSAGE_ADMIN = new Permission("message.admin"); + public static Permission ADMIN_OVERRIDE = new Permission("message.admin.override"); + public static Permission ADMIN_SOCIAL_SPY = new Permission("message.admin.social-spy"); + public static Permission ADMIN_CONSOLE_SPY = new Permission("message.admin.console-spy"); + public static Permission BYPASS_SOCIAL_SPY = new Permission("message.bypass.social-spy"); + public static Permission BYPASS_COMMAND_SPY = new Permission("message.bypass.command-spy"); +} diff --git a/src/main/java/simplexity/simplepms/logic/Util.java b/src/main/java/simplexity/simplepms/logic/MessageUtils.java similarity index 95% rename from src/main/java/simplexity/simplepms/logic/Util.java rename to src/main/java/simplexity/simplepms/logic/MessageUtils.java index 8ce2ac0..16238d2 100644 --- a/src/main/java/simplexity/simplepms/logic/Util.java +++ b/src/main/java/simplexity/simplepms/logic/MessageUtils.java @@ -15,15 +15,15 @@ import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.Message; -public class Util { - private static Util instance; +public class MessageUtils { + private static MessageUtils instance; private final MiniMessage miniMessage = SimplePMs.getMiniMessage(); - private Util() { + private MessageUtils() { } - public static Util getInstance() { - if (instance == null) instance = new Util(); + public static MessageUtils getInstance() { + if (instance == null) instance = new MessageUtils(); return instance; } diff --git a/src/main/java/simplexity/simplepms/logic/Messaging.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java similarity index 68% rename from src/main/java/simplexity/simplepms/logic/Messaging.java rename to src/main/java/simplexity/simplepms/logic/PMHandler.java index 4dc9dd6..d6090c3 100644 --- a/src/main/java/simplexity/simplepms/logic/Messaging.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -1,28 +1,30 @@ package simplexity.simplepms.logic; +import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.Message; +import simplexity.simplepms.events.PrivateMessageEvent; -public class Messaging { +import java.util.HashMap; - private static final String CONSOLE_SPY = "message.admin.console-spy"; - private static final String SOCIAL_SPY_BYPASS = "message.bypass.social-spy"; - private static final String COMMAND_SPY_BYPASS = "message.bypass.command-spy"; +public class PMHandler { + public static final HashMap lastMessaged = new HashMap<>(); - public static void sendMessage(CommandSender initiator, CommandSender target, String messageContent) { + public static void handlePrivateMessage(CommandSender initiator, CommandSender target, String messageContent) throws CommandSyntaxException { + PrivateMessageEvent messageEvent = callPMEvent(initiator, target, messageContent); handleMessageSend(initiator, target, messageContent); handleMessageReceive(initiator, target, messageContent); handleSocialSpy(initiator, target, messageContent); - PreProcessing.lastMessaged.put(initiator, target); - PreProcessing.lastMessaged.put(target, initiator); + lastMessaged.put(initiator, target); + lastMessaged.put(target, initiator); } private static void handleMessageSend(CommandSender initiator, CommandSender target, String messageContent) { - initiator.sendMessage(Util.getInstance().parseMessage( + initiator.sendMessage(MessageUtils.getInstance().parseMessage( Message.FORMAT_SENT.getMessage(), initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().sendingMessagePlaysSound()) return; @@ -34,7 +36,7 @@ private static void handleMessageSend(CommandSender initiator, CommandSender tar } private static void handleMessageReceive(CommandSender initiator, CommandSender target, String messageContent) { - target.sendMessage(Util.getInstance().parseMessage( + target.sendMessage(MessageUtils.getInstance().parseMessage( Message.FORMAT_RECEIVED.getMessage(), initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().receivingMessagePlaysSound()) return; @@ -47,8 +49,8 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender public static void sendCommandSpy(CommandSender initiator, String command, String messageContent) { - if (initiator.hasPermission(COMMAND_SPY_BYPASS)) return; - Component parsedMessage = Util.getInstance().parseMessage( + if (initiator.hasPermission(Constants.BYPASS_COMMAND_SPY)) return; + Component parsedMessage = MessageUtils.getInstance().parseMessage( Message.FORMAT_COMMAND_SPY.getMessage(), initiator, command, messageContent, true); for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { @@ -61,13 +63,14 @@ public static void sendCommandSpy(CommandSender initiator, String command, Strin } } - public static void handleSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { + private static void handleSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { boolean consoleSpy = false; - Player initiatorPlayer = Util.getInstance().getPlayerFromCommandSender(initiator); - Player targetPlayer = Util.getInstance().getPlayerFromCommandSender(target); + Player initiatorPlayer = MessageUtils.getInstance().getPlayerFromCommandSender(initiator); + Player targetPlayer = MessageUtils.getInstance().getPlayerFromCommandSender(target); if (initiatorPlayer == null || targetPlayer == null) consoleSpy = true; if (!consoleSpy) { - if (initiatorPlayer.hasPermission(SOCIAL_SPY_BYPASS) || targetPlayer.hasPermission(SOCIAL_SPY_BYPASS)) return; + if (initiatorPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY) || targetPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY)) + return; sendSocialSpy(initiator, target, messageContent); } else { sendConsoleSpy(initiator, target, messageContent); @@ -75,13 +78,13 @@ public static void handleSocialSpy(CommandSender initiator, CommandSender target } private static void sendConsoleSpy(CommandSender initiator, CommandSender target, String messageContent) { - Component parsedMessage = Util.getInstance().parseMessage( + Component parsedMessage = MessageUtils.getInstance().parseMessage( Message.FORMAT_SOCIAL_SPY.getMessage(), initiator, target, messageContent, true); for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { if (initiator.equals(spyingPlayer) || target.equals(spyingPlayer)) continue; - if (!spyingPlayer.hasPermission(CONSOLE_SPY)) continue; + if (!spyingPlayer.hasPermission(Constants.ADMIN_CONSOLE_SPY)) continue; spyingPlayer.sendMessage(parsedMessage); playSpySound(spyingPlayer); } @@ -91,7 +94,7 @@ private static void sendConsoleSpy(CommandSender initiator, CommandSender target } private static void sendSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { - Component parsedMessage = Util.getInstance().parseMessage( + Component parsedMessage = MessageUtils.getInstance().parseMessage( Message.FORMAT_SOCIAL_SPY.getMessage(), initiator, target, messageContent, true); @@ -117,5 +120,11 @@ private static void playSpySound(Player spyingPlayer) { ConfigHandler.getInstance().getSpyPitch()); } + private static PrivateMessageEvent callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { + PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, SimplePMs.getSpyingPlayers()); + SimplePMs.getInstance().getServer().getPluginManager().callEvent(messageEvent); + if (messageEvent.isCancelled()) return null; + return messageEvent; + } } diff --git a/src/main/java/simplexity/simplepms/logic/PreProcessing.java b/src/main/java/simplexity/simplepms/logic/PreProcessing.java deleted file mode 100644 index 95701f8..0000000 --- a/src/main/java/simplexity/simplepms/logic/PreProcessing.java +++ /dev/null @@ -1,119 +0,0 @@ -package simplexity.simplepms.logic; - -import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.config.Message; -import simplexity.simplepms.events.PrivateMessageEvent; -import simplexity.simplepms.objects.PlayerBlock; -import simplexity.simplepms.objects.PlayerSettings; -import simplexity.simplepms.saving.Cache; - -import java.util.HashMap; -import java.util.List; -import java.util.logging.Logger; - -public class PreProcessing { - private static PreProcessing instance; - private static final String RECEIVE_PERMISSION = "message.basic.receive"; - private static final String ADMIN_OVERRIDE = "message.admin.override"; - private static final Logger logger = SimplePMs.getInstance().getLogger(); - public static final HashMap lastMessaged = new HashMap<>(); - - - private PreProcessing() { - } - - public static PreProcessing getInstance() { - if (instance == null) instance = new PreProcessing(); - return instance; - } - - public CommandSender getTarget(String[] args) { - String targetString = args[0]; - if (ConfigHandler.getInstance().getValidNamesForConsole().contains(targetString)) { - return SimplePMs.getPMConsoleSender(); - } - return Util.getInstance().getPlayer(targetString); - } - - public boolean messagingBlocked(CommandSender sender, CommandSender recipient, String providedName) { - if (sender.hasPermission(ADMIN_OVERRIDE)) { - return false; - } - if (!(recipient instanceof Player target)) { - return !canSendToNonPlayer(sender, recipient); - } - if (!(sender instanceof Player initiator)) { - logger.info("[ERROR] There was an attempt to send a message from a non-player that is not the console. Info: "); - logger.info("Sender: " + sender.getName() + " [" + sender + "]"); - logger.info("Recipient: " + recipient.getName() + " [" + recipient + "]"); - sender.sendRichMessage(Message.SOMETHING_WENT_WRONG.getMessage()); - return true; - } - if (!initiator.canSee(target) && !ConfigHandler.getInstance().canPlayersSendToHiddenPlayers()) { - initiator.sendRichMessage(Message.RECIPIENT_NOT_EXIST.getMessage(), - Placeholder.unparsed("name", providedName)); - return true; - } - if (messagesDisabled(initiator)) { - initiator.sendRichMessage(Message.YOUR_MESSAGES_CURRENTLY_DISABLED.getMessage()); - return true; - } - if (messagesDisabled(target) || !target.hasPermission(RECEIVE_PERMISSION) || userBlocked(target, initiator)) { - initiator.sendRichMessage(Message.TARGET_CANNOT_RECIEVE_MESSAGE.getMessage()); - return true; - } - if (userBlocked(initiator, target)) { - initiator.sendRichMessage(Message.CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED.getMessage()); - return true; - } - return false; - } - - private boolean canSendToNonPlayer(CommandSender sender, CommandSender recipient) { - if (!recipient.equals(SimplePMs.getPMConsoleSender())) { - logger.info("[ERROR] There was an attempt to send a message to a non-player that is not the console. Info: "); - logger.info("Sender: " + sender.getName() + " [" + sender + "]"); - logger.info("Recipient: " + recipient.getName() + " [" + recipient + "]"); - sender.sendRichMessage(Message.SOMETHING_WENT_WRONG.getMessage()); - return true; - } - if (ConfigHandler.getInstance().canPlayersSendToConsole()) return true; - sender.sendRichMessage(Message.CANNOT_MESSAGE_CONSOLE.getMessage()); - return false; - } - - public boolean messagesDisabled(Player player) { - PlayerSettings playerSettings = Cache.playerSettings.get(player.getUniqueId()); - if (playerSettings == null) { - return false; - } - return playerSettings.messagesDisabled(); - } - - public boolean userBlocked(Player player1, Player player2) { - List playerBlocks = Cache.blockList.get(player1.getUniqueId()); - if (playerBlocks == null) { - return false; - } - for (PlayerBlock playerBlock : playerBlocks) { - if (playerBlock.blockedPlayerUUID().equals(player2.getUniqueId())) { - return true; - } - } - return false; - } - - public void callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { - PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, SimplePMs.getSpyingPlayers()); - SimplePMs.getInstance().getServer().getPluginManager().callEvent(messageEvent); - if (!messageEvent.isCancelled()) { - Messaging.sendMessage(initiator, target, messageContent); - } - - } - -} diff --git a/src/main/java/simplexity/simplepms/objects/PlayerBlock.java b/src/main/java/simplexity/simplepms/objects/PlayerBlock.java index 4d69567..8bc5292 100644 --- a/src/main/java/simplexity/simplepms/objects/PlayerBlock.java +++ b/src/main/java/simplexity/simplepms/objects/PlayerBlock.java @@ -2,6 +2,7 @@ import java.util.UUID; +@SuppressWarnings("StringTemplateMigration") public record PlayerBlock(UUID blockingPlayerUUID, String blockedPlayerName, UUID blockedPlayerUUID, String blockReason) { public String toString() { diff --git a/src/main/java/simplexity/simplepms/objects/PlayerSettings.java b/src/main/java/simplexity/simplepms/objects/PlayerSettings.java index 3b08e35..4bde586 100644 --- a/src/main/java/simplexity/simplepms/objects/PlayerSettings.java +++ b/src/main/java/simplexity/simplepms/objects/PlayerSettings.java @@ -2,6 +2,7 @@ import java.util.UUID; +@SuppressWarnings("StringTemplateMigration") public final class PlayerSettings { private final UUID playerUUID; private boolean socialSpyEnabled; @@ -25,15 +26,15 @@ public String toString() { + "\nMessages Enabled: " + messagesDisabled; } - public UUID playerUUID() { + public UUID getPlayerUUID() { return playerUUID; } - public boolean socialSpyEnabled() { + public boolean isSocialSpyEnabled() { return socialSpyEnabled; } - public boolean messagesDisabled() { + public boolean areMessagesDisabled() { return messagesDisabled; } diff --git a/src/main/java/simplexity/simplepms/objects/Target.java b/src/main/java/simplexity/simplepms/objects/Target.java new file mode 100644 index 0000000..9a2fb12 --- /dev/null +++ b/src/main/java/simplexity/simplepms/objects/Target.java @@ -0,0 +1,6 @@ +package simplexity.simplepms.objects; + +import org.bukkit.command.CommandSender; + +public record Target(CommandSender sender, String providedName) { +} diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index baa7631..3bd86e0 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -153,8 +153,8 @@ public List getBlockedPlayers(UUID playerUUID) { public void updateSettings(UUID playerUUID, PlayerSettings settings) { try (PreparedStatement statement = connection.prepareStatement(settingsUpdateStatement)) { statement.setString(1, String.valueOf(playerUUID)); - statement.setBoolean(2, settings.socialSpyEnabled()); - statement.setBoolean(3, settings.messagesDisabled()); + statement.setBoolean(2, settings.isSocialSpyEnabled()); + statement.setBoolean(3, settings.areMessagesDisabled()); statement.executeUpdate(); } catch (SQLException e) { logger.severe("Failed to update settings to database: " + e.getMessage()); From b5b1cbd03904d8634caf190760c79ffff5cce0aa Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Thu, 29 May 2025 16:12:17 -0700 Subject: [PATCH 02/10] Block and Unblock are now brig commands --- .../java/simplexity/simplepms/SimplePMs.java | 5 +- .../simplexity/simplepms/commands/Block.java | 98 ++++++++++++------- .../simplepms/commands/Blocklist.java | 12 +-- .../simplepms/commands/Exceptions.java | 40 +++++--- .../simplepms/commands/MessageToggle.java | 8 +- .../simplepms/commands/PrivateMessage.java | 7 +- .../simplexity/simplepms/commands/Reload.java | 4 +- .../simplexity/simplepms/commands/Reply.java | 5 +- .../simplepms/commands/SocialSpy.java | 8 +- .../simplepms/commands/Unblock.java | 78 +++++++++++++-- .../commands/arguments/MessageArgument.java | 24 ----- .../arguments/OfflinePlayerArgument.java | 80 +++++++++++++++ .../suggestions/BlockedUserSuggestions.java | 4 + .../simplepms/config/ConfigHandler.java | 8 +- .../simplepms/config/LocaleHandler.java | 14 +-- .../{Message.java => LocaleMessage.java} | 36 +++---- .../simplepms/events/BlockUserEvent.java | 86 ++++++++++++++++ .../simplepms/events/PrivateMessageEvent.java | 4 +- .../simplepms/events/UnblockUserEvent.java | 61 ++++++++++++ .../simplepms/logic/BlockHandler.java | 36 +++++++ .../simplepms/logic/MessageUtils.java | 6 +- .../simplexity/simplepms/logic/PMHandler.java | 20 ++-- .../simplepms/logic/UnblockHandler.java | 38 +++++++ .../simplexity/simplepms/saving/Cache.java | 19 ++-- 24 files changed, 539 insertions(+), 162 deletions(-) delete mode 100644 src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java create mode 100644 src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java create mode 100644 src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java rename src/main/java/simplexity/simplepms/config/{Message.java => LocaleMessage.java} (51%) create mode 100644 src/main/java/simplexity/simplepms/events/BlockUserEvent.java create mode 100644 src/main/java/simplexity/simplepms/events/UnblockUserEvent.java create mode 100644 src/main/java/simplexity/simplepms/logic/BlockHandler.java create mode 100644 src/main/java/simplexity/simplepms/logic/UnblockHandler.java diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index ef7e51c..693a051 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -23,6 +23,7 @@ import java.util.Objects; import java.util.Set; +@SuppressWarnings("UnstableApiUsage") public final class SimplePMs extends JavaPlugin { private static Plugin instance; @@ -60,6 +61,8 @@ public void onEnable() { this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { commands.registrar().register(PrivateMessage.createCommand()); commands.registrar().register(Reply.createCommand()); + commands.registrar().register(Block.createCommand()); + commands.registrar().register(Unblock.createCommand()); }); } @@ -82,8 +85,6 @@ public static ConsoleCommandSender getPMConsoleSender() { private void registerCommands() { Objects.requireNonNull(this.getCommand("socialspy")).setExecutor(new SocialSpy()); Objects.requireNonNull(this.getCommand("spmreload")).setExecutor(new Reload()); - Objects.requireNonNull(this.getCommand("block")).setExecutor(new Block()); - Objects.requireNonNull(this.getCommand("unblock")).setExecutor(new Unblock()); Objects.requireNonNull(this.getCommand("blocklist")).setExecutor(new Blocklist()); Objects.requireNonNull(this.getCommand("msgtoggle")).setExecutor(new MessageToggle()); } diff --git a/src/main/java/simplexity/simplepms/commands/Block.java b/src/main/java/simplexity/simplepms/commands/Block.java index 4e9453c..829fc85 100644 --- a/src/main/java/simplexity/simplepms/commands/Block.java +++ b/src/main/java/simplexity/simplepms/commands/Block.java @@ -1,45 +1,69 @@ package simplexity.simplepms.commands; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import simplexity.simplepms.config.Message; -import simplexity.simplepms.logic.MessageUtils; -import simplexity.simplepms.objects.PlayerBlock; -import simplexity.simplepms.saving.Cache; - -import java.util.Arrays; - -public class Block implements CommandExecutor { - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { - if (!(sender instanceof Player player)) { - sender.sendRichMessage(Message.ONLY_PLAYER.getMessage()); - return false; - } - if (args.length == 0) { - player.sendRichMessage(Message.NO_USER_PROVIDED.getMessage()); - return false; - } - String playerToBlockString = args[0]; - Player playerToBlock = MessageUtils.getInstance().getPlayer(playerToBlockString); - if (playerToBlock == null) { - sender.sendRichMessage(Message.RECIPIENT_NOT_EXIST.getMessage(), - Placeholder.parsed("name", playerToBlockString)); - return false; - } - String blockReason = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - PlayerBlock playerBlock = new PlayerBlock( - player.getUniqueId(), - playerToBlock.getName(), - playerToBlock.getUniqueId(), - blockReason); - Cache.addBlockedUser(player.getUniqueId(), playerBlock); - player.sendRichMessage(Message.BLOCKED_PLAYER.getMessage(), - Placeholder.parsed("name", playerToBlockString)); - return true; +import simplexity.simplepms.commands.arguments.OfflinePlayerArgument; +import simplexity.simplepms.config.LocaleMessage; +import simplexity.simplepms.logic.BlockHandler; +import simplexity.simplepms.logic.Constants; + +@SuppressWarnings("UnstableApiUsage") +public class Block { + + public static LiteralCommandNode createCommand() { + OfflinePlayerArgument offlinePlayerArg = new OfflinePlayerArgument(); + + return Commands.literal("block") + .requires(Block::canExecute) + .then(Commands.argument("target", offlinePlayerArg) + .suggests(offlinePlayerArg::suggestOnlinePlayers) + .executes(Block::execute) + .then(Commands.argument("reason", StringArgumentType.greedyString()) + .executes(Block::executeWithReason))).build(); + } + + private static boolean canExecute(CommandSourceStack css) { + if (!(css.getSender() instanceof Player)) return false; + return css.getSender().hasPermission(Constants.MESSAGE_BLOCK); + } + + private static int execute(CommandContext ctx) throws CommandSyntaxException { + CommandSender sender = ctx.getSource().getSender(); + if (!(sender instanceof Player playerSender)) throw Exceptions.ERROR_MUST_BE_PLAYER.create(); + OfflinePlayer target = ctx.getArgument("target", OfflinePlayer.class); + BlockHandler.addBlockedPlayer(playerSender, target, null); + sendSuccessMessage(playerSender, target); + return Command.SINGLE_SUCCESS; + } + + private static int executeWithReason(CommandContext ctx) throws CommandSyntaxException { + CommandSender sender = ctx.getSource().getSender(); + if (!(sender instanceof Player playerSender)) throw Exceptions.ERROR_MUST_BE_PLAYER.create(); + OfflinePlayer target = ctx.getArgument("target", OfflinePlayer.class); + String reason = ctx.getArgument("reason", String.class); + BlockHandler.addBlockedPlayer(playerSender, target, reason); + sendSuccessMessage(playerSender, target); + return Command.SINGLE_SUCCESS; + } + + private static void sendSuccessMessage(@NotNull Player sender, @NotNull OfflinePlayer blockedPlayer) { + String blockedPlayerName = blockedPlayer.getName(); + if (blockedPlayerName == null) blockedPlayerName = "[NO NAME FOUND]"; // Attempting to make intellij shut up + sender.sendRichMessage( + LocaleMessage.BLOCKED_PLAYER.getMessage(), + Placeholder.parsed("name", blockedPlayerName) + ); + } + } diff --git a/src/main/java/simplexity/simplepms/commands/Blocklist.java b/src/main/java/simplexity/simplepms/commands/Blocklist.java index d1074e3..5b813cb 100644 --- a/src/main/java/simplexity/simplepms/commands/Blocklist.java +++ b/src/main/java/simplexity/simplepms/commands/Blocklist.java @@ -9,7 +9,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; @@ -23,24 +23,24 @@ public class Blocklist implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if (!(sender instanceof Player player)) { - sender.sendMessage(Message.ONLY_PLAYER.getMessage()); + sender.sendMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); return false; } UUID uuid = player.getUniqueId(); List blockList = Cache.getBlockList(uuid); if (blockList == null || blockList.isEmpty()) { - player.sendRichMessage(Message.BLOCKLIST_EMPTY.getMessage()); + player.sendRichMessage(LocaleMessage.BLOCKLIST_EMPTY.getMessage()); return true; } - Component message = miniMessage.deserialize(Message.BLOCKLIST_HEADER.getMessage()); + Component message = miniMessage.deserialize(LocaleMessage.BLOCKLIST_HEADER.getMessage()); for (PlayerBlock block : blockList) { message = message.appendNewline(); message = message.append(miniMessage.deserialize( - Message.BLOCKLIST_NAME.getMessage(), + LocaleMessage.BLOCKLIST_NAME.getMessage(), Placeholder.parsed("name", block.blockedPlayerName()) )); if (block.blockReason() == null || block.blockReason().isEmpty()) continue; - message = message.append(miniMessage.deserialize(Message.BLOCKLIST_REASON.getMessage(), + message = message.append(miniMessage.deserialize(LocaleMessage.BLOCKLIST_REASON.getMessage(), Placeholder.parsed("reason", block.blockReason()))); } sender.sendMessage(message); diff --git a/src/main/java/simplexity/simplepms/commands/Exceptions.java b/src/main/java/simplexity/simplepms/commands/Exceptions.java index d74a665..69b3a37 100644 --- a/src/main/java/simplexity/simplepms/commands/Exceptions.java +++ b/src/main/java/simplexity/simplepms/commands/Exceptions.java @@ -6,7 +6,7 @@ import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; @SuppressWarnings("UnstableApiUsage") public class Exceptions { @@ -16,7 +16,7 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_EMPTY_MESSAGE = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.BLANK_MESSAGE.getMessage() + LocaleMessage.ERROR_BLANK_MESSAGE.getMessage() ) ) ); @@ -24,24 +24,24 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_NO_PERMISSION = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.NO_PERMISSION.getMessage() + LocaleMessage.ERROR_NO_PERMISSION.getMessage() ) ) ); public static final DynamicCommandExceptionType ERROR_INVALID_USER = new DynamicCommandExceptionType(input -> { - return MessageComponentSerializer.message().serialize( - miniMessage.deserialize( - Message.RECIPIENT_NOT_EXIST.getMessage(), - Placeholder.unparsed("name", input.toString()) - ) - ); + return MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + LocaleMessage.ERROR_RECIPIENT_NOT_EXIST.getMessage(), + Placeholder.unparsed("name", input.toString()) + ) + ); }); public static final SimpleCommandExceptionType ERROR_YOUR_MESSAGES_ARE_DISABLED = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.YOUR_MESSAGES_CURRENTLY_DISABLED.getMessage() + LocaleMessage.ERROR_YOUR_MESSAGES_CURRENTLY_DISABLED.getMessage() ) ) ); @@ -49,7 +49,7 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_TARGET_CANNOT_RECEIVE_MESSAGE = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.TARGET_CANNOT_RECIEVE_MESSAGE.getMessage() + LocaleMessage.ERROR_TARGET_CANNOT_RECIEVE_MESSAGE.getMessage() ) ) ); @@ -57,7 +57,7 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_CANNOT_MESSAGE_SOMEONE_YOU_HAVE_BLOCKED = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED.getMessage() + LocaleMessage.ERROR_CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED.getMessage() ) ) ); @@ -65,11 +65,25 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_NOBODY_TO_REPLY_TO = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - Message.CANNOT_REPLY.getMessage() + LocaleMessage.ERROR_CANNOT_REPLY.getMessage() ) ) ); + public static final SimpleCommandExceptionType ERROR_MUST_BE_PLAYER = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + LocaleMessage.ERROR_NOT_A_PLAYER.getMessage() + ) + ) + ); + public static final SimpleCommandExceptionType ERROR_NOT_BLOCKING_ANYONE_BY_THIS_NAME = new SimpleCommandExceptionType( + MessageComponentSerializer.message().serialize( + miniMessage.deserialize( + LocaleMessage.PLAYER_NOT_BLOCKED.getMessage() + ) + ) + ); } diff --git a/src/main/java/simplexity/simplepms/commands/MessageToggle.java b/src/main/java/simplexity/simplepms/commands/MessageToggle.java index 9048087..9ec70c0 100644 --- a/src/main/java/simplexity/simplepms/commands/MessageToggle.java +++ b/src/main/java/simplexity/simplepms/commands/MessageToggle.java @@ -5,7 +5,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.objects.PlayerSettings; import simplexity.simplepms.saving.Cache; @@ -15,18 +15,18 @@ public class MessageToggle implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { if (!(sender instanceof Player player)) { - sender.sendRichMessage(Message.ONLY_PLAYER.getMessage()); + sender.sendRichMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); return false; } UUID uuid = player.getUniqueId(); PlayerSettings playerSettings = Cache.getPlayerSettings(uuid); if (playerSettings.areMessagesDisabled()) { Cache.updateMessageSettings(uuid, false); - player.sendRichMessage(Message.MESSAGES_ENABLED.getMessage()); + player.sendRichMessage(LocaleMessage.MESSAGES_ENABLED.getMessage()); return true; } Cache.updateMessageSettings(uuid, true); - player.sendRichMessage(Message.MESSAGES_DISABLED.getMessage()); + player.sendRichMessage(LocaleMessage.MESSAGES_DISABLED.getMessage()); return true; } } diff --git a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java index b116d4a..f08dc63 100644 --- a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java +++ b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java @@ -1,15 +1,13 @@ package simplexity.simplepms.commands; import com.mojang.brigadier.Command; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import simplexity.simplepms.commands.arguments.MessageArgument; import simplexity.simplepms.commands.arguments.TargetArgument; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.PMHandler; @@ -21,13 +19,12 @@ public class PrivateMessage { public static LiteralCommandNode createCommand() { TargetArgument targetArg = new TargetArgument(); - MessageArgument messageArg = new MessageArgument(); return Commands.literal("msg") .requires(PrivateMessage::canExecute) .then(Commands.argument("target", targetArg) .suggests(targetArg::suggestOnlinePlayers) - .then(Commands.argument("message", messageArg) + .then(Commands.argument("message", StringArgumentType.greedyString()) .executes(PrivateMessage::execute))).build(); } diff --git a/src/main/java/simplexity/simplepms/commands/Reload.java b/src/main/java/simplexity/simplepms/commands/Reload.java index b98e7c9..1426688 100644 --- a/src/main/java/simplexity/simplepms/commands/Reload.java +++ b/src/main/java/simplexity/simplepms/commands/Reload.java @@ -5,13 +5,13 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; public class Reload implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { ConfigHandler.getInstance().loadConfigValues(); - sender.sendRichMessage(Message.RELOADED.getMessage()); + sender.sendRichMessage(LocaleMessage.RELOADED.getMessage()); return true; } diff --git a/src/main/java/simplexity/simplepms/commands/Reply.java b/src/main/java/simplexity/simplepms/commands/Reply.java index eee50dc..9c9da5a 100644 --- a/src/main/java/simplexity/simplepms/commands/Reply.java +++ b/src/main/java/simplexity/simplepms/commands/Reply.java @@ -1,13 +1,13 @@ package simplexity.simplepms.commands; import com.mojang.brigadier.Command; +import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; -import simplexity.simplepms.commands.arguments.MessageArgument; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.PMHandler; @@ -15,11 +15,10 @@ public class Reply { public static LiteralCommandNode createCommand() { - MessageArgument messageArgument = new MessageArgument(); return Commands.literal("reply") .requires(Reply::canExecute) - .then(Commands.argument("message", messageArgument) + .then(Commands.argument("message", StringArgumentType.greedyString()) .executes(Reply::execute)).build(); } diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index 04da26c..53968b8 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -6,7 +6,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.objects.PlayerSettings; import simplexity.simplepms.saving.Cache; import simplexity.simplepms.saving.SqlHandler; @@ -19,19 +19,19 @@ public class SocialSpy implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { if (!(sender instanceof Player player)) { - sender.sendRichMessage(Message.ONLY_PLAYER.getMessage()); + sender.sendRichMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); return false; } UUID uuid = player.getUniqueId(); PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); if (settings == null || settings.isSocialSpyEnabled()) { Cache.updateSocialSpySettings(uuid, false); - sender.sendRichMessage(Message.SOCIAL_SPY_DISABLED.getMessage()); + sender.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); SimplePMs.getSpyingPlayers().remove(player); return true; } Cache.updateSocialSpySettings(uuid, true); - sender.sendRichMessage(Message.SOCIAL_SPY_ENABLED.getMessage()); + sender.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); SimplePMs.getSpyingPlayers().add(player); return true; } diff --git a/src/main/java/simplexity/simplepms/commands/Unblock.java b/src/main/java/simplexity/simplepms/commands/Unblock.java index 4ce9b78..c77e065 100644 --- a/src/main/java/simplexity/simplepms/commands/Unblock.java +++ b/src/main/java/simplexity/simplepms/commands/Unblock.java @@ -1,28 +1,84 @@ package simplexity.simplepms.commands; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; +import io.papermc.paper.command.brigadier.MessageComponentSerializer; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; -import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; +import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.logic.UnblockHandler; import simplexity.simplepms.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CompletableFuture; -public class Unblock implements TabExecutor { +@SuppressWarnings("UnstableApiUsage") +public class Unblock { + + public static LiteralCommandNode createCommand() { + + return Commands.literal("unblock") + .requires(Unblock::canExecute) + .then(Commands.argument("target", StringArgumentType.word()) + .suggests(Unblock::suggestBlockedUsers) + .executes(Unblock::execute)).build(); + } + + private static boolean canExecute(CommandSourceStack css) { + if (!(css.getSender() instanceof Player)) return false; + return css.getSender().hasPermission(Constants.MESSAGE_BLOCK); + } + + private static int execute(CommandContext ctx) throws CommandSyntaxException { + CommandSender sender = ctx.getSource().getSender(); + if (!(sender instanceof Player playerSender)) throw Exceptions.ERROR_MUST_BE_PLAYER.create(); + String target = ctx.getArgument("target", String.class); + UnblockHandler.removeBlockedPlayer(playerSender, target); + sendSuccessMessage(playerSender, target); + return Command.SINGLE_SUCCESS; + } + + private static void sendSuccessMessage(Player sender, String name) { + sender.sendRichMessage( + LocaleMessage.NO_LONGER_BLOCKING.getMessage(), + Placeholder.parsed("name", name) + ); + } + + private static CompletableFuture suggestBlockedUsers(final CommandContext ctx, final SuggestionsBuilder builder) { + CommandSender sender = ctx.getSource().getSender(); + if (!(sender instanceof Player playerSender)) return builder.buildFuture(); + List blockedPlayers = Cache.getBlockList(playerSender.getUniqueId()); + if (blockedPlayers.isEmpty()) return builder.buildFuture(); + for (PlayerBlock block : blockedPlayers) { + builder.suggest(block.blockedPlayerName(), + MessageComponentSerializer.message().serialize(Component.text(block.blockReason()))); + } + return builder.buildFuture(); + } + + + + /* @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if (!(sender instanceof Player player)) { - sender.sendRichMessage(Message.ONLY_PLAYER.getMessage()); + sender.sendRichMessage(Message.ERROR_NOT_A_PLAYER.getMessage()); return false; } if (args.length == 0) { - player.sendRichMessage(Message.NO_USER_PROVIDED.getMessage()); + player.sendRichMessage(Message.ERROR_NO_USER_PROVIDED.getMessage()); return false; } String blockString = args[0]; @@ -32,7 +88,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command player.sendRichMessage(Message.PLAYER_NOT_BLOCKED.getMessage()); return false; } - Cache.removeBlockedUser(player.getUniqueId(), blockedPlayer); + Cache.removeBlockedUser(player.getUniqueId(), blockedPlayer.blockedPlayerUUID()); player.sendRichMessage(Message.NO_LONGER_BLOCKING.getMessage(), Placeholder.parsed("name", blockString)); return true; @@ -58,4 +114,6 @@ private PlayerBlock getBlockedPlayer(String playerBlocked, List pla } return blocked; } + + */ } diff --git a/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java deleted file mode 100644 index 7cb4be4..0000000 --- a/src/main/java/simplexity/simplepms/commands/arguments/MessageArgument.java +++ /dev/null @@ -1,24 +0,0 @@ -package simplexity.simplepms.commands.arguments; - -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import io.papermc.paper.command.brigadier.argument.CustomArgumentType; -import org.jetbrains.annotations.NotNull; -import simplexity.simplepms.commands.Exceptions; - -@SuppressWarnings("UnstableApiUsage") -public class MessageArgument implements CustomArgumentType { - @Override - public @NotNull String parse(@NotNull StringReader stringReader) throws CommandSyntaxException { - String message = stringReader.getRemaining(); - if (message.isEmpty()) throw Exceptions.ERROR_EMPTY_MESSAGE.create(); - return message; - } - - @Override - public @NotNull ArgumentType getNativeType() { - return StringArgumentType.greedyString(); - } -} diff --git a/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java new file mode 100644 index 0000000..cda8efe --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java @@ -0,0 +1,80 @@ +package simplexity.simplepms.commands.arguments; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.MessageComponentSerializer; +import io.papermc.paper.command.brigadier.argument.CustomArgumentType; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.config.ConfigHandler; + +import java.util.concurrent.CompletableFuture; + + +@SuppressWarnings("UnstableApiUsage") +public class OfflinePlayerArgument implements CustomArgumentType { + + @Override + public @NotNull OfflinePlayer parse(@NotNull StringReader reader) throws CommandSyntaxException { + String playerName = reader.readString(); + OfflinePlayer[] offlinePlayers = Bukkit.getOfflinePlayers(); + OfflinePlayer offlinePlayer = null; + for (OfflinePlayer player : offlinePlayers) { + if (player.getName() == null || player.getName().isEmpty()) continue; + if (player.getName().equalsIgnoreCase(playerName)) { + offlinePlayer = player; + break; + } + } + if (offlinePlayer == null || !offlinePlayer.hasPlayedBefore()) + throw Exceptions.ERROR_INVALID_USER.create(playerName); + return offlinePlayer; + } + + @Override + public @NotNull ArgumentType getNativeType() { + return StringArgumentType.word(); + } + + /** + * Provides suggestions for players based on the online player list. + * Will also provide a hover-able element that shows their current nickname. + * + * @param context Command Context + * @param builder SuggestionsBuilder object for adding suggestions to + * @param For Paper, generally CommandSourceStack + * @return Suggestions as a CompletableFuture + */ + public @NotNull CompletableFuture suggestOnlinePlayers(@NotNull CommandContext context, @NotNull SuggestionsBuilder builder) { + if (!(context.getSource() instanceof CommandSourceStack css)) return builder.buildFuture(); + CommandSender sender = css.getSender(); + Player playerSender = null; + if (sender instanceof Player) playerSender = (Player) sender; + for (Player player : Bukkit.getOnlinePlayers()) { + if (playerSender != null) { + if (!playerSender.canSee(player) && + !ConfigHandler.getInstance().canPlayersSendToHiddenPlayers()) continue; + } + String suggestion = player.getName(); + if (suggestion.toLowerCase().contains(builder.getRemainingLowerCase())) { + builder.suggest( + suggestion, + MessageComponentSerializer.message().serialize( + player.displayName() + ) + ); + } + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java b/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java new file mode 100644 index 0000000..aa0243e --- /dev/null +++ b/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java @@ -0,0 +1,4 @@ +package simplexity.simplepms.commands.suggestions; + +public class BlockedUserSuggestions { +} diff --git a/src/main/java/simplexity/simplepms/config/ConfigHandler.java b/src/main/java/simplexity/simplepms/config/ConfigHandler.java index 0a0eb8d..ef98162 100644 --- a/src/main/java/simplexity/simplepms/config/ConfigHandler.java +++ b/src/main/java/simplexity/simplepms/config/ConfigHandler.java @@ -87,8 +87,8 @@ private Sound getValidSound(String soundString, Sound defaultSound){ try { sound = Sound.valueOf(soundString); } catch (IllegalArgumentException exception) { - String warning = Message.SOUND_NOT_VALID.getMessage().replace("%sound-string%", soundString); - String warning2 = Message.USING_DEFAULT_SOUND.getMessage().replace("%default-sound%", defaultSound.name()); + String warning = LocaleMessage.LOG_ERROR_SOUND_NOT_VALID.getMessage().replace("%sound-string%", soundString); + String warning2 = LocaleMessage.LOG_ERROR_USING_DEFAULT_SOUND.getMessage().replace("%default-sound%", defaultSound.name()); logger.warning(warning); logger.warning(warning2); sound = defaultSound; @@ -98,9 +98,9 @@ private Sound getValidSound(String soundString, Sound defaultSound){ private float getValidFloat(double numberToCheck){ if (numberToCheck <= 2 && numberToCheck >= 0) return (float) numberToCheck; - String warning = Message.OUT_OF_RANGE.getMessage().replace("%number%", String.valueOf(numberToCheck)); + String warning = LocaleMessage.LOG_ERROR_FLOAT_OUT_OF_RANGE.getMessage().replace("%number%", String.valueOf(numberToCheck)); logger.warning(warning); - logger.warning(Message.USING_DEFAULT_NUMBER.getMessage()); + logger.warning(LocaleMessage.LOG_ERROR_USING_DEFAULT_FLOAT.getMessage()); return 1.0f; } diff --git a/src/main/java/simplexity/simplepms/config/LocaleHandler.java b/src/main/java/simplexity/simplepms/config/LocaleHandler.java index ee60fff..2d6363e 100644 --- a/src/main/java/simplexity/simplepms/config/LocaleHandler.java +++ b/src/main/java/simplexity/simplepms/config/LocaleHandler.java @@ -52,16 +52,16 @@ public void reloadLocale() { private void populateLocale() { - Set missing = new HashSet<>(Arrays.asList(Message.values())); - for (Message message : Message.values()) { - if (locale.contains(message.getPath())) { - message.setMessage(locale.getString(message.getPath())); - missing.remove(message); + Set missing = new HashSet<>(Arrays.asList(LocaleMessage.values())); + for (LocaleMessage localeMessage : LocaleMessage.values()) { + if (locale.contains(localeMessage.getPath())) { + localeMessage.setMessage(locale.getString(localeMessage.getPath())); + missing.remove(localeMessage); } } - for (Message message : missing) { - locale.set(message.getPath(), message.getMessage()); + for (LocaleMessage localeMessage : missing) { + locale.set(localeMessage.getPath(), localeMessage.getMessage()); } diff --git a/src/main/java/simplexity/simplepms/config/Message.java b/src/main/java/simplexity/simplepms/config/LocaleMessage.java similarity index 51% rename from src/main/java/simplexity/simplepms/config/Message.java rename to src/main/java/simplexity/simplepms/config/LocaleMessage.java index 8aa1c6a..3b98bcf 100644 --- a/src/main/java/simplexity/simplepms/config/Message.java +++ b/src/main/java/simplexity/simplepms/config/LocaleMessage.java @@ -1,6 +1,6 @@ package simplexity.simplepms.config; -public enum Message { +public enum LocaleMessage { CONSOLE_SENDER_NAME("console.name", "[Server]"), CONSOLE_NAME_SOCIAL_SPY("console.social-spy-name", "[Server]"), RELOADED("plugin.reloaded", "SimplePMs Config has been reloaded"), @@ -19,28 +19,28 @@ public enum Message { BLOCKLIST_NAME("plugin.block-list.name", "• "), BLOCKLIST_REASON("plugin.block-list.reason", " (Reason: )"), BLOCKLIST_EMPTY("plugin.block-list.empty", "You are not blocking anybody"), - ONLY_PLAYER("error.only-player", "You must be a player to execute this command."), - NO_PERMISSION("error.no-permission", "You do not have permission to do this"), - NO_RECIPIENT_PROVIDED("error.no-recipient-provided", "You must provide a valid recipient for your message"), - NO_USER_PROVIDED("error.no-user-provided", "You must provide a valid user"), - BLANK_MESSAGE("error.blank-message", "You cannot send someone a blank message"), - RECIPIENT_NOT_EXIST("error.recipient-not-exist", "The user either does not exist, or is not online"), - TARGET_CANNOT_RECIEVE_MESSAGE("error.cannot-receive-message", "Sorry, looks like that player cannot receive messages right now"), - CANNOT_REPLY("error.cannot-reply", "There is nobody to reply to, sorry. Try /msg [name] instead"), - YOUR_MESSAGES_CURRENTLY_DISABLED("error.your-messages-currently-disabled", "Sorry, you cannot send a message to someone while your messages are disabled."), - CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED("error.cannot-message-someone-you-blocked", "Sorry, you cannot message someone you currently have blocked."), - CANNOT_MESSAGE_CONSOLE("error.cannot-message-console", "Sorry, you cannot message the server"), - SOMETHING_WENT_WRONG("error.something-wrong", "Sorry, something went wrong, please check console for more information"), - SOUND_NOT_VALID("console-error.sound-not-valid", "Warning! The sound you have input: '%sound-string%' is invalid! Please be sure you use a sound that is listed on https://jd.papermc.io/paper/1.21.4/org/bukkit/Sound.html"), - USING_DEFAULT_SOUND("console-error.using-default-sound", "Using %default-sound% until a valid sound is provided"), - OUT_OF_RANGE("console-error.float-out-of-range", "The number %number% is out of range! Volume and pitch values must be a number between 0 and 2!"), - USING_DEFAULT_NUMBER("console-error.using-default-float", "Setting to 1.0 until a valid value is provided"); + ERROR_NOT_A_PLAYER("error.only-player", "You must be a player to execute this command."), + ERROR_NO_PERMISSION("error.no-permission", "You do not have permission to do this"), + ERROR_NO_RECIPIENT_PROVIDED("error.no-recipient-provided", "You must provide a valid recipient for your message"), + ERROR_NO_USER_PROVIDED("error.no-user-provided", "You must provide a valid user"), + ERROR_BLANK_MESSAGE("error.blank-message", "You cannot send someone a blank message"), + ERROR_RECIPIENT_NOT_EXIST("error.recipient-not-exist", "The user either does not exist, or is not online"), + ERROR_TARGET_CANNOT_RECIEVE_MESSAGE("error.cannot-receive-message", "Sorry, looks like that player cannot receive messages right now"), + ERROR_CANNOT_REPLY("error.cannot-reply", "There is nobody to reply to, sorry. Try /msg [name] instead"), + ERROR_YOUR_MESSAGES_CURRENTLY_DISABLED("error.your-messages-currently-disabled", "Sorry, you cannot send a message to someone while your messages are disabled."), + ERROR_CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED("error.cannot-message-someone-you-blocked", "Sorry, you cannot message someone you currently have blocked."), + ERROR_CANNOT_MESSAGE_CONSOLE("error.cannot-message-console", "Sorry, you cannot message the server"), + ERROR_SOMETHING_WENT_WRONG("error.something-wrong", "Sorry, something went wrong, please check console for more information"), + LOG_ERROR_SOUND_NOT_VALID("console-error.sound-not-valid", "Warning! The sound you have input: '%sound-string%' is invalid! Please be sure you use a sound that is listed on https://jd.papermc.io/paper/1.21.4/org/bukkit/Sound.html"), + LOG_ERROR_USING_DEFAULT_SOUND("console-error.using-default-sound", "Using %default-sound% until a valid sound is provided"), + LOG_ERROR_FLOAT_OUT_OF_RANGE("console-error.float-out-of-range", "The number %number% is out of range! Volume and pitch values must be a number between 0 and 2!"), + LOG_ERROR_USING_DEFAULT_FLOAT("console-error.using-default-float", "Setting to 1.0 until a valid value is provided"); private final String path; private String message; - Message(String path, String message) { + LocaleMessage(String path, String message) { this.path = path; this.message = message; } diff --git a/src/main/java/simplexity/simplepms/events/BlockUserEvent.java b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java new file mode 100644 index 0000000..cdffc64 --- /dev/null +++ b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java @@ -0,0 +1,86 @@ +package simplexity.simplepms.events; + +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nullable; +import java.util.UUID; + +public class BlockUserEvent extends Event implements Cancellable { + private boolean cancelled; + private UUID initiatorUuid; + private UUID blockedPlayerUuid; + private String blockedPlayerName; + private String blockReason; + + private static final HandlerList handlers = new HandlerList(); + + public BlockUserEvent(@NotNull UUID initiatorUuid, @NotNull UUID blockedPlayerUuid, @NotNull String blockedPlayerName, @Nullable String blockReason) { + this.initiatorUuid = initiatorUuid; + this.blockedPlayerUuid = blockedPlayerUuid; + this.blockedPlayerName = blockedPlayerName; + this.blockReason = blockReason; + } + + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public @NotNull HandlerList getHandlers() { + return handlers; + } + + /** + * Gets the handlerList for this event + * + * @return HandlerList + */ + public static HandlerList getHandlerList() { + return handlers; + } + + @NotNull + public UUID getInitiatorUuid() { + return initiatorUuid; + } + + public void setInitiatorUuid(@NotNull UUID initiatorUuid) { + this.initiatorUuid = initiatorUuid; + } + + @NotNull + public UUID getBlockedPlayerUuid() { + return blockedPlayerUuid; + } + + public void setBlockedPlayerUuid(@NotNull UUID blockedPlayerUuid) { + this.blockedPlayerUuid = blockedPlayerUuid; + } + + @NotNull + public String getBlockedPlayerName() { + return blockedPlayerName; + } + + public void setBlockedPlayerName(@NotNull String blockedPlayerName) { + this.blockedPlayerName = blockedPlayerName; + } + + @Nullable + public String getBlockReason() { + return blockReason; + } + + public void setBlockReason(@Nullable String blockReason) { + this.blockReason = blockReason; + } +} diff --git a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java index cd85e46..72573d1 100644 --- a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java +++ b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java @@ -18,11 +18,11 @@ public class PrivateMessageEvent extends Event implements Cancellable { private CommandSender initiator; private CommandSender recipient; private String messageContent; - private Set spyingPlayers; + private final Set spyingPlayers; private boolean cancelled; private static final HandlerList handlers = new HandlerList(); - public PrivateMessageEvent(CommandSender initiator, CommandSender recipient, String messageContent, Set spyingPlayers) { + public PrivateMessageEvent(@NotNull CommandSender initiator, @NotNull CommandSender recipient, @NotNull String messageContent, @NotNull Set spyingPlayers) { this.initiator = initiator; this.recipient = recipient; this.messageContent = messageContent; diff --git a/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java new file mode 100644 index 0000000..fb09daa --- /dev/null +++ b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java @@ -0,0 +1,61 @@ +package simplexity.simplepms.events; + +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; + +public class UnblockUserEvent extends Event implements Cancellable { + private boolean cancelled; + private UUID initiatorUuid; + private UUID blockedPlayerUuid; + private static final HandlerList handlers = new HandlerList(); + + public UnblockUserEvent(UUID initiatorUuid, UUID blockedPlayerUuid){ + this.initiatorUuid = initiatorUuid; + this.blockedPlayerUuid = blockedPlayerUuid; + } + + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public @NotNull HandlerList getHandlers() { + return handlers; + } + + /** + * Gets the handlerList for this event + * + * @return HandlerList + */ + public static HandlerList getHandlerList() { + return handlers; + } + + public UUID getInitiatorUuid() { + return initiatorUuid; + } + + public void setInitiatorUuid(UUID initiatorUuid) { + this.initiatorUuid = initiatorUuid; + } + + public UUID getBlockedPlayerUuid() { + return blockedPlayerUuid; + } + + public void setBlockedPlayerUuid(UUID blockedPlayerUuid) { + this.blockedPlayerUuid = blockedPlayerUuid; + } + +} diff --git a/src/main/java/simplexity/simplepms/logic/BlockHandler.java b/src/main/java/simplexity/simplepms/logic/BlockHandler.java new file mode 100644 index 0000000..7bda545 --- /dev/null +++ b/src/main/java/simplexity/simplepms/logic/BlockHandler.java @@ -0,0 +1,36 @@ +package simplexity.simplepms.logic; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.events.BlockUserEvent; +import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.saving.Cache; + +import javax.annotation.Nullable; + +public class BlockHandler { + + public static void addBlockedPlayer(@NotNull Player blockingPlayer, @NotNull OfflinePlayer playerToBlock, @Nullable String reason) { + BlockUserEvent blockUserEvent = callBlockEvent(blockingPlayer, playerToBlock, reason); + if (blockUserEvent.isCancelled()) return; + PlayerBlock playerBlock = new PlayerBlock( + blockUserEvent.getInitiatorUuid(), + blockUserEvent.getBlockedPlayerName(), + blockUserEvent.getBlockedPlayerUuid(), + blockUserEvent.getBlockReason()); + Cache.addBlockedUser(blockingPlayer.getUniqueId(), playerBlock); + } + + private static BlockUserEvent callBlockEvent(@NotNull Player blockingPlayer, @NotNull OfflinePlayer playerToBlock, @Nullable String reason){ + String blockedPlayerName = playerToBlock.getName(); + if (blockedPlayerName == null) blockedPlayerName = "[NO NAME FOUND]"; + BlockUserEvent blockUserEvent = new BlockUserEvent(blockingPlayer.getUniqueId(), playerToBlock.getUniqueId(), blockedPlayerName, reason); + SimplePMs.getInstance().getServer().getPluginManager().callEvent(blockUserEvent); + return blockUserEvent; + } + + +} diff --git a/src/main/java/simplexity/simplepms/logic/MessageUtils.java b/src/main/java/simplexity/simplepms/logic/MessageUtils.java index 16238d2..cdb0053 100644 --- a/src/main/java/simplexity/simplepms/logic/MessageUtils.java +++ b/src/main/java/simplexity/simplepms/logic/MessageUtils.java @@ -13,7 +13,7 @@ import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; public class MessageUtils { private static MessageUtils instance; @@ -49,8 +49,8 @@ public Component parseMessage(String localeMessage, @NotNull CommandSender initi private Component getCommmandSenderComponent(CommandSender sender, boolean socialSpy) { if (!(sender instanceof Player player)) { - if (socialSpy) return miniMessage.deserialize(Message.CONSOLE_NAME_SOCIAL_SPY.getMessage()); - return miniMessage.deserialize(Message.CONSOLE_SENDER_NAME.getMessage()); + if (socialSpy) return miniMessage.deserialize(LocaleMessage.CONSOLE_NAME_SOCIAL_SPY.getMessage()); + return miniMessage.deserialize(LocaleMessage.CONSOLE_SENDER_NAME.getMessage()); } if (!SimplePMs.isPapiEnabled()) { if (socialSpy) return parseName(player, ConfigHandler.getInstance().getSocialSpyFormat()); diff --git a/src/main/java/simplexity/simplepms/logic/PMHandler.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java index d6090c3..e604aa6 100644 --- a/src/main/java/simplexity/simplepms/logic/PMHandler.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -1,12 +1,11 @@ package simplexity.simplepms.logic; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.config.Message; +import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.events.PrivateMessageEvent; import java.util.HashMap; @@ -14,8 +13,12 @@ public class PMHandler { public static final HashMap lastMessaged = new HashMap<>(); - public static void handlePrivateMessage(CommandSender initiator, CommandSender target, String messageContent) throws CommandSyntaxException { + public static void handlePrivateMessage(CommandSender initiator, CommandSender target, String messageContent) { PrivateMessageEvent messageEvent = callPMEvent(initiator, target, messageContent); + if (messageEvent.isCancelled()) return; + initiator = messageEvent.getInitiator(); + target = messageEvent.getRecipient(); + messageContent = messageEvent.getMessageContent(); handleMessageSend(initiator, target, messageContent); handleMessageReceive(initiator, target, messageContent); handleSocialSpy(initiator, target, messageContent); @@ -25,7 +28,7 @@ public static void handlePrivateMessage(CommandSender initiator, CommandSender t private static void handleMessageSend(CommandSender initiator, CommandSender target, String messageContent) { initiator.sendMessage(MessageUtils.getInstance().parseMessage( - Message.FORMAT_SENT.getMessage(), + LocaleMessage.FORMAT_SENT.getMessage(), initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().sendingMessagePlaysSound()) return; if (!(initiator instanceof Player player)) return; @@ -37,7 +40,7 @@ private static void handleMessageSend(CommandSender initiator, CommandSender tar private static void handleMessageReceive(CommandSender initiator, CommandSender target, String messageContent) { target.sendMessage(MessageUtils.getInstance().parseMessage( - Message.FORMAT_RECEIVED.getMessage(), + LocaleMessage.FORMAT_RECEIVED.getMessage(), initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().receivingMessagePlaysSound()) return; if (!(target instanceof Player player)) return; @@ -51,7 +54,7 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender public static void sendCommandSpy(CommandSender initiator, String command, String messageContent) { if (initiator.hasPermission(Constants.BYPASS_COMMAND_SPY)) return; Component parsedMessage = MessageUtils.getInstance().parseMessage( - Message.FORMAT_COMMAND_SPY.getMessage(), initiator, + LocaleMessage.FORMAT_COMMAND_SPY.getMessage(), initiator, command, messageContent, true); for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { if (initiator.equals(spyingPlayer)) continue; @@ -79,7 +82,7 @@ private static void handleSocialSpy(CommandSender initiator, CommandSender targe private static void sendConsoleSpy(CommandSender initiator, CommandSender target, String messageContent) { Component parsedMessage = MessageUtils.getInstance().parseMessage( - Message.FORMAT_SOCIAL_SPY.getMessage(), + LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), initiator, target, messageContent, true); for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { @@ -95,7 +98,7 @@ private static void sendConsoleSpy(CommandSender initiator, CommandSender target private static void sendSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { Component parsedMessage = MessageUtils.getInstance().parseMessage( - Message.FORMAT_SOCIAL_SPY.getMessage(), + LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), initiator, target, messageContent, true); for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { @@ -123,7 +126,6 @@ private static void playSpySound(Player spyingPlayer) { private static PrivateMessageEvent callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, SimplePMs.getSpyingPlayers()); SimplePMs.getInstance().getServer().getPluginManager().callEvent(messageEvent); - if (messageEvent.isCancelled()) return null; return messageEvent; } diff --git a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java new file mode 100644 index 0000000..354db32 --- /dev/null +++ b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java @@ -0,0 +1,38 @@ +package simplexity.simplepms.logic; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.events.UnblockUserEvent; +import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.saving.Cache; + +import java.util.List; +import java.util.UUID; + +public class UnblockHandler { + + public static void removeBlockedPlayer(@NotNull Player blockingPlayer, @NotNull String userToRemove) throws CommandSyntaxException { + List playerBlocks = Cache.getBlockList(blockingPlayer.getUniqueId()); + UUID playerToUnblockUuid = null; + for (PlayerBlock block : playerBlocks) { + if (block.blockedPlayerName().equalsIgnoreCase(userToRemove)) { + playerToUnblockUuid = block.blockedPlayerUUID(); + break; + } + } + if (playerToUnblockUuid == null) throw Exceptions.ERROR_NOT_BLOCKING_ANYONE_BY_THIS_NAME.create(); + UnblockUserEvent unblockEvent = callUnblockEvent(blockingPlayer.getUniqueId(), playerToUnblockUuid); + if (unblockEvent.isCancelled()) return; + Cache.removeBlockedUser(unblockEvent.getInitiatorUuid(), unblockEvent.getBlockedPlayerUuid()); + + } + + private static UnblockUserEvent callUnblockEvent(@NotNull UUID initiatorUuid, @NotNull UUID playerToUnblockUuid) { + UnblockUserEvent unblockEvent = new UnblockUserEvent(initiatorUuid, playerToUnblockUuid); + Bukkit.getServer().getPluginManager().callEvent(unblockEvent); + return unblockEvent; + } +} diff --git a/src/main/java/simplexity/simplepms/saving/Cache.java b/src/main/java/simplexity/simplepms/saving/Cache.java index a83329e..723a6b1 100644 --- a/src/main/java/simplexity/simplepms/saving/Cache.java +++ b/src/main/java/simplexity/simplepms/saving/Cache.java @@ -57,15 +57,16 @@ public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { SqlHandler.getInstance().addBlockedPlayer(uuid, playerBlock.blockedPlayerUUID(), playerBlock.blockReason()); } - public static void removeBlockedUser(UUID uuid, PlayerBlock playerBlock) { - List blockedPlayers = getBlockList(uuid); - blockedPlayers.removeIf(block -> { - UUID blockedUUID = playerBlock.blockedPlayerUUID(); - UUID currentUUID = block.blockedPlayerUUID(); - return currentUUID.equals(blockedUUID); - }); - blockList.put(uuid, blockedPlayers); - SqlHandler.getInstance().removeBlockedPlayer(uuid, playerBlock.blockedPlayerUUID()); + public static void removeBlockedUser(UUID uuid, UUID blockedPlayerUuid) { + List userBlockList = blockList.get(uuid); + for (PlayerBlock block : userBlockList) { + if (block.blockedPlayerUUID().equals(blockedPlayerUuid)) { + userBlockList.remove(block); + break; + } + } + blockList.put(uuid, userBlockList); + SqlHandler.getInstance().removeBlockedPlayer(uuid, blockedPlayerUuid); } } From 6f872d9042d890e55c317b56c7a9085e1fdaf9cc Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Thu, 29 May 2025 16:44:11 -0700 Subject: [PATCH 03/10] Commands are on brig now, aliases do not work --- pom.xml | 2 +- .../java/simplexity/simplepms/SimplePMs.java | 13 ++-- .../simplexity/simplepms/commands/Block.java | 1 + .../simplepms/commands/Blocklist.java | 71 ++++++++++--------- .../simplepms/commands/MessageToggle.java | 52 ++++++++------ .../simplepms/commands/PrivateMessage.java | 3 +- .../simplexity/simplepms/commands/Reload.java | 28 +++++--- .../simplexity/simplepms/commands/Reply.java | 2 + .../simplepms/commands/SocialSpy.java | 54 +++++++------- .../simplepms/commands/Unblock.java | 52 +------------- .../arguments/OfflinePlayerArgument.java | 2 +- .../arguments}/Target.java | 2 +- .../commands/arguments/TargetArgument.java | 4 +- .../suggestions/BlockedUserSuggestions.java | 4 -- .../commands/{ => util}/Exceptions.java | 29 ++------ .../commands/{ => util}/MessageChecks.java | 6 +- .../simplepms/config/LocaleMessage.java | 2 +- .../simplepms/listeners/LoginListener.java | 2 +- .../simplepms/logic/BlockHandler.java | 3 +- .../simplexity/simplepms/logic/Constants.java | 2 - .../simplepms/logic/UnblockHandler.java | 4 +- .../simplexity/simplepms/saving/Cache.java | 4 +- .../simplepms/saving/SqlHandler.java | 4 +- .../{ => saving}/objects/PlayerBlock.java | 2 +- .../{ => saving}/objects/PlayerSettings.java | 4 +- 25 files changed, 152 insertions(+), 200 deletions(-) rename src/main/java/simplexity/simplepms/{objects => commands/arguments}/Target.java (69%) delete mode 100644 src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java rename src/main/java/simplexity/simplepms/commands/{ => util}/Exceptions.java (75%) rename src/main/java/simplexity/simplepms/commands/{ => util}/MessageChecks.java (95%) rename src/main/java/simplexity/simplepms/{ => saving}/objects/PlayerBlock.java (91%) rename src/main/java/simplexity/simplepms/{ => saving}/objects/PlayerSettings.java (92%) diff --git a/pom.xml b/pom.xml index 85d2675..58bca31 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ simplexity SimplePMs - 2.3.1 + 2.3.2 jar SimplePMs diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index 693a051..4b410ce 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -20,7 +20,6 @@ import simplexity.simplepms.listeners.QuitListener; import java.util.HashSet; -import java.util.Objects; import java.util.Set; @SuppressWarnings("UnstableApiUsage") @@ -44,7 +43,6 @@ public static Set getSpyingPlayers() { @Override public void onEnable() { instance = this; - registerCommands(); this.getServer().getPluginManager().registerEvents(new LoginListener(), this); this.getServer().getPluginManager().registerEvents(new QuitListener(), this); this.getServer().getPluginManager().registerEvents(new PreCommandListener(), this); @@ -63,6 +61,10 @@ public void onEnable() { commands.registrar().register(Reply.createCommand()); commands.registrar().register(Block.createCommand()); commands.registrar().register(Unblock.createCommand()); + commands.registrar().register(MessageToggle.createCommand()); + commands.registrar().register(SocialSpy.createCommand()); + commands.registrar().register(Reload.createCommand()); + commands.registrar().register(Blocklist.createCommand()); }); } @@ -82,11 +84,4 @@ public static ConsoleCommandSender getPMConsoleSender() { return consoleSender; } - private void registerCommands() { - Objects.requireNonNull(this.getCommand("socialspy")).setExecutor(new SocialSpy()); - Objects.requireNonNull(this.getCommand("spmreload")).setExecutor(new Reload()); - Objects.requireNonNull(this.getCommand("blocklist")).setExecutor(new Blocklist()); - Objects.requireNonNull(this.getCommand("msgtoggle")).setExecutor(new MessageToggle()); - } - } diff --git a/src/main/java/simplexity/simplepms/commands/Block.java b/src/main/java/simplexity/simplepms/commands/Block.java index 829fc85..6cd3c3a 100644 --- a/src/main/java/simplexity/simplepms/commands/Block.java +++ b/src/main/java/simplexity/simplepms/commands/Block.java @@ -13,6 +13,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.commands.arguments.OfflinePlayerArgument; +import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.BlockHandler; import simplexity.simplepms.logic.Constants; diff --git a/src/main/java/simplexity/simplepms/commands/Blocklist.java b/src/main/java/simplexity/simplepms/commands/Blocklist.java index 5b813cb..9966e21 100644 --- a/src/main/java/simplexity/simplepms/commands/Blocklist.java +++ b/src/main/java/simplexity/simplepms/commands/Blocklist.java @@ -1,49 +1,56 @@ package simplexity.simplepms.commands; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.LocaleMessage; -import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.Cache; +import simplexity.simplepms.saving.objects.PlayerBlock; import java.util.List; import java.util.UUID; -public class Blocklist implements CommandExecutor { +@SuppressWarnings("UnstableApiUsage") +public class Blocklist { - private final MiniMessage miniMessage = SimplePMs.getMiniMessage(); + private static final MiniMessage miniMessage = SimplePMs.getMiniMessage(); - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { - if (!(sender instanceof Player player)) { - sender.sendMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); - return false; - } - UUID uuid = player.getUniqueId(); - List blockList = Cache.getBlockList(uuid); - if (blockList == null || blockList.isEmpty()) { - player.sendRichMessage(LocaleMessage.BLOCKLIST_EMPTY.getMessage()); - return true; - } - Component message = miniMessage.deserialize(LocaleMessage.BLOCKLIST_HEADER.getMessage()); - for (PlayerBlock block : blockList) { - message = message.appendNewline(); - message = message.append(miniMessage.deserialize( - LocaleMessage.BLOCKLIST_NAME.getMessage(), - Placeholder.parsed("name", block.blockedPlayerName()) - )); - if (block.blockReason() == null || block.blockReason().isEmpty()) continue; - message = message.append(miniMessage.deserialize(LocaleMessage.BLOCKLIST_REASON.getMessage(), - Placeholder.parsed("reason", block.blockReason()))); - } - sender.sendMessage(message); - return true; + public static LiteralCommandNode createCommand() { + return Commands.literal("blocklist") + .requires(Blocklist::canExecute) + .executes(ctx -> { + Player player = (Player) ctx.getSource().getSender(); + UUID uuid = player.getUniqueId(); + List blockList = Cache.getBlockList(uuid); + if (blockList == null || blockList.isEmpty()) { + player.sendRichMessage(LocaleMessage.BLOCKLIST_EMPTY.getMessage()); + return Command.SINGLE_SUCCESS; + } + Component message = miniMessage.deserialize(LocaleMessage.BLOCKLIST_HEADER.getMessage()); + for (PlayerBlock block : blockList) { + message = message.appendNewline(); + message = message.append(miniMessage.deserialize( + LocaleMessage.BLOCKLIST_NAME.getMessage(), + Placeholder.parsed("name", block.blockedPlayerName()) + )); + if (block.blockReason() == null || block.blockReason().isEmpty()) continue; + message = message.append(miniMessage.deserialize(LocaleMessage.BLOCKLIST_REASON.getMessage(), + Placeholder.parsed("reason", block.blockReason()))); + } + player.sendMessage(message); + return Command.SINGLE_SUCCESS; + }).build(); + } + + private static boolean canExecute(CommandSourceStack css) { + if (!(css.getSender() instanceof Player)) return false; + return css.getSender().hasPermission(Constants.MESSAGE_BLOCK); } } diff --git a/src/main/java/simplexity/simplepms/commands/MessageToggle.java b/src/main/java/simplexity/simplepms/commands/MessageToggle.java index 9ec70c0..381d0d8 100644 --- a/src/main/java/simplexity/simplepms/commands/MessageToggle.java +++ b/src/main/java/simplexity/simplepms/commands/MessageToggle.java @@ -1,32 +1,40 @@ package simplexity.simplepms.commands; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import simplexity.simplepms.config.LocaleMessage; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.Cache; +import simplexity.simplepms.saving.objects.PlayerSettings; import java.util.UUID; -public class MessageToggle implements CommandExecutor { - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { - if (!(sender instanceof Player player)) { - sender.sendRichMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); - return false; - } - UUID uuid = player.getUniqueId(); - PlayerSettings playerSettings = Cache.getPlayerSettings(uuid); - if (playerSettings.areMessagesDisabled()) { - Cache.updateMessageSettings(uuid, false); - player.sendRichMessage(LocaleMessage.MESSAGES_ENABLED.getMessage()); - return true; - } - Cache.updateMessageSettings(uuid, true); - player.sendRichMessage(LocaleMessage.MESSAGES_DISABLED.getMessage()); - return true; +@SuppressWarnings("UnstableApiUsage") +public class MessageToggle { + + public static LiteralCommandNode createCommand() { + return Commands.literal("msgtoggle") + .requires(MessageToggle::canExecute) + .executes(ctx -> { + Player sender = (Player) ctx.getSource().getSender(); + UUID playerUuid = sender.getUniqueId(); + PlayerSettings playerSettings = Cache.getPlayerSettings(playerUuid); + if (playerSettings.areMessagesDisabled()) { + Cache.updateMessageSettings(playerUuid, false); + sender.sendRichMessage(LocaleMessage.MESSAGES_ENABLED.getMessage()); + return Command.SINGLE_SUCCESS; + } + Cache.updateMessageSettings(playerUuid, true); + sender.sendRichMessage(LocaleMessage.MESSAGES_DISABLED.getMessage()); + return Command.SINGLE_SUCCESS; + }).build(); + } + + public static boolean canExecute(CommandSourceStack css) { + if (!(css.getSender() instanceof Player)) return false; + return css.getSender().hasPermission(Constants.MESSAGE_TOGGLE); } } diff --git a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java index f08dc63..a223863 100644 --- a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java +++ b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java @@ -9,9 +9,10 @@ import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; import simplexity.simplepms.commands.arguments.TargetArgument; +import simplexity.simplepms.commands.util.MessageChecks; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.PMHandler; -import simplexity.simplepms.objects.Target; +import simplexity.simplepms.commands.arguments.Target; @SuppressWarnings("UnstableApiUsage") public class PrivateMessage { diff --git a/src/main/java/simplexity/simplepms/commands/Reload.java b/src/main/java/simplexity/simplepms/commands/Reload.java index 1426688..eaa94d7 100644 --- a/src/main/java/simplexity/simplepms/commands/Reload.java +++ b/src/main/java/simplexity/simplepms/commands/Reload.java @@ -1,19 +1,25 @@ package simplexity.simplepms.commands; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.LocaleMessage; +import simplexity.simplepms.logic.Constants; -public class Reload implements CommandExecutor { - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - ConfigHandler.getInstance().loadConfigValues(); - sender.sendRichMessage(LocaleMessage.RELOADED.getMessage()); - return true; - } - +@SuppressWarnings("UnstableApiUsage") +public class Reload { + public static LiteralCommandNode createCommand() { + return Commands.literal("spmreload") + .requires(css -> css.getSender().hasPermission(Constants.RELOAD)) + .executes(ctx -> { + CommandSender sender = ctx.getSource().getSender(); + ConfigHandler.getInstance().loadConfigValues(); + sender.sendRichMessage(LocaleMessage.RELOADED.getMessage()); + return Command.SINGLE_SUCCESS; + }).build(); + } } diff --git a/src/main/java/simplexity/simplepms/commands/Reply.java b/src/main/java/simplexity/simplepms/commands/Reply.java index 9c9da5a..8baca00 100644 --- a/src/main/java/simplexity/simplepms/commands/Reply.java +++ b/src/main/java/simplexity/simplepms/commands/Reply.java @@ -8,6 +8,8 @@ import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; +import simplexity.simplepms.commands.util.Exceptions; +import simplexity.simplepms.commands.util.MessageChecks; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.PMHandler; diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index 53968b8..844af3a 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -1,39 +1,45 @@ package simplexity.simplepms.commands; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.tree.LiteralCommandNode; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import io.papermc.paper.command.brigadier.Commands; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.LocaleMessage; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.Cache; import simplexity.simplepms.saving.SqlHandler; +import simplexity.simplepms.saving.objects.PlayerSettings; import java.util.UUID; -public class SocialSpy implements CommandExecutor { +@SuppressWarnings("UnstableApiUsage") +public class SocialSpy { + public static LiteralCommandNode createCommand(){ + return Commands.literal("socialspy") + .requires(SocialSpy::canExecute) + .executes(ctx -> { + Player player = (Player) ctx.getSource().getSender(); + UUID uuid = player.getUniqueId(); + PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); + if (settings == null || settings.isSocialSpyEnabled()) { + Cache.updateSocialSpySettings(uuid, false); + player.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); + SimplePMs.getSpyingPlayers().remove(player); + return Command.SINGLE_SUCCESS; + } + Cache.updateSocialSpySettings(uuid, true); + player.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); + SimplePMs.getSpyingPlayers().add(player); + return Command.SINGLE_SUCCESS; + }).build(); + } - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (!(sender instanceof Player player)) { - sender.sendRichMessage(LocaleMessage.ERROR_NOT_A_PLAYER.getMessage()); - return false; - } - UUID uuid = player.getUniqueId(); - PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); - if (settings == null || settings.isSocialSpyEnabled()) { - Cache.updateSocialSpySettings(uuid, false); - sender.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); - SimplePMs.getSpyingPlayers().remove(player); - return true; - } - Cache.updateSocialSpySettings(uuid, true); - sender.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); - SimplePMs.getSpyingPlayers().add(player); - return true; + private static boolean canExecute(CommandSourceStack css){ + if (!(css.getSender() instanceof Player)) return false; + return css.getSender().hasPermission(Constants.ADMIN_SOCIAL_SPY); } } diff --git a/src/main/java/simplexity/simplepms/commands/Unblock.java b/src/main/java/simplexity/simplepms/commands/Unblock.java index c77e065..e06f8cb 100644 --- a/src/main/java/simplexity/simplepms/commands/Unblock.java +++ b/src/main/java/simplexity/simplepms/commands/Unblock.java @@ -14,10 +14,11 @@ import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.UnblockHandler; -import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; import java.util.List; @@ -67,53 +68,4 @@ private static CompletableFuture suggestBlockedUsers(final CommandC } return builder.buildFuture(); } - - - - /* - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { - if (!(sender instanceof Player player)) { - sender.sendRichMessage(Message.ERROR_NOT_A_PLAYER.getMessage()); - return false; - } - if (args.length == 0) { - player.sendRichMessage(Message.ERROR_NO_USER_PROVIDED.getMessage()); - return false; - } - String blockString = args[0]; - List playerBlockList = Cache.getBlockList(player.getUniqueId()); - PlayerBlock blockedPlayer = getBlockedPlayer(blockString, playerBlockList); - if (blockedPlayer == null) { - player.sendRichMessage(Message.PLAYER_NOT_BLOCKED.getMessage()); - return false; - } - Cache.removeBlockedUser(player.getUniqueId(), blockedPlayer.blockedPlayerUUID()); - player.sendRichMessage(Message.NO_LONGER_BLOCKING.getMessage(), - Placeholder.parsed("name", blockString)); - return true; - } - - private PlayerBlock getBlockedPlayer(String playerBlocked, List playerBlockList) { - for (PlayerBlock playerBlock : playerBlockList) { - if (playerBlock.blockedPlayerName().equals(playerBlocked)) { - return playerBlock; - } - } - return null; - } - - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { - if (!(sender instanceof Player player)) { - return null; - } - ArrayList blocked = new ArrayList<>(); - for (PlayerBlock block : Cache.getBlockList(player.getUniqueId())) { - blocked.add(block.blockedPlayerName()); - } - return blocked; - } - - */ } diff --git a/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java index cda8efe..739c221 100644 --- a/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java +++ b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java @@ -15,7 +15,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.config.ConfigHandler; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/simplexity/simplepms/objects/Target.java b/src/main/java/simplexity/simplepms/commands/arguments/Target.java similarity index 69% rename from src/main/java/simplexity/simplepms/objects/Target.java rename to src/main/java/simplexity/simplepms/commands/arguments/Target.java index 9a2fb12..52d6abd 100644 --- a/src/main/java/simplexity/simplepms/objects/Target.java +++ b/src/main/java/simplexity/simplepms/commands/arguments/Target.java @@ -1,4 +1,4 @@ -package simplexity.simplepms.objects; +package simplexity.simplepms.commands.arguments; import org.bukkit.command.CommandSender; diff --git a/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java index 88f7490..0760243 100644 --- a/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java +++ b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java @@ -10,15 +10,13 @@ import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.MessageComponentSerializer; import io.papermc.paper.command.brigadier.argument.CustomArgumentType; -import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.objects.Target; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java b/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java deleted file mode 100644 index aa0243e..0000000 --- a/src/main/java/simplexity/simplepms/commands/suggestions/BlockedUserSuggestions.java +++ /dev/null @@ -1,4 +0,0 @@ -package simplexity.simplepms.commands.suggestions; - -public class BlockedUserSuggestions { -} diff --git a/src/main/java/simplexity/simplepms/commands/Exceptions.java b/src/main/java/simplexity/simplepms/commands/util/Exceptions.java similarity index 75% rename from src/main/java/simplexity/simplepms/commands/Exceptions.java rename to src/main/java/simplexity/simplepms/commands/util/Exceptions.java index 69b3a37..e696907 100644 --- a/src/main/java/simplexity/simplepms/commands/Exceptions.java +++ b/src/main/java/simplexity/simplepms/commands/util/Exceptions.java @@ -1,4 +1,4 @@ -package simplexity.simplepms.commands; +package simplexity.simplepms.commands.util; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; @@ -13,30 +13,13 @@ public class Exceptions { private static final MiniMessage miniMessage = SimplePMs.getMiniMessage(); - public static final SimpleCommandExceptionType ERROR_EMPTY_MESSAGE = new SimpleCommandExceptionType( + public static final DynamicCommandExceptionType ERROR_INVALID_USER = new DynamicCommandExceptionType(input -> MessageComponentSerializer.message().serialize( miniMessage.deserialize( - LocaleMessage.ERROR_BLANK_MESSAGE.getMessage() + LocaleMessage.ERROR_RECIPIENT_NOT_EXIST.getMessage(), + Placeholder.unparsed("name", input.toString()) ) - ) - ); - - public static final SimpleCommandExceptionType ERROR_NO_PERMISSION = new SimpleCommandExceptionType( - MessageComponentSerializer.message().serialize( - miniMessage.deserialize( - LocaleMessage.ERROR_NO_PERMISSION.getMessage() - ) - ) - ); - - public static final DynamicCommandExceptionType ERROR_INVALID_USER = new DynamicCommandExceptionType(input -> { - return MessageComponentSerializer.message().serialize( - miniMessage.deserialize( - LocaleMessage.ERROR_RECIPIENT_NOT_EXIST.getMessage(), - Placeholder.unparsed("name", input.toString()) - ) - ); - }); + )); public static final SimpleCommandExceptionType ERROR_YOUR_MESSAGES_ARE_DISABLED = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( @@ -49,7 +32,7 @@ public class Exceptions { public static final SimpleCommandExceptionType ERROR_TARGET_CANNOT_RECEIVE_MESSAGE = new SimpleCommandExceptionType( MessageComponentSerializer.message().serialize( miniMessage.deserialize( - LocaleMessage.ERROR_TARGET_CANNOT_RECIEVE_MESSAGE.getMessage() + LocaleMessage.ERROR_TARGET_CANNOT_RECEIVE_MESSAGE.getMessage() ) ) ); diff --git a/src/main/java/simplexity/simplepms/commands/MessageChecks.java b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java similarity index 95% rename from src/main/java/simplexity/simplepms/commands/MessageChecks.java rename to src/main/java/simplexity/simplepms/commands/util/MessageChecks.java index c422099..6688e38 100644 --- a/src/main/java/simplexity/simplepms/commands/MessageChecks.java +++ b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java @@ -1,12 +1,12 @@ -package simplexity.simplepms.commands; +package simplexity.simplepms.commands.util; import com.mojang.brigadier.exceptions.CommandSyntaxException; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.logic.Constants; -import simplexity.simplepms.objects.PlayerBlock; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.saving.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerSettings; import simplexity.simplepms.saving.Cache; import java.util.List; diff --git a/src/main/java/simplexity/simplepms/config/LocaleMessage.java b/src/main/java/simplexity/simplepms/config/LocaleMessage.java index 3b98bcf..ab0d88c 100644 --- a/src/main/java/simplexity/simplepms/config/LocaleMessage.java +++ b/src/main/java/simplexity/simplepms/config/LocaleMessage.java @@ -25,7 +25,7 @@ public enum LocaleMessage { ERROR_NO_USER_PROVIDED("error.no-user-provided", "You must provide a valid user"), ERROR_BLANK_MESSAGE("error.blank-message", "You cannot send someone a blank message"), ERROR_RECIPIENT_NOT_EXIST("error.recipient-not-exist", "The user either does not exist, or is not online"), - ERROR_TARGET_CANNOT_RECIEVE_MESSAGE("error.cannot-receive-message", "Sorry, looks like that player cannot receive messages right now"), + ERROR_TARGET_CANNOT_RECEIVE_MESSAGE("error.cannot-receive-message", "Sorry, looks like that player cannot receive messages right now"), ERROR_CANNOT_REPLY("error.cannot-reply", "There is nobody to reply to, sorry. Try /msg [name] instead"), ERROR_YOUR_MESSAGES_CURRENTLY_DISABLED("error.your-messages-currently-disabled", "Sorry, you cannot send a message to someone while your messages are disabled."), ERROR_CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED("error.cannot-message-someone-you-blocked", "Sorry, you cannot message someone you currently have blocked."), diff --git a/src/main/java/simplexity/simplepms/listeners/LoginListener.java b/src/main/java/simplexity/simplepms/listeners/LoginListener.java index 1cad10a..023128f 100644 --- a/src/main/java/simplexity/simplepms/listeners/LoginListener.java +++ b/src/main/java/simplexity/simplepms/listeners/LoginListener.java @@ -5,7 +5,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.saving.objects.PlayerSettings; import simplexity.simplepms.saving.SqlHandler; public class LoginListener implements Listener { diff --git a/src/main/java/simplexity/simplepms/logic/BlockHandler.java b/src/main/java/simplexity/simplepms/logic/BlockHandler.java index 7bda545..c8c6217 100644 --- a/src/main/java/simplexity/simplepms/logic/BlockHandler.java +++ b/src/main/java/simplexity/simplepms/logic/BlockHandler.java @@ -1,12 +1,11 @@ package simplexity.simplepms.logic; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.events.BlockUserEvent; -import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; import javax.annotation.Nullable; diff --git a/src/main/java/simplexity/simplepms/logic/Constants.java b/src/main/java/simplexity/simplepms/logic/Constants.java index 7c4dd65..402537d 100644 --- a/src/main/java/simplexity/simplepms/logic/Constants.java +++ b/src/main/java/simplexity/simplepms/logic/Constants.java @@ -3,13 +3,11 @@ import org.bukkit.permissions.Permission; public class Constants { - public static Permission MESSAGE_BASIC = new Permission("message.basic"); public static Permission MESSAGE_SEND = new Permission("message.basic.send"); public static Permission MESSAGE_RECEIVE = new Permission("message.basic.receive"); public static Permission MESSAGE_TOGGLE = new Permission("message.basic.toggle"); public static Permission MESSAGE_BLOCK = new Permission("message.basic.block"); public static Permission RELOAD = new Permission("message.reload"); - public static Permission MESSAGE_ADMIN = new Permission("message.admin"); public static Permission ADMIN_OVERRIDE = new Permission("message.admin.override"); public static Permission ADMIN_SOCIAL_SPY = new Permission("message.admin.social-spy"); public static Permission ADMIN_CONSOLE_SPY = new Permission("message.admin.console-spy"); diff --git a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java index 354db32..c2a5e3b 100644 --- a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java +++ b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java @@ -4,9 +4,9 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import simplexity.simplepms.commands.Exceptions; +import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.events.UnblockUserEvent; -import simplexity.simplepms.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; import java.util.List; diff --git a/src/main/java/simplexity/simplepms/saving/Cache.java b/src/main/java/simplexity/simplepms/saving/Cache.java index 723a6b1..4da44e8 100644 --- a/src/main/java/simplexity/simplepms/saving/Cache.java +++ b/src/main/java/simplexity/simplepms/saving/Cache.java @@ -1,7 +1,7 @@ package simplexity.simplepms.saving; -import simplexity.simplepms.objects.PlayerBlock; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.saving.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerSettings; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index 3bd86e0..7162db7 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -3,8 +3,8 @@ import org.bukkit.Bukkit; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.objects.PlayerBlock; -import simplexity.simplepms.objects.PlayerSettings; +import simplexity.simplepms.saving.objects.PlayerBlock; +import simplexity.simplepms.saving.objects.PlayerSettings; import java.sql.Connection; import java.sql.DriverManager; diff --git a/src/main/java/simplexity/simplepms/objects/PlayerBlock.java b/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java similarity index 91% rename from src/main/java/simplexity/simplepms/objects/PlayerBlock.java rename to src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java index 8bc5292..737ff54 100644 --- a/src/main/java/simplexity/simplepms/objects/PlayerBlock.java +++ b/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java @@ -1,4 +1,4 @@ -package simplexity.simplepms.objects; +package simplexity.simplepms.saving.objects; import java.util.UUID; diff --git a/src/main/java/simplexity/simplepms/objects/PlayerSettings.java b/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java similarity index 92% rename from src/main/java/simplexity/simplepms/objects/PlayerSettings.java rename to src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java index 4bde586..8a1e62f 100644 --- a/src/main/java/simplexity/simplepms/objects/PlayerSettings.java +++ b/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java @@ -1,8 +1,8 @@ -package simplexity.simplepms.objects; +package simplexity.simplepms.saving.objects; import java.util.UUID; -@SuppressWarnings("StringTemplateMigration") +@SuppressWarnings({"StringTemplateMigration", "unused"}) public final class PlayerSettings { private final UUID playerUUID; private boolean socialSpyEnabled; From 7c08b99878f105f127ee11e56a6ccc03f5c0b238 Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Fri, 30 May 2025 17:58:09 -0700 Subject: [PATCH 04/10] Fix up SQL handler, Fix up Cache, make it so that users aren't permanantly in Cache, add aliases --- pom.xml | 5 + .../java/simplexity/simplepms/SimplePMs.java | 9 +- .../simplepms/commands/PrivateMessage.java | 34 ++++- .../simplexity/simplepms/commands/Reply.java | 16 +- .../simplepms/commands/SocialSpy.java | 42 +++--- .../simplepms/listeners/LoginListener.java | 7 +- .../simplepms/listeners/QuitListener.java | 4 +- .../simplepms/logic/MessageUtils.java | 15 -- .../simplexity/simplepms/saving/Cache.java | 53 ++++--- .../simplepms/saving/SqlHandler.java | 141 ++++++++---------- src/main/resources/plugin.yml | 28 ---- 11 files changed, 180 insertions(+), 174 deletions(-) diff --git a/pom.xml b/pom.xml index 58bca31..cd4e89f 100644 --- a/pom.xml +++ b/pom.xml @@ -90,5 +90,10 @@ 2.11.6 provided + + com.zaxxer + HikariCP + 6.3.0 + diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index 4b410ce..a351b54 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -28,13 +28,10 @@ public final class SimplePMs extends JavaPlugin { private static Plugin instance; private static final MiniMessage miniMessage = MiniMessage.miniMessage(); private static boolean papiEnabled = false; - private static final HashSet players = new HashSet<>(); private static final HashSet spyingPlayers = new HashSet<>(); private static ConsoleCommandSender consoleSender; - public static HashSet getPlayers() { - return players; - } + public static Set getSpyingPlayers() { return spyingPlayers; @@ -58,11 +55,15 @@ public void onEnable() { ConfigHandler.getInstance().loadConfigValues(); this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { commands.registrar().register(PrivateMessage.createCommand()); + commands.registrar().register(PrivateMessage.createTellAlias()); + commands.registrar().register(PrivateMessage.createWhisperAlias()); commands.registrar().register(Reply.createCommand()); + commands.registrar().register(Reply.createAlias()); commands.registrar().register(Block.createCommand()); commands.registrar().register(Unblock.createCommand()); commands.registrar().register(MessageToggle.createCommand()); commands.registrar().register(SocialSpy.createCommand()); + commands.registrar().register(SocialSpy.createAlias()); commands.registrar().register(Reload.createCommand()); commands.registrar().register(Blocklist.createCommand()); }); diff --git a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java index a223863..77ba420 100644 --- a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java +++ b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java @@ -2,6 +2,7 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; @@ -19,14 +20,35 @@ public class PrivateMessage { public static LiteralCommandNode createCommand() { - TargetArgument targetArg = new TargetArgument(); - return Commands.literal("msg") .requires(PrivateMessage::canExecute) - .then(Commands.argument("target", targetArg) - .suggests(targetArg::suggestOnlinePlayers) - .then(Commands.argument("message", StringArgumentType.greedyString()) - .executes(PrivateMessage::execute))).build(); + .then(targetArg() + .then(messageArg())).build(); + } + + public static LiteralCommandNode createTellAlias() { + return Commands.literal("tell") + .requires(PrivateMessage::canExecute) + .then(targetArg() + .then(messageArg())).build(); + } + + public static LiteralCommandNode createWhisperAlias() { + return Commands.literal("w") + .requires(PrivateMessage::canExecute) + .then(targetArg() + .then(messageArg())).build(); + } + + private static RequiredArgumentBuilder targetArg(){ + TargetArgument targetArg = new TargetArgument(); + return Commands.argument("target", targetArg) + .suggests(targetArg::suggestOnlinePlayers); + } + + private static RequiredArgumentBuilder messageArg() { + return Commands.argument("message", StringArgumentType.greedyString()) + .executes(PrivateMessage::execute); } private static boolean canExecute(CommandSourceStack css) { diff --git a/src/main/java/simplexity/simplepms/commands/Reply.java b/src/main/java/simplexity/simplepms/commands/Reply.java index 8baca00..4b386d2 100644 --- a/src/main/java/simplexity/simplepms/commands/Reply.java +++ b/src/main/java/simplexity/simplepms/commands/Reply.java @@ -2,6 +2,7 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; @@ -17,17 +18,26 @@ public class Reply { public static LiteralCommandNode createCommand() { - return Commands.literal("reply") .requires(Reply::canExecute) - .then(Commands.argument("message", StringArgumentType.greedyString()) - .executes(Reply::execute)).build(); + .then(messageArg()).build(); + } + + public static LiteralCommandNode createAlias() { + return Commands.literal("r") + .requires(Reply::canExecute) + .then(messageArg()).build(); } private static boolean canExecute(CommandSourceStack css) { return css.getSender().hasPermission(Constants.MESSAGE_SEND); } + private static RequiredArgumentBuilder messageArg() { + return Commands.argument("message", StringArgumentType.greedyString()) + .executes(Reply::execute); + } + private static int execute(CommandContext ctx) throws CommandSyntaxException { CommandSender sender = ctx.getSource().getSender(); CommandSender target = PMHandler.lastMessaged.get(sender); diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index 844af3a..a3991a3 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -1,6 +1,7 @@ package simplexity.simplepms.commands; import com.mojang.brigadier.Command; +import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.tree.LiteralCommandNode; import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; @@ -9,32 +10,23 @@ import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.Cache; -import simplexity.simplepms.saving.SqlHandler; import simplexity.simplepms.saving.objects.PlayerSettings; import java.util.UUID; -@SuppressWarnings("UnstableApiUsage") +@SuppressWarnings({"UnstableApiUsage", "SameReturnValue"}) public class SocialSpy { public static LiteralCommandNode createCommand(){ return Commands.literal("socialspy") .requires(SocialSpy::canExecute) - .executes(ctx -> { - Player player = (Player) ctx.getSource().getSender(); - UUID uuid = player.getUniqueId(); - PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); - if (settings == null || settings.isSocialSpyEnabled()) { - Cache.updateSocialSpySettings(uuid, false); - player.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); - SimplePMs.getSpyingPlayers().remove(player); - return Command.SINGLE_SUCCESS; - } - Cache.updateSocialSpySettings(uuid, true); - player.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); - SimplePMs.getSpyingPlayers().add(player); - return Command.SINGLE_SUCCESS; - }).build(); + .executes(SocialSpy::execute).build(); + } + + public static LiteralCommandNode createAlias(){ + return Commands.literal("ss") + .requires(SocialSpy::canExecute) + .executes(SocialSpy::execute).build(); } private static boolean canExecute(CommandSourceStack css){ @@ -42,4 +34,20 @@ private static boolean canExecute(CommandSourceStack css){ return css.getSender().hasPermission(Constants.ADMIN_SOCIAL_SPY); } + private static int execute(CommandContext ctx) { + Player player = (Player) ctx.getSource().getSender(); + UUID uuid = player.getUniqueId(); + PlayerSettings settings = Cache.getPlayerSettings(uuid); + if (settings == null || settings.isSocialSpyEnabled()) { + Cache.updateSocialSpySettings(uuid, false); + player.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); + SimplePMs.getSpyingPlayers().remove(player); + return Command.SINGLE_SUCCESS; + } + Cache.updateSocialSpySettings(uuid, true); + player.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); + SimplePMs.getSpyingPlayers().add(player); + return Command.SINGLE_SUCCESS; + } + } diff --git a/src/main/java/simplexity/simplepms/listeners/LoginListener.java b/src/main/java/simplexity/simplepms/listeners/LoginListener.java index 023128f..3fae3cf 100644 --- a/src/main/java/simplexity/simplepms/listeners/LoginListener.java +++ b/src/main/java/simplexity/simplepms/listeners/LoginListener.java @@ -5,19 +5,20 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.saving.Cache; import simplexity.simplepms.saving.objects.PlayerSettings; -import simplexity.simplepms.saving.SqlHandler; public class LoginListener implements Listener { @EventHandler public void onLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); - PlayerSettings playerSettings = SqlHandler.getInstance().getSettings(player.getUniqueId()); + Cache.addPlayerSettingsToCache(player.getUniqueId()); + Cache.addBlockListToCache(player.getUniqueId()); + PlayerSettings playerSettings = Cache.getPlayerSettings(player.getUniqueId()); if (playerSettings.isSocialSpyEnabled()) { SimplePMs.getSpyingPlayers().add(player); } - SimplePMs.getPlayers().add(player); } } diff --git a/src/main/java/simplexity/simplepms/listeners/QuitListener.java b/src/main/java/simplexity/simplepms/listeners/QuitListener.java index 229a684..7b32ccc 100644 --- a/src/main/java/simplexity/simplepms/listeners/QuitListener.java +++ b/src/main/java/simplexity/simplepms/listeners/QuitListener.java @@ -4,12 +4,14 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.saving.Cache; public class QuitListener implements Listener { @EventHandler public void onQuit(PlayerQuitEvent e) { SimplePMs.getSpyingPlayers().remove(e.getPlayer()); - SimplePMs.getPlayers().remove(e.getPlayer()); + Cache.removeBlockListFromCache(e.getPlayer().getUniqueId()); + Cache.removePlayerSettingsFromCache(e.getPlayer().getUniqueId()); } } diff --git a/src/main/java/simplexity/simplepms/logic/MessageUtils.java b/src/main/java/simplexity/simplepms/logic/MessageUtils.java index cdb0053..7cbbe04 100644 --- a/src/main/java/simplexity/simplepms/logic/MessageUtils.java +++ b/src/main/java/simplexity/simplepms/logic/MessageUtils.java @@ -7,7 +7,6 @@ import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -94,18 +93,4 @@ public TagResolver papiTag(final Player player) { }); } - public Player getPlayer(String name) { - Player player; - player = SimplePMs.getInstance().getServer().getPlayer(name); - if (player != null) { - return player; - } - for (Player listedPlayer : SimplePMs.getPlayers()) { - String listedPlayerPlainName = PlainTextComponentSerializer.plainText().serialize(listedPlayer.displayName()); - if (listedPlayerPlainName.equalsIgnoreCase(name)) { - return listedPlayer; - } - } - return null; - } } diff --git a/src/main/java/simplexity/simplepms/saving/Cache.java b/src/main/java/simplexity/simplepms/saving/Cache.java index 4da44e8..a0707af 100644 --- a/src/main/java/simplexity/simplepms/saving/Cache.java +++ b/src/main/java/simplexity/simplepms/saving/Cache.java @@ -13,45 +13,48 @@ public class Cache { public static final HashMap playerSettings = new HashMap<>(); public static List getBlockList(UUID uuid) { - if (blockList.containsKey(uuid)) { - return blockList.get(uuid); - } - List blockedPlayers = SqlHandler.getInstance().getBlockedPlayers(uuid); - blockList.put(uuid, blockedPlayers); - return blockedPlayers; + return blockList.get(uuid); } public static PlayerSettings getPlayerSettings(UUID uuid) { - if (playerSettings.containsKey(uuid)) { - return playerSettings.get(uuid); - } + return playerSettings.get(uuid); + } + + public static void addPlayerSettingsToCache(UUID uuid) { PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); playerSettings.put(uuid, settings); - return settings; + } + + public static void addBlockListToCache(UUID uuid) { + List userBlockList = SqlHandler.getInstance().getBlockedPlayers(uuid); + blockList.put(uuid, userBlockList); + } + + public static void removePlayerSettingsFromCache(UUID uuid){ + playerSettings.remove(uuid); + } + + public static void removeBlockListFromCache(UUID uuid){ + playerSettings.remove(uuid); } public static void updateSocialSpySettings(UUID uuid, boolean socialSpy) { - PlayerSettings settings = getPlayerSettings(uuid); + PlayerSettings settings = playerSettings.get(uuid); settings.setSocialSpyEnabled(socialSpy); playerSettings.put(uuid, settings); - SqlHandler.getInstance().updateSettings(uuid, settings); + SqlHandler.getInstance().updateSettings(uuid, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); } public static void updateMessageSettings(UUID uuid, boolean messageDisabled) { - PlayerSettings settings = getPlayerSettings(uuid); + PlayerSettings settings = playerSettings.get(uuid); settings.setMessagesDisabled(messageDisabled); playerSettings.put(uuid, settings); - SqlHandler.getInstance().updateSettings(uuid, settings); + SqlHandler.getInstance().updateSettings(uuid, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); } public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { - List blockedPlayers = getBlockList(uuid); - if (blockedPlayers == null) blockedPlayers = new ArrayList<>(); - blockedPlayers.removeIf(block -> { - UUID blockedUUID = playerBlock.blockedPlayerUUID(); - UUID currentUUID = block.blockedPlayerUUID(); - return currentUUID.equals(blockedUUID); - }); + removeCachedDuplicates(uuid, playerBlock.blockedPlayerUUID()); + List blockedPlayers = blockList.get(uuid); blockedPlayers.add(playerBlock); blockList.put(uuid, blockedPlayers); SqlHandler.getInstance().addBlockedPlayer(uuid, playerBlock.blockedPlayerUUID(), playerBlock.blockReason()); @@ -69,4 +72,12 @@ public static void removeBlockedUser(UUID uuid, UUID blockedPlayerUuid) { SqlHandler.getInstance().removeBlockedPlayer(uuid, blockedPlayerUuid); } + private static void removeCachedDuplicates(UUID blockingUuid, UUID blockedUuid) { + List blockedPlayers = blockList.get(blockingUuid); + if (blockedPlayers == null) blockedPlayers = new ArrayList<>(); + blockedPlayers.removeIf(block -> + block.blockedPlayerUUID().equals(blockedUuid)); + blockList.put(blockingUuid, blockedPlayers); + } + } diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index 7162db7..2236361 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -1,62 +1,24 @@ package simplexity.simplepms.saving; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; import org.bukkit.Bukkit; +import org.slf4j.Logger; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.objects.PlayerSettings; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import java.util.logging.Logger; -@SuppressWarnings("CallToPrintStackTrace") +@SuppressWarnings({"CallToPrintStackTrace", "SqlResolve"}) public class SqlHandler { - private Connection connection; - private final Logger logger = SimplePMs.getInstance().getLogger(); - private static final String blocklistInitStatement = """ - CREATE TABLE IF NOT EXISTS blocklist ( - player_uuid VARCHAR (36) NOT NULL, - blocked_player_uuid VARCHAR(36) NOT NULL, - block_reason VARCHAR(256), - PRIMARY KEY (player_uuid, blocked_player_uuid) - );"""; - - private static final String settingsInitStatement = """ - CREATE TABLE IF NOT EXISTS settings ( - player_uuid VARCHAR (36) NOT NULL PRIMARY KEY, - socialspy_enabled BOOLEAN NOT NULL, - messages_disabled BOOLEAN NOT NULL - );"""; - - private static final String settingsUpdateStatement = """ - REPLACE INTO settings (player_uuid, socialspy_enabled, messages_disabled) - VALUES (?, ?, ?);"""; - - private static final String settingsSelection = """ - SELECT socialspy_enabled, messages_disabled - FROM settings - WHERE player_uuid = ?;"""; - - private static final String blocklistUpdateStatement = """ - REPLACE INTO blocklist (player_uuid, blocked_player_uuid, block_reason) - VALUES (?, ?, ?);"""; - - private static final String deleteBlockStatement = """ - DELETE FROM blocklist - WHERE player_uuid = ? and blocked_player_uuid = ?;"""; - - private static final String blockSelection = """ - SELECT blocked_player_uuid, block_reason - from blocklist - WHERE player_uuid = ?;"""; private SqlHandler() { } @@ -71,26 +33,43 @@ public static SqlHandler getInstance() { } + private static final HikariConfig hikariConfig = new HikariConfig(); + private static HikariDataSource dataSource; + private final Logger logger = SimplePMs.getInstance().getSLF4JLogger(); + + public void init() { - try { - connection = sqlOrSqlLite(); - try (Statement statement = connection.createStatement()) { - statement.execute(blocklistInitStatement); - statement.execute(settingsInitStatement); - } + setupConfig(); + try (Connection connection = getConnection()) { + PreparedStatement blocklistInitStatement = connection.prepareStatement(""" + CREATE TABLE IF NOT EXISTS blocklist ( + player_uuid VARCHAR (36) NOT NULL, + blocked_player_uuid VARCHAR(36) NOT NULL, + block_reason VARCHAR(256), + PRIMARY KEY (player_uuid, blocked_player_uuid) + );"""); + blocklistInitStatement.execute(); + PreparedStatement playerSettingsInitStatement = connection.prepareStatement(""" + CREATE TABLE IF NOT EXISTS settings ( + player_uuid VARCHAR (36) NOT NULL PRIMARY KEY, + socialspy_enabled BOOLEAN NOT NULL, + messages_disabled BOOLEAN NOT NULL + );"""); + playerSettingsInitStatement.execute(); } catch (SQLException e) { - logger.severe("Failed to connect to database: " + e.getMessage()); - e.printStackTrace(); + logger.warn("Failed to connect to database: {}", e.getMessage(), e); } } public PlayerSettings getSettings(UUID playerUUID) { - try (PreparedStatement statement = connection.prepareStatement(settingsSelection)) { + String queryString = "SELECT socialspy_enabled, messages_disabled FROM settings WHERE player_uuid = ?;"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); try (ResultSet resultSet = statement.executeQuery()) { if (!resultSet.next()) { PlayerSettings settings = new PlayerSettings(playerUUID); - updateSettings(playerUUID, settings); + updateSettings(playerUUID, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); return settings; } else { boolean socialSpy = resultSet.getBoolean("socialspy_enabled"); @@ -99,41 +78,44 @@ public PlayerSettings getSettings(UUID playerUUID) { } } } catch (SQLException e) { - logger.severe("Failed to retrieve settings from database: " + e.getMessage()); - e.printStackTrace(); + logger.warn("Failed to retrieve settings from database: {}", e.getMessage(), e); } return null; } public void addBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID, String reason) { - try (PreparedStatement statement = connection.prepareStatement(blocklistUpdateStatement)) { + String queryString = "REPLACE INTO blocklist (player_uuid, blocked_player_uuid, block_reason) VALUES (?, ?, ?);"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); statement.setString(2, String.valueOf(blockedPlayerUUID)); statement.setString(3, reason); statement.executeUpdate(); } catch (SQLException e) { - logger.severe("Failed to add blocked player: " + e.getMessage()); + logger.warn("Failed to add blocked player: {}", e.getMessage(), e); e.printStackTrace(); } } public void removeBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID) { - try (PreparedStatement statement = connection.prepareStatement(deleteBlockStatement)) { + String queryString = "DELETE FROM blocklist WHERE player_uuid = ? and blocked_player_uuid = ?;"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); statement.setString(2, String.valueOf(blockedPlayerUUID)); statement.executeUpdate(); } catch (SQLException e) { - logger.severe("Failed to remove blocked player: " + e.getMessage()); - e.printStackTrace(); + logger.warn("Failed to remove blocked player: {}", e.getMessage(), e); } } public List getBlockedPlayers(UUID playerUUID) { + String queryString = "SELECT blocked_player_uuid, block_reason from blocklist WHERE player_uuid = ?;"; List blockedPlayers = new ArrayList<>(); - try (PreparedStatement statement = connection.prepareStatement(blockSelection)) { + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); try (ResultSet resultSet = statement.executeQuery()) { - if (!resultSet.next()) return null; while (resultSet.next()) { UUID blockedPlayerUUID = UUID.fromString(resultSet.getString("blocked_player_uuid")); String blockedPlayerName = Bukkit.getOfflinePlayer(blockedPlayerUUID).getName(); @@ -142,32 +124,39 @@ public List getBlockedPlayers(UUID playerUUID) { blockedPlayers.add(block); } } - return blockedPlayers; } catch (SQLException e) { - logger.severe("Failed to get blocked players: " + e.getMessage()); - e.printStackTrace(); + logger.warn("Failed to get blocked players: {}", e.getMessage(), e); } - return null; + return blockedPlayers; } - public void updateSettings(UUID playerUUID, PlayerSettings settings) { - try (PreparedStatement statement = connection.prepareStatement(settingsUpdateStatement)) { + public void updateSettings(UUID playerUUID, boolean socialSpyEnabled, boolean messagesDisabled) { + String queryString = "REPLACE INTO settings (player_uuid, socialspy_enabled, messages_disabled) VALUES (?, ?, ?);"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); - statement.setBoolean(2, settings.isSocialSpyEnabled()); - statement.setBoolean(3, settings.areMessagesDisabled()); + statement.setBoolean(2, socialSpyEnabled); + statement.setBoolean(3, messagesDisabled); statement.executeUpdate(); } catch (SQLException e) { - logger.severe("Failed to update settings to database: " + e.getMessage()); - e.printStackTrace(); + logger.warn("Failed to update settings to database: {}", e.getMessage(), e); } } - private Connection sqlOrSqlLite() throws SQLException { - if (ConfigHandler.getInstance().isMysqlEnabled()) { - return DriverManager.getConnection("jdbc:mysql://" + ConfigHandler.getInstance().getMysqlIp() + "/" + ConfigHandler.getInstance().getMysqlName(), ConfigHandler.getInstance().getMysqlUsername(), ConfigHandler.getInstance().getMysqlPassword()); - } else { - return DriverManager.getConnection("jdbc:sqlite:" + SimplePMs.getInstance().getDataFolder() + "/simple-pms.db"); + private void setupConfig() { + if (!ConfigHandler.getInstance().isMysqlEnabled()) { + hikariConfig.setJdbcUrl("jdbc:sqlite:" + SimplePMs.getInstance().getDataFolder() + "/simple-pms.db"); + dataSource = new HikariDataSource(hikariConfig); + return; } + hikariConfig.setJdbcUrl("jdbc:mysql://" + ConfigHandler.getInstance().getMysqlIp() + "/" + ConfigHandler.getInstance().getMysqlName()); + hikariConfig.setUsername(ConfigHandler.getInstance().getMysqlUsername()); + hikariConfig.setPassword(ConfigHandler.getInstance().getMysqlPassword()); + dataSource = new HikariDataSource(hikariConfig); + } + + private static Connection getConnection() throws SQLException { + return dataSource.getConnection(); } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 6fe8a27..fec4653 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -6,34 +6,6 @@ authors: [ Rhythmic, Peashooter101 ] description: Plugin focused on simple private messaging. softdepend: - PlaceholderAPI -commands: - msg: - description: "Allows the user to send a private message to someone." - aliases: [tell, w] - permission: message.basic.send - msgtoggle: - description: "Toggles direct messages for the user" - permission: message.basic.toggle - reply: - description: "allows the user to reply to a private message" - aliases: [r] - permission: message.basic.send - block: - description: "Blocks a user from direct-messaging you" - permission: message.basic.block - unblock: - description: "Unblocks a user you have blocked" - permission: message.basic.block - blocklist: - description: "Lists the players you have blocked and the reasons" - permission: message.basic.block - socialspy: - description: "toggles socialspy" - aliases: [ss] - permission: message.admin.social-spy - spmreload: - description: "reloads SimplePMs" - permission: message.reload permissions: message.basic: default: true From 25d421979752cf76b41c4cf6ad1a269dacf58027 Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Fri, 30 May 2025 18:19:22 -0700 Subject: [PATCH 05/10] Fixes to social spy --- .../listeners/PreCommandListener.java | 6 +- .../simplepms/logic/MessageUtils.java | 9 +-- .../simplexity/simplepms/logic/PMHandler.java | 77 ++----------------- .../simplepms/logic/SpyHandler.java | 71 +++++++++++++++++ 4 files changed, 81 insertions(+), 82 deletions(-) create mode 100644 src/main/java/simplexity/simplepms/logic/SpyHandler.java diff --git a/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java b/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java index 583e60c..3fb8efa 100644 --- a/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java +++ b/src/main/java/simplexity/simplepms/listeners/PreCommandListener.java @@ -5,10 +5,10 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.logic.PMHandler; +import simplexity.simplepms.logic.SpyHandler; public class PreCommandListener implements Listener { - @EventHandler(priority= EventPriority.MONITOR, ignoreCancelled = true) + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCommand(PlayerCommandPreprocessEvent event) { if (!ConfigHandler.getInstance().isCommandSpyEnabled()) return; @@ -16,6 +16,6 @@ public void onCommand(PlayerCommandPreprocessEvent event) { if (!ConfigHandler.getInstance().getCommandsToSpy().contains(args[0])) return; String command = args[0].toLowerCase(); String message = event.getMessage(); - PMHandler.sendCommandSpy(event.getPlayer(), command, message); + SpyHandler.sendCommandSpy(event.getPlayer(), command, message); } } diff --git a/src/main/java/simplexity/simplepms/logic/MessageUtils.java b/src/main/java/simplexity/simplepms/logic/MessageUtils.java index 7cbbe04..5768281 100644 --- a/src/main/java/simplexity/simplepms/logic/MessageUtils.java +++ b/src/main/java/simplexity/simplepms/logic/MessageUtils.java @@ -46,6 +46,8 @@ public Component parseMessage(String localeMessage, @NotNull CommandSender initi } + + private Component getCommmandSenderComponent(CommandSender sender, boolean socialSpy) { if (!(sender instanceof Player player)) { if (socialSpy) return miniMessage.deserialize(LocaleMessage.CONSOLE_NAME_SOCIAL_SPY.getMessage()); @@ -76,13 +78,6 @@ private Component parsePapiName(Player player, String message) { ); } - public Player getPlayerFromCommandSender(CommandSender sender) { - if (!(sender instanceof Player player)) { - return null; - } - return player; - } - public TagResolver papiTag(final Player player) { if (player == null) return TagResolver.empty(); return TagResolver.resolver("papi", (argumentQueue, context) -> { diff --git a/src/main/java/simplexity/simplepms/logic/PMHandler.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java index e604aa6..b36f0c1 100644 --- a/src/main/java/simplexity/simplepms/logic/PMHandler.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -1,6 +1,5 @@ package simplexity.simplepms.logic; -import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; @@ -21,9 +20,13 @@ public static void handlePrivateMessage(CommandSender initiator, CommandSender t messageContent = messageEvent.getMessageContent(); handleMessageSend(initiator, target, messageContent); handleMessageReceive(initiator, target, messageContent); - handleSocialSpy(initiator, target, messageContent); lastMessaged.put(initiator, target); lastMessaged.put(target, initiator); + if (!(initiator instanceof Player) || !(target instanceof Player)) { + SpyHandler.handleConsoleSpy(messageEvent); + } else { + SpyHandler.handleSocialSpy(messageEvent); + } } private static void handleMessageSend(CommandSender initiator, CommandSender target, String messageContent) { @@ -51,77 +54,7 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender } - public static void sendCommandSpy(CommandSender initiator, String command, String messageContent) { - if (initiator.hasPermission(Constants.BYPASS_COMMAND_SPY)) return; - Component parsedMessage = MessageUtils.getInstance().parseMessage( - LocaleMessage.FORMAT_COMMAND_SPY.getMessage(), initiator, - command, messageContent, true); - for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { - if (initiator.equals(spyingPlayer)) continue; - spyingPlayer.sendMessage(parsedMessage); - playSpySound(spyingPlayer); - } - if (ConfigHandler.getInstance().doesConsoleHaveCommandSpy()) { - sendConsoleMessage(parsedMessage); - } - } - - private static void handleSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { - boolean consoleSpy = false; - Player initiatorPlayer = MessageUtils.getInstance().getPlayerFromCommandSender(initiator); - Player targetPlayer = MessageUtils.getInstance().getPlayerFromCommandSender(target); - if (initiatorPlayer == null || targetPlayer == null) consoleSpy = true; - if (!consoleSpy) { - if (initiatorPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY) || targetPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY)) - return; - sendSocialSpy(initiator, target, messageContent); - } else { - sendConsoleSpy(initiator, target, messageContent); - } - } - - private static void sendConsoleSpy(CommandSender initiator, CommandSender target, String messageContent) { - Component parsedMessage = MessageUtils.getInstance().parseMessage( - LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), - initiator, target, messageContent, - true); - for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { - if (initiator.equals(spyingPlayer) || target.equals(spyingPlayer)) continue; - if (!spyingPlayer.hasPermission(Constants.ADMIN_CONSOLE_SPY)) continue; - spyingPlayer.sendMessage(parsedMessage); - playSpySound(spyingPlayer); - } - if (ConfigHandler.getInstance().doesConsoleHaveSocialSpy()) { - sendConsoleMessage(parsedMessage); - } - } - - private static void sendSocialSpy(CommandSender initiator, CommandSender target, String messageContent) { - Component parsedMessage = MessageUtils.getInstance().parseMessage( - LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), - initiator, target, messageContent, - true); - for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { - if (initiator.equals(spyingPlayer) || target.equals(spyingPlayer)) continue; - spyingPlayer.sendMessage(parsedMessage); - playSpySound(spyingPlayer); - } - if (ConfigHandler.getInstance().doesConsoleHaveSocialSpy()) { - sendConsoleMessage(parsedMessage); - } - } - - private static void sendConsoleMessage(Component message) { - SimplePMs.getPMConsoleSender().sendMessage(message); - } - private static void playSpySound(Player spyingPlayer) { - if (!ConfigHandler.getInstance().messagePlaysSoundForSpy()) return; - spyingPlayer.playSound(spyingPlayer, - ConfigHandler.getInstance().getSpySound(), - ConfigHandler.getInstance().getSpyVolume(), - ConfigHandler.getInstance().getSpyPitch()); - } private static PrivateMessageEvent callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, SimplePMs.getSpyingPlayers()); diff --git a/src/main/java/simplexity/simplepms/logic/SpyHandler.java b/src/main/java/simplexity/simplepms/logic/SpyHandler.java new file mode 100644 index 0000000..e558813 --- /dev/null +++ b/src/main/java/simplexity/simplepms/logic/SpyHandler.java @@ -0,0 +1,71 @@ +package simplexity.simplepms.logic; + +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.config.ConfigHandler; +import simplexity.simplepms.config.LocaleMessage; +import simplexity.simplepms.events.PrivateMessageEvent; + +public class SpyHandler { + + private static final CommandSender console = SimplePMs.getPMConsoleSender(); + + public static void sendCommandSpy(CommandSender initiator, String command, String messageContent) { + Component parsedMessage = MessageUtils.getInstance().parseMessage( + LocaleMessage.FORMAT_COMMAND_SPY.getMessage(), initiator, + command, messageContent, true); + if (ConfigHandler.getInstance().doesConsoleHaveCommandSpy()) { + console.sendMessage(parsedMessage); + } + if (initiator.hasPermission(Constants.BYPASS_COMMAND_SPY)) return; + for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { + if (initiator.equals(spyingPlayer)) continue; + if (!spyingPlayer.hasPermission(Constants.ADMIN_SOCIAL_SPY)) continue; + spyingPlayer.sendMessage(parsedMessage); + playSpySound(spyingPlayer); + } + } + + public static void handleSocialSpy(PrivateMessageEvent messageEvent) { + Player initiatorPlayer = (Player) messageEvent.getInitiator(); + Player targetPlayer = (Player) messageEvent.getRecipient(); + Component parsedMessage = MessageUtils.getInstance().parseMessage( + LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), + initiatorPlayer, targetPlayer, messageEvent.getMessageContent(), + true); + if (ConfigHandler.getInstance().doesConsoleHaveSocialSpy()) console.sendMessage(parsedMessage); + if (initiatorPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY) || + targetPlayer.hasPermission(Constants.BYPASS_SOCIAL_SPY)) return; + for (Player spyingPlayer : messageEvent.getSpyingPlayers()) { + if (!spyingPlayer.hasPermission(Constants.ADMIN_SOCIAL_SPY)) continue; + if (spyingPlayer.equals(initiatorPlayer) || + spyingPlayer.equals(targetPlayer)) continue; + spyingPlayer.sendMessage(parsedMessage); + playSpySound(spyingPlayer); + } + } + + public static void handleConsoleSpy(PrivateMessageEvent messageEvent) { + Component parsedMessage = MessageUtils.getInstance().parseMessage( + LocaleMessage.FORMAT_SOCIAL_SPY.getMessage(), + messageEvent.getInitiator(), messageEvent.getRecipient(), messageEvent.getMessageContent(), + true); + for (Player spyingPlayer : messageEvent.getSpyingPlayers()) { + if (!spyingPlayer.hasPermission(Constants.ADMIN_CONSOLE_SPY)) continue; + if (spyingPlayer.equals(messageEvent.getInitiator()) || + spyingPlayer.equals(messageEvent.getRecipient())) continue; + spyingPlayer.sendMessage(parsedMessage); + playSpySound(spyingPlayer); + } + } + + private static void playSpySound(Player spyingPlayer) { + if (!ConfigHandler.getInstance().messagePlaysSoundForSpy()) return; + spyingPlayer.playSound(spyingPlayer, + ConfigHandler.getInstance().getSpySound(), + ConfigHandler.getInstance().getSpyVolume(), + ConfigHandler.getInstance().getSpyPitch()); + } +} From f04079b706e4b9525e52c6ef9c4a639a29f04c3a Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Sat, 31 May 2025 15:29:37 -0700 Subject: [PATCH 06/10] Cleanup, async sql calls, javadocs --- .../java/simplexity/simplepms/SimplePMs.java | 7 +- .../simplepms/events/BlockUserEvent.java | 71 +++++++++++ .../simplepms/events/PrivateMessageEvent.java | 30 ++++- .../simplepms/events/UnblockUserEvent.java | 40 +++++- .../simplepms/listeners/LoginListener.java | 14 +-- .../simplepms/listeners/PreLoginListener.java | 18 +++ .../simplexity/simplepms/saving/Cache.java | 64 +++++++++- .../simplepms/saving/SqlHandler.java | 114 ++++++++++-------- 8 files changed, 280 insertions(+), 78 deletions(-) create mode 100644 src/main/java/simplexity/simplepms/listeners/PreLoginListener.java diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index a351b54..5bf7649 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -17,6 +17,7 @@ import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.listeners.LoginListener; import simplexity.simplepms.listeners.PreCommandListener; +import simplexity.simplepms.listeners.PreLoginListener; import simplexity.simplepms.listeners.QuitListener; import java.util.HashSet; @@ -32,7 +33,6 @@ public final class SimplePMs extends JavaPlugin { private static ConsoleCommandSender consoleSender; - public static Set getSpyingPlayers() { return spyingPlayers; } @@ -40,13 +40,12 @@ public static Set getSpyingPlayers() { @Override public void onEnable() { instance = this; - this.getServer().getPluginManager().registerEvents(new LoginListener(), this); + this.getServer().getPluginManager().registerEvents(new PreLoginListener(), this); this.getServer().getPluginManager().registerEvents(new QuitListener(), this); this.getServer().getPluginManager().registerEvents(new PreCommandListener(), this); + this.getServer().getPluginManager().registerEvents(new LoginListener(), this); if (this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { papiEnabled = true; - } else { - this.getLogger().info("You do not have PlaceholderAPI loaded on your server. Any PlaceholderAPI placeholders used in this plugin's messages, will not work."); } consoleSender = this.getServer().getConsoleSender(); this.saveDefaultConfig(); diff --git a/src/main/java/simplexity/simplepms/events/BlockUserEvent.java b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java index cdffc64..a7ce1bf 100644 --- a/src/main/java/simplexity/simplepms/events/BlockUserEvent.java +++ b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java @@ -8,6 +8,7 @@ import javax.annotation.Nullable; import java.util.UUID; +@SuppressWarnings("unused") public class BlockUserEvent extends Event implements Cancellable { private boolean cancelled; private UUID initiatorUuid; @@ -25,16 +26,34 @@ public BlockUserEvent(@NotNull UUID initiatorUuid, @NotNull UUID blockedPlayerUu } + /** + * Gets whether this event has been cancelled + * + * @return boolean Cancelled + */ + @Override public boolean isCancelled() { return cancelled; } + /** + * Sets whether this event should be cancelled + * + * @param cancel boolean + */ + @Override public void setCancelled(boolean cancel) { this.cancelled = cancel; } + /** + * Gets the handlerList for this event + * + * @return HandlerList + */ + public @NotNull HandlerList getHandlers() { return handlers; } @@ -48,38 +67,90 @@ public static HandlerList getHandlerList() { return handlers; } + /** + * Gets the UUID of the player doing the blocking + * @return UUID + */ + @NotNull public UUID getInitiatorUuid() { return initiatorUuid; } + /** + * Sets the UUID for which player will have their block list altered + * Changing this UUID will change which user has a new player added to their blocked list + * This method expects a Player UUID, using andy UUID that does not belong to a player will lead to + * unexpected and unsupported behavior + * + * @param initiatorUuid UUID + */ public void setInitiatorUuid(@NotNull UUID initiatorUuid) { this.initiatorUuid = initiatorUuid; } + /** + * Gets the UUID of the player being blocked in this event + * + * @return UUID player Being blocked + */ @NotNull public UUID getBlockedPlayerUuid() { return blockedPlayerUuid; } + /** + * Sets the UUID of which player should be blocked + * Changing this UUID will alter which user is being placed into the player's block list + * This method expects a Player UUID, using any UUID that does not belong to a player will lead to + * unexpected and unsupported behavior + * + * @param blockedPlayerUuid UUID + */ public void setBlockedPlayerUuid(@NotNull UUID blockedPlayerUuid) { this.blockedPlayerUuid = blockedPlayerUuid; } + /** + * Gets the name of the player being blocked + * This name is not automatically updated when someone's username changes + * it is only used as a player-readable identifier for remembering who they blocked and being able to unblock them + * All verification is done through UUID + * + * @return String name + */ @NotNull public String getBlockedPlayerName() { return blockedPlayerName; } + /** + * Sets the name of the player being blocked, as of the current time. + * This is solely for player-readable identification + * This is used in the block list and in the unblock command, but UUID is used for actual verification. + * Display names can be used here + * @param blockedPlayerName String name + */ public void setBlockedPlayerName(@NotNull String blockedPlayerName) { this.blockedPlayerName = blockedPlayerName; } + /** + * Gets the provided reason for blocking. May be null if no reason was provided. + * + * @return String block reason + */ @Nullable public String getBlockReason() { return blockReason; } + /** + * Sets the reason for blocking the other player. + * This is displayed in the user's own blocklist, and when hovering over usernames when unblocking + * + * @param blockReason String + */ public void setBlockReason(@Nullable String blockReason) { this.blockReason = blockReason; } diff --git a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java index 72573d1..515ffe5 100644 --- a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java +++ b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java @@ -13,6 +13,7 @@ /** * Called when a private message is sent */ +@SuppressWarnings("unused") public class PrivateMessageEvent extends Event implements Cancellable { private CommandSender initiator; @@ -30,7 +31,7 @@ public PrivateMessageEvent(@NotNull CommandSender initiator, @NotNull CommandSen } /** - * Gets the CommandSender who sent the message + * Gets the CommandSender who sent the message. * * @return CommandSender */ @@ -39,7 +40,11 @@ public CommandSender getInitiator() { } /** - * Sets the CommandSender who sent the message + * Sets which CommandSender will start this message. + * Expected types are either a Player or a ConsoleCommandSender + * Using other types of CommandSender may lead to unexpected and unsupported behavior + * + * @param initiator CommandSender */ public void setInitiator(CommandSender initiator) { @@ -56,7 +61,11 @@ public CommandSender getRecipient() { } /** - * Sets the CommandSender who will receive the message + * Sets which CommandSender will receive this message. + * Expected types are either a Player or a ConsoleCommandSender + * Using other types of CommandSender may lead to unexpected and unsupported behavior + * + * @param recipient CommandSender */ public void setRecipient(CommandSender recipient){ @@ -64,16 +73,19 @@ public void setRecipient(CommandSender recipient){ } /** - * Gets the content of the message being sent + * Gets the message that is going to be sent from this event * - * @return String + * @return String message */ public String getMessageContent() { return messageContent; } /** - * Sets the message content + * Sets the message that will be sent from this event. + * Note that this only affects the actual message content and not the way the message is formatted + * + * @param messageContent String */ public void setMessageContent(String messageContent){ @@ -108,6 +120,12 @@ public void setCancelled(boolean cancel) { } + /** + * Gets the handlerList for this event + * + * @return HandlerList + */ + public @NotNull HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java index fb09daa..9ff215f 100644 --- a/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java +++ b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java @@ -7,28 +7,45 @@ import java.util.UUID; +@SuppressWarnings("unused") public class UnblockUserEvent extends Event implements Cancellable { private boolean cancelled; private UUID initiatorUuid; private UUID blockedPlayerUuid; private static final HandlerList handlers = new HandlerList(); - public UnblockUserEvent(UUID initiatorUuid, UUID blockedPlayerUuid){ + public UnblockUserEvent(UUID initiatorUuid, UUID blockedPlayerUuid) { this.initiatorUuid = initiatorUuid; this.blockedPlayerUuid = blockedPlayerUuid; } + /** + * Gets whether this event has been cancelled + * @return boolean Cancelled + */ @Override public boolean isCancelled() { return cancelled; } + /** + * Sets whether this event should be cancelled + * + * @param cancel boolean + */ + @Override public void setCancelled(boolean cancel) { this.cancelled = cancel; } + /** + * Gets the handler list, idk bukkit requires 2 of these or I'm just doing it wrong + * + * @return HandlerList + */ + public @NotNull HandlerList getHandlers() { return handlers; } @@ -42,18 +59,39 @@ public static HandlerList getHandlerList() { return handlers; } + /** + * Gets the UUID of the player who requested to unblock someone + * + * @return UUID + */ public UUID getInitiatorUuid() { return initiatorUuid; } + /** + * Sets the UUID of the person who will request to unblock someone + * + * @param initiatorUuid UUID + */ + public void setInitiatorUuid(UUID initiatorUuid) { this.initiatorUuid = initiatorUuid; } + /** + * Gets the UUID of the player who will be unblocked + * + * @return UUID + */ public UUID getBlockedPlayerUuid() { return blockedPlayerUuid; } + /** + * Sets the UUID of the player who will be unblocked + * + * @param blockedPlayerUuid UUID + */ public void setBlockedPlayerUuid(UUID blockedPlayerUuid) { this.blockedPlayerUuid = blockedPlayerUuid; } diff --git a/src/main/java/simplexity/simplepms/listeners/LoginListener.java b/src/main/java/simplexity/simplepms/listeners/LoginListener.java index 3fae3cf..297c40e 100644 --- a/src/main/java/simplexity/simplepms/listeners/LoginListener.java +++ b/src/main/java/simplexity/simplepms/listeners/LoginListener.java @@ -1,6 +1,5 @@ package simplexity.simplepms.listeners; -import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; @@ -11,14 +10,9 @@ public class LoginListener implements Listener { @EventHandler - public void onLogin(PlayerLoginEvent event) { - Player player = event.getPlayer(); - Cache.addPlayerSettingsToCache(player.getUniqueId()); - Cache.addBlockListToCache(player.getUniqueId()); - PlayerSettings playerSettings = Cache.getPlayerSettings(player.getUniqueId()); - if (playerSettings.isSocialSpyEnabled()) { - SimplePMs.getSpyingPlayers().add(player); - } - } + public void onLogin(PlayerLoginEvent loginEvent) { + PlayerSettings settings = Cache.getPlayerSettings(loginEvent.getPlayer().getUniqueId()); + if (settings.isSocialSpyEnabled()) SimplePMs.getSpyingPlayers().add(loginEvent.getPlayer()); + } } diff --git a/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java b/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java new file mode 100644 index 0000000..93f73f7 --- /dev/null +++ b/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java @@ -0,0 +1,18 @@ +package simplexity.simplepms.listeners; + +import com.destroystokyo.paper.profile.PlayerProfile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import simplexity.simplepms.saving.Cache; + +public class PreLoginListener implements Listener { + + @EventHandler + public void onPreLogin(AsyncPlayerPreLoginEvent event) { + PlayerProfile player = event.getPlayerProfile(); + Cache.addPlayerSettingsToCache(player.getId()); + Cache.addBlockListToCache(player.getId()); + } + +} diff --git a/src/main/java/simplexity/simplepms/saving/Cache.java b/src/main/java/simplexity/simplepms/saving/Cache.java index a0707af..b96f28e 100644 --- a/src/main/java/simplexity/simplepms/saving/Cache.java +++ b/src/main/java/simplexity/simplepms/saving/Cache.java @@ -20,24 +20,57 @@ public static PlayerSettings getPlayerSettings(UUID uuid) { return playerSettings.get(uuid); } + /** + * Adds the provided player's settings to the cache + * + * @param uuid Player's UUID + */ public static void addPlayerSettingsToCache(UUID uuid) { - PlayerSettings settings = SqlHandler.getInstance().getSettings(uuid); - playerSettings.put(uuid, settings); + SqlHandler.getInstance().getSettings(uuid, (settings) -> { + if (settings != null) { + playerSettings.put(uuid, settings); + } + }); } + /** + * Adds the provided player's Block List to the cache + * + * @param uuid Player's UUID + */ + public static void addBlockListToCache(UUID uuid) { - List userBlockList = SqlHandler.getInstance().getBlockedPlayers(uuid); - blockList.put(uuid, userBlockList); + SqlHandler.getInstance().getBlockedPlayers(uuid, (userBlockList) -> { + if (userBlockList != null) { + blockList.put(uuid, userBlockList); + } + }); } - public static void removePlayerSettingsFromCache(UUID uuid){ + /** + * Clears the user from the settings cache + * + * @param uuid Player's UUID + */ + public static void removePlayerSettingsFromCache(UUID uuid) { playerSettings.remove(uuid); } - public static void removeBlockListFromCache(UUID uuid){ + /** + * Clears the user from the blocklist cache + * + * @param uuid Player's UUID + */ + public static void removeBlockListFromCache(UUID uuid) { playerSettings.remove(uuid); } + /** + * Updates the provided player's current social spy settings. Updates cache and then updates SQL + * + * @param uuid UUID Player Uuid + * @param socialSpy boolean New Setting + */ public static void updateSocialSpySettings(UUID uuid, boolean socialSpy) { PlayerSettings settings = playerSettings.get(uuid); settings.setSocialSpyEnabled(socialSpy); @@ -45,6 +78,12 @@ public static void updateSocialSpySettings(UUID uuid, boolean socialSpy) { SqlHandler.getInstance().updateSettings(uuid, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); } + /** + * Updates the provided player's current message toggle state. Updates cache and then updates SQL + * + * @param uuid UUID Player Uuid + * @param messageDisabled boolean New Setting + */ public static void updateMessageSettings(UUID uuid, boolean messageDisabled) { PlayerSettings settings = playerSettings.get(uuid); settings.setMessagesDisabled(messageDisabled); @@ -52,6 +91,13 @@ public static void updateMessageSettings(UUID uuid, boolean messageDisabled) { SqlHandler.getInstance().updateSettings(uuid, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); } + /** + * Updates a player's blocklist by adding or updating a blocked player. + * + * @param uuid UUID blocking player + * @param playerBlock PlayerBlock block + */ + public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { removeCachedDuplicates(uuid, playerBlock.blockedPlayerUUID()); List blockedPlayers = blockList.get(uuid); @@ -60,6 +106,12 @@ public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { SqlHandler.getInstance().addBlockedPlayer(uuid, playerBlock.blockedPlayerUUID(), playerBlock.blockReason()); } + /** + * Removes a blocked player from a player's blocklist + * + * @param uuid UUID unblocking player + * @param blockedPlayerUuid UUID + */ public static void removeBlockedUser(UUID uuid, UUID blockedPlayerUuid) { List userBlockList = blockList.get(uuid); for (PlayerBlock block : userBlockList) { diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index 2236361..446fa33 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -3,6 +3,7 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; import org.slf4j.Logger; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.ConfigHandler; @@ -16,8 +17,9 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.function.Consumer; -@SuppressWarnings({"CallToPrintStackTrace", "SqlResolve"}) +@SuppressWarnings({"CallToPrintStackTrace", "SqlResolve", "StringTemplateMigration"}) public class SqlHandler { private SqlHandler() { @@ -35,6 +37,7 @@ public static SqlHandler getInstance() { private static final HikariConfig hikariConfig = new HikariConfig(); private static HikariDataSource dataSource; + private static final Plugin plugin = SimplePMs.getInstance(); private final Logger logger = SimplePMs.getInstance().getSLF4JLogger(); @@ -61,55 +64,62 @@ player_uuid VARCHAR (36) NOT NULL PRIMARY KEY, } } - public PlayerSettings getSettings(UUID playerUUID) { - String queryString = "SELECT socialspy_enabled, messages_disabled FROM settings WHERE player_uuid = ?;"; - try (Connection connection = getConnection()) { - PreparedStatement statement = connection.prepareStatement(queryString); - statement.setString(1, String.valueOf(playerUUID)); - try (ResultSet resultSet = statement.executeQuery()) { - if (!resultSet.next()) { - PlayerSettings settings = new PlayerSettings(playerUUID); - updateSettings(playerUUID, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); - return settings; - } else { - boolean socialSpy = resultSet.getBoolean("socialspy_enabled"); - boolean messagesDisabled = resultSet.getBoolean("messages_disabled"); - return new PlayerSettings(playerUUID, socialSpy, messagesDisabled); + public void getSettings(UUID playerUUID, Consumer callback) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + String queryString = "SELECT socialspy_enabled, messages_disabled FROM settings WHERE player_uuid = ?;"; + PlayerSettings settings = null; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); + statement.setString(1, String.valueOf(playerUUID)); + try (ResultSet resultSet = statement.executeQuery()) { + if (!resultSet.next()) { + settings = new PlayerSettings(playerUUID); + updateSettings(playerUUID, settings.isSocialSpyEnabled(), settings.areMessagesDisabled()); + } else { + boolean socialSpy = resultSet.getBoolean("socialspy_enabled"); + boolean messagesDisabled = resultSet.getBoolean("messages_disabled"); + settings = new PlayerSettings(playerUUID, socialSpy, messagesDisabled); + } } + } catch (SQLException e) { + logger.warn("Failed to retrieve settings from database: {}", e.getMessage(), e); } - } catch (SQLException e) { - logger.warn("Failed to retrieve settings from database: {}", e.getMessage(), e); - } - return null; + PlayerSettings finalSettings = settings; + Bukkit.getScheduler().runTask(plugin, () -> callback.accept(finalSettings)); + }); } public void addBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID, String reason) { - String queryString = "REPLACE INTO blocklist (player_uuid, blocked_player_uuid, block_reason) VALUES (?, ?, ?);"; - try (Connection connection = getConnection()) { - PreparedStatement statement = connection.prepareStatement(queryString); - statement.setString(1, String.valueOf(playerUUID)); - statement.setString(2, String.valueOf(blockedPlayerUUID)); - statement.setString(3, reason); - statement.executeUpdate(); - } catch (SQLException e) { - logger.warn("Failed to add blocked player: {}", e.getMessage(), e); - e.printStackTrace(); - } + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + String queryString = "REPLACE INTO blocklist (player_uuid, blocked_player_uuid, block_reason) VALUES (?, ?, ?);"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); + statement.setString(1, String.valueOf(playerUUID)); + statement.setString(2, String.valueOf(blockedPlayerUUID)); + statement.setString(3, reason); + statement.executeUpdate(); + } catch (SQLException e) { + logger.warn("Failed to add blocked player: {}", e.getMessage(), e); + e.printStackTrace(); + } + }); } public void removeBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID) { - String queryString = "DELETE FROM blocklist WHERE player_uuid = ? and blocked_player_uuid = ?;"; - try (Connection connection = getConnection()) { - PreparedStatement statement = connection.prepareStatement(queryString); - statement.setString(1, String.valueOf(playerUUID)); - statement.setString(2, String.valueOf(blockedPlayerUUID)); - statement.executeUpdate(); - } catch (SQLException e) { - logger.warn("Failed to remove blocked player: {}", e.getMessage(), e); - } + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + String queryString = "DELETE FROM blocklist WHERE player_uuid = ? and blocked_player_uuid = ?;"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); + statement.setString(1, String.valueOf(playerUUID)); + statement.setString(2, String.valueOf(blockedPlayerUUID)); + statement.executeUpdate(); + } catch (SQLException e) { + logger.warn("Failed to remove blocked player: {}", e.getMessage(), e); + } + }); } - public List getBlockedPlayers(UUID playerUUID) { + public void getBlockedPlayers(UUID playerUUID, Consumer> callback) { String queryString = "SELECT blocked_player_uuid, block_reason from blocklist WHERE player_uuid = ?;"; List blockedPlayers = new ArrayList<>(); try (Connection connection = getConnection()) { @@ -124,23 +134,25 @@ public List getBlockedPlayers(UUID playerUUID) { blockedPlayers.add(block); } } + Bukkit.getScheduler().runTask(plugin, () -> callback.accept(blockedPlayers)); } catch (SQLException e) { logger.warn("Failed to get blocked players: {}", e.getMessage(), e); } - return blockedPlayers; } public void updateSettings(UUID playerUUID, boolean socialSpyEnabled, boolean messagesDisabled) { - String queryString = "REPLACE INTO settings (player_uuid, socialspy_enabled, messages_disabled) VALUES (?, ?, ?);"; - try (Connection connection = getConnection()) { - PreparedStatement statement = connection.prepareStatement(queryString); - statement.setString(1, String.valueOf(playerUUID)); - statement.setBoolean(2, socialSpyEnabled); - statement.setBoolean(3, messagesDisabled); - statement.executeUpdate(); - } catch (SQLException e) { - logger.warn("Failed to update settings to database: {}", e.getMessage(), e); - } + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + String queryString = "REPLACE INTO settings (player_uuid, socialspy_enabled, messages_disabled) VALUES (?, ?, ?);"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); + statement.setString(1, String.valueOf(playerUUID)); + statement.setBoolean(2, socialSpyEnabled); + statement.setBoolean(3, messagesDisabled); + statement.executeUpdate(); + } catch (SQLException e) { + logger.warn("Failed to update settings to database: {}", e.getMessage(), e); + } + }); } From 26329f2b6002a9bd539be5bf0f891215daaa606f Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Tue, 3 Jun 2025 14:35:56 -0700 Subject: [PATCH 07/10] SQL stuff is all async now, I think --- .../java/simplexity/simplepms/SimplePMs.java | 23 +++--- .../simplepms/commands/Blocklist.java | 6 +- .../simplexity/simplepms/commands/Reload.java | 2 + .../simplepms/commands/SocialSpy.java | 5 +- .../simplepms/commands/Unblock.java | 4 +- .../arguments/OfflinePlayerArgument.java | 2 +- .../commands/util/MessageChecks.java | 2 +- .../simplepms/config/ConfigHandler.java | 2 - .../simplepms/config/LocaleMessage.java | 1 + .../simplepms/listeners/JoinListener.java | 20 +++++ .../simplepms/listeners/LoginListener.java | 18 ----- .../simplepms/listeners/PreLoginListener.java | 18 ----- .../simplepms/listeners/QuitListener.java | 3 +- .../simplexity/simplepms/logic/PMHandler.java | 3 +- .../simplepms/logic/SpyHandler.java | 3 +- .../simplepms/logic/UnblockHandler.java | 4 +- .../simplexity/simplepms/saving/Cache.java | 67 +++++++++------- .../simplepms/saving/SqlHandler.java | 77 ++++++++++++------- .../simplepms/saving/objects/PlayerBlock.java | 47 +++++++++-- 19 files changed, 178 insertions(+), 129 deletions(-) create mode 100644 src/main/java/simplexity/simplepms/listeners/JoinListener.java delete mode 100644 src/main/java/simplexity/simplepms/listeners/LoginListener.java delete mode 100644 src/main/java/simplexity/simplepms/listeners/PreLoginListener.java diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index 5bf7649..15e9cb0 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -3,7 +3,6 @@ import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import simplexity.simplepms.commands.Block; @@ -15,13 +14,10 @@ import simplexity.simplepms.commands.SocialSpy; import simplexity.simplepms.commands.Unblock; import simplexity.simplepms.config.ConfigHandler; -import simplexity.simplepms.listeners.LoginListener; +import simplexity.simplepms.listeners.JoinListener; import simplexity.simplepms.listeners.PreCommandListener; -import simplexity.simplepms.listeners.PreLoginListener; import simplexity.simplepms.listeners.QuitListener; - -import java.util.HashSet; -import java.util.Set; +import simplexity.simplepms.saving.SqlHandler; @SuppressWarnings("UnstableApiUsage") public final class SimplePMs extends JavaPlugin { @@ -29,21 +25,15 @@ public final class SimplePMs extends JavaPlugin { private static Plugin instance; private static final MiniMessage miniMessage = MiniMessage.miniMessage(); private static boolean papiEnabled = false; - private static final HashSet spyingPlayers = new HashSet<>(); private static ConsoleCommandSender consoleSender; - public static Set getSpyingPlayers() { - return spyingPlayers; - } - @Override public void onEnable() { instance = this; - this.getServer().getPluginManager().registerEvents(new PreLoginListener(), this); this.getServer().getPluginManager().registerEvents(new QuitListener(), this); this.getServer().getPluginManager().registerEvents(new PreCommandListener(), this); - this.getServer().getPluginManager().registerEvents(new LoginListener(), this); + this.getServer().getPluginManager().registerEvents(new JoinListener(), this); if (this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { papiEnabled = true; } @@ -52,6 +42,7 @@ public void onEnable() { getConfig().options().copyDefaults(true); saveConfig(); ConfigHandler.getInstance().loadConfigValues(); + SqlHandler.getInstance().init(); this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { commands.registrar().register(PrivateMessage.createCommand()); commands.registrar().register(PrivateMessage.createTellAlias()); @@ -68,6 +59,12 @@ public void onEnable() { }); } + @Override + + public void onDisable() { + SqlHandler.getInstance().shutdownConnection(); + } + public static MiniMessage getMiniMessage() { return miniMessage; } diff --git a/src/main/java/simplexity/simplepms/commands/Blocklist.java b/src/main/java/simplexity/simplepms/commands/Blocklist.java index 9966e21..de8f826 100644 --- a/src/main/java/simplexity/simplepms/commands/Blocklist.java +++ b/src/main/java/simplexity/simplepms/commands/Blocklist.java @@ -38,11 +38,11 @@ public static LiteralCommandNode createCommand() { message = message.appendNewline(); message = message.append(miniMessage.deserialize( LocaleMessage.BLOCKLIST_NAME.getMessage(), - Placeholder.parsed("name", block.blockedPlayerName()) + Placeholder.parsed("name", block.getBlockedPlayerName()) )); - if (block.blockReason() == null || block.blockReason().isEmpty()) continue; + if (block.getBlockReason() == null || block.getBlockReason().isEmpty()) continue; message = message.append(miniMessage.deserialize(LocaleMessage.BLOCKLIST_REASON.getMessage(), - Placeholder.parsed("reason", block.blockReason()))); + Placeholder.parsed("reason", block.getBlockReason()))); } player.sendMessage(message); return Command.SINGLE_SUCCESS; diff --git a/src/main/java/simplexity/simplepms/commands/Reload.java b/src/main/java/simplexity/simplepms/commands/Reload.java index eaa94d7..5422114 100644 --- a/src/main/java/simplexity/simplepms/commands/Reload.java +++ b/src/main/java/simplexity/simplepms/commands/Reload.java @@ -8,6 +8,7 @@ import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.saving.SqlHandler; @SuppressWarnings("UnstableApiUsage") public class Reload { @@ -18,6 +19,7 @@ public static LiteralCommandNode createCommand() { .executes(ctx -> { CommandSender sender = ctx.getSource().getSender(); ConfigHandler.getInstance().loadConfigValues(); + SqlHandler.getInstance().reloadDatabase(); sender.sendRichMessage(LocaleMessage.RELOADED.getMessage()); return Command.SINGLE_SUCCESS; }).build(); diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index a3991a3..1fef05d 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -6,7 +6,6 @@ import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; import org.bukkit.entity.Player; -import simplexity.simplepms.SimplePMs; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.Cache; @@ -41,12 +40,12 @@ private static int execute(CommandContext ctx) { if (settings == null || settings.isSocialSpyEnabled()) { Cache.updateSocialSpySettings(uuid, false); player.sendRichMessage(LocaleMessage.SOCIAL_SPY_DISABLED.getMessage()); - SimplePMs.getSpyingPlayers().remove(player); + Cache.getSpyingPlayers().remove(player); return Command.SINGLE_SUCCESS; } Cache.updateSocialSpySettings(uuid, true); player.sendRichMessage(LocaleMessage.SOCIAL_SPY_ENABLED.getMessage()); - SimplePMs.getSpyingPlayers().add(player); + Cache.getSpyingPlayers().add(player); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/simplexity/simplepms/commands/Unblock.java b/src/main/java/simplexity/simplepms/commands/Unblock.java index e06f8cb..96f2a9e 100644 --- a/src/main/java/simplexity/simplepms/commands/Unblock.java +++ b/src/main/java/simplexity/simplepms/commands/Unblock.java @@ -63,8 +63,8 @@ private static CompletableFuture suggestBlockedUsers(final CommandC List blockedPlayers = Cache.getBlockList(playerSender.getUniqueId()); if (blockedPlayers.isEmpty()) return builder.buildFuture(); for (PlayerBlock block : blockedPlayers) { - builder.suggest(block.blockedPlayerName(), - MessageComponentSerializer.message().serialize(Component.text(block.blockReason()))); + builder.suggest(block.getBlockedPlayerName(), + MessageComponentSerializer.message().serialize(Component.text(block.getBlockReason()))); } return builder.buildFuture(); } diff --git a/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java index 739c221..46c783b 100644 --- a/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java +++ b/src/main/java/simplexity/simplepms/commands/arguments/OfflinePlayerArgument.java @@ -43,7 +43,7 @@ public class OfflinePlayerArgument implements CustomArgumentType getNativeType() { - return StringArgumentType.word(); + return StringArgumentType.greedyString(); } /** diff --git a/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java index 6688e38..bd07c5f 100644 --- a/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java +++ b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java @@ -64,7 +64,7 @@ private static boolean userBlocked(Player blocklistPlayer, Player potentialBlock return false; } for (PlayerBlock playerBlock : playerBlocks) { - if (playerBlock.blockedPlayerUUID().equals(potentialBlock.getUniqueId())) { + if (playerBlock.getBlockedPlayerUUID().equals(potentialBlock.getUniqueId())) { return true; } } diff --git a/src/main/java/simplexity/simplepms/config/ConfigHandler.java b/src/main/java/simplexity/simplepms/config/ConfigHandler.java index ef98162..2e35180 100644 --- a/src/main/java/simplexity/simplepms/config/ConfigHandler.java +++ b/src/main/java/simplexity/simplepms/config/ConfigHandler.java @@ -3,7 +3,6 @@ import org.bukkit.Sound; import org.bukkit.configuration.file.FileConfiguration; import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.saving.SqlHandler; import java.util.ArrayList; import java.util.HashSet; @@ -30,7 +29,6 @@ public static ConfigHandler getInstance() { public void loadConfigValues() { SimplePMs.getInstance().reloadConfig(); FileConfiguration config = SimplePMs.getInstance().getConfig(); - SqlHandler.getInstance().init(); LocaleHandler.getInstance().reloadLocale(); List commands = config.getStringList("command-spy.commands"); List consoleNames = config.getStringList("valid-console-names"); diff --git a/src/main/java/simplexity/simplepms/config/LocaleMessage.java b/src/main/java/simplexity/simplepms/config/LocaleMessage.java index ab0d88c..4b180ee 100644 --- a/src/main/java/simplexity/simplepms/config/LocaleMessage.java +++ b/src/main/java/simplexity/simplepms/config/LocaleMessage.java @@ -31,6 +31,7 @@ public enum LocaleMessage { ERROR_CANNOT_MESSAGE_SOMEONE_YOU_BLOCKED("error.cannot-message-someone-you-blocked", "Sorry, you cannot message someone you currently have blocked."), ERROR_CANNOT_MESSAGE_CONSOLE("error.cannot-message-console", "Sorry, you cannot message the server"), ERROR_SOMETHING_WENT_WRONG("error.something-wrong", "Sorry, something went wrong, please check console for more information"), + ERROR_NAME_NOT_FOUND("error.name-not-found", "Name not found"), LOG_ERROR_SOUND_NOT_VALID("console-error.sound-not-valid", "Warning! The sound you have input: '%sound-string%' is invalid! Please be sure you use a sound that is listed on https://jd.papermc.io/paper/1.21.4/org/bukkit/Sound.html"), LOG_ERROR_USING_DEFAULT_SOUND("console-error.using-default-sound", "Using %default-sound% until a valid sound is provided"), LOG_ERROR_FLOAT_OUT_OF_RANGE("console-error.float-out-of-range", "The number %number% is out of range! Volume and pitch values must be a number between 0 and 2!"), diff --git a/src/main/java/simplexity/simplepms/listeners/JoinListener.java b/src/main/java/simplexity/simplepms/listeners/JoinListener.java new file mode 100644 index 0000000..f168329 --- /dev/null +++ b/src/main/java/simplexity/simplepms/listeners/JoinListener.java @@ -0,0 +1,20 @@ +package simplexity.simplepms.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.saving.Cache; + +import java.util.UUID; + +public class JoinListener implements Listener { + + @EventHandler + public void onLogin(PlayerJoinEvent joinEvent) { + Player player = joinEvent.getPlayer(); + UUID playerUuid = player.getUniqueId(); + Cache.populateCache(playerUuid, player, player.hasPermission(Constants.ADMIN_SOCIAL_SPY)); + } +} diff --git a/src/main/java/simplexity/simplepms/listeners/LoginListener.java b/src/main/java/simplexity/simplepms/listeners/LoginListener.java deleted file mode 100644 index 297c40e..0000000 --- a/src/main/java/simplexity/simplepms/listeners/LoginListener.java +++ /dev/null @@ -1,18 +0,0 @@ -package simplexity.simplepms.listeners; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerLoginEvent; -import simplexity.simplepms.SimplePMs; -import simplexity.simplepms.saving.Cache; -import simplexity.simplepms.saving.objects.PlayerSettings; - -public class LoginListener implements Listener { - - @EventHandler - public void onLogin(PlayerLoginEvent loginEvent) { - PlayerSettings settings = Cache.getPlayerSettings(loginEvent.getPlayer().getUniqueId()); - if (settings.isSocialSpyEnabled()) SimplePMs.getSpyingPlayers().add(loginEvent.getPlayer()); - - } -} diff --git a/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java b/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java deleted file mode 100644 index 93f73f7..0000000 --- a/src/main/java/simplexity/simplepms/listeners/PreLoginListener.java +++ /dev/null @@ -1,18 +0,0 @@ -package simplexity.simplepms.listeners; - -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import simplexity.simplepms.saving.Cache; - -public class PreLoginListener implements Listener { - - @EventHandler - public void onPreLogin(AsyncPlayerPreLoginEvent event) { - PlayerProfile player = event.getPlayerProfile(); - Cache.addPlayerSettingsToCache(player.getId()); - Cache.addBlockListToCache(player.getId()); - } - -} diff --git a/src/main/java/simplexity/simplepms/listeners/QuitListener.java b/src/main/java/simplexity/simplepms/listeners/QuitListener.java index 7b32ccc..a7b552c 100644 --- a/src/main/java/simplexity/simplepms/listeners/QuitListener.java +++ b/src/main/java/simplexity/simplepms/listeners/QuitListener.java @@ -3,13 +3,12 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; -import simplexity.simplepms.SimplePMs; import simplexity.simplepms.saving.Cache; public class QuitListener implements Listener { @EventHandler public void onQuit(PlayerQuitEvent e) { - SimplePMs.getSpyingPlayers().remove(e.getPlayer()); + Cache.getSpyingPlayers().remove(e.getPlayer()); Cache.removeBlockListFromCache(e.getPlayer().getUniqueId()); Cache.removePlayerSettingsFromCache(e.getPlayer().getUniqueId()); } diff --git a/src/main/java/simplexity/simplepms/logic/PMHandler.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java index b36f0c1..6d67a26 100644 --- a/src/main/java/simplexity/simplepms/logic/PMHandler.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -6,6 +6,7 @@ import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.events.PrivateMessageEvent; +import simplexity.simplepms.saving.Cache; import java.util.HashMap; @@ -57,7 +58,7 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender private static PrivateMessageEvent callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { - PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, SimplePMs.getSpyingPlayers()); + PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, Cache.getSpyingPlayers()); SimplePMs.getInstance().getServer().getPluginManager().callEvent(messageEvent); return messageEvent; } diff --git a/src/main/java/simplexity/simplepms/logic/SpyHandler.java b/src/main/java/simplexity/simplepms/logic/SpyHandler.java index e558813..0fca2bf 100644 --- a/src/main/java/simplexity/simplepms/logic/SpyHandler.java +++ b/src/main/java/simplexity/simplepms/logic/SpyHandler.java @@ -7,6 +7,7 @@ import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.events.PrivateMessageEvent; +import simplexity.simplepms.saving.Cache; public class SpyHandler { @@ -20,7 +21,7 @@ public static void sendCommandSpy(CommandSender initiator, String command, Strin console.sendMessage(parsedMessage); } if (initiator.hasPermission(Constants.BYPASS_COMMAND_SPY)) return; - for (Player spyingPlayer : SimplePMs.getSpyingPlayers()) { + for (Player spyingPlayer : Cache.getSpyingPlayers()) { if (initiator.equals(spyingPlayer)) continue; if (!spyingPlayer.hasPermission(Constants.ADMIN_SOCIAL_SPY)) continue; spyingPlayer.sendMessage(parsedMessage); diff --git a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java index c2a5e3b..97b6650 100644 --- a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java +++ b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java @@ -18,8 +18,8 @@ public static void removeBlockedPlayer(@NotNull Player blockingPlayer, @NotNull List playerBlocks = Cache.getBlockList(blockingPlayer.getUniqueId()); UUID playerToUnblockUuid = null; for (PlayerBlock block : playerBlocks) { - if (block.blockedPlayerName().equalsIgnoreCase(userToRemove)) { - playerToUnblockUuid = block.blockedPlayerUUID(); + if (block.getBlockedPlayerName().equalsIgnoreCase(userToRemove)) { + playerToUnblockUuid = block.getBlockedPlayerUUID(); break; } } diff --git a/src/main/java/simplexity/simplepms/saving/Cache.java b/src/main/java/simplexity/simplepms/saving/Cache.java index b96f28e..f686fd8 100644 --- a/src/main/java/simplexity/simplepms/saving/Cache.java +++ b/src/main/java/simplexity/simplepms/saving/Cache.java @@ -1,16 +1,23 @@ package simplexity.simplepms.saving; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import simplexity.simplepms.SimplePMs; +import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.objects.PlayerSettings; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.UUID; public class Cache { public static final HashMap> blockList = new HashMap<>(); public static final HashMap playerSettings = new HashMap<>(); + public static final HashSet spyingPlayers = new HashSet<>(); public static List getBlockList(UUID uuid) { return blockList.get(uuid); @@ -20,30 +27,19 @@ public static PlayerSettings getPlayerSettings(UUID uuid) { return playerSettings.get(uuid); } - /** - * Adds the provided player's settings to the cache - * - * @param uuid Player's UUID - */ - public static void addPlayerSettingsToCache(UUID uuid) { - SqlHandler.getInstance().getSettings(uuid, (settings) -> { - if (settings != null) { - playerSettings.put(uuid, settings); - } - }); - } - - /** - * Adds the provided player's Block List to the cache - * - * @param uuid Player's UUID - */ - public static void addBlockListToCache(UUID uuid) { - SqlHandler.getInstance().getBlockedPlayers(uuid, (userBlockList) -> { - if (userBlockList != null) { - blockList.put(uuid, userBlockList); - } + public static void populateCache(UUID uuid, Player player, boolean hasSpyPerms) { + Bukkit.getScheduler().runTaskAsynchronously(SimplePMs.getInstance(), () -> { + SqlHandler.getInstance().getBlockedPlayers(uuid).thenAccept(blocklist -> { + blockList.put(uuid, blocklist); + populateNullNames(uuid); + }); + SqlHandler.getInstance().getSettings(uuid).thenAccept(settings -> { + playerSettings.put(uuid, settings); + if (hasSpyPerms && settings.isSocialSpyEnabled()) { + spyingPlayers.add(player); + } + }); }); } @@ -99,11 +95,11 @@ public static void updateMessageSettings(UUID uuid, boolean messageDisabled) { */ public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { - removeCachedDuplicates(uuid, playerBlock.blockedPlayerUUID()); + removeCachedDuplicates(uuid, playerBlock.getBlockedPlayerUUID()); List blockedPlayers = blockList.get(uuid); blockedPlayers.add(playerBlock); blockList.put(uuid, blockedPlayers); - SqlHandler.getInstance().addBlockedPlayer(uuid, playerBlock.blockedPlayerUUID(), playerBlock.blockReason()); + SqlHandler.getInstance().addBlockedPlayer(uuid, playerBlock.getBlockedPlayerUUID(), playerBlock.getBlockedPlayerName(), playerBlock.getBlockReason()); } /** @@ -115,7 +111,7 @@ public static void addBlockedUser(UUID uuid, PlayerBlock playerBlock) { public static void removeBlockedUser(UUID uuid, UUID blockedPlayerUuid) { List userBlockList = blockList.get(uuid); for (PlayerBlock block : userBlockList) { - if (block.blockedPlayerUUID().equals(blockedPlayerUuid)) { + if (block.getBlockedPlayerUUID().equals(blockedPlayerUuid)) { userBlockList.remove(block); break; } @@ -127,9 +123,24 @@ public static void removeBlockedUser(UUID uuid, UUID blockedPlayerUuid) { private static void removeCachedDuplicates(UUID blockingUuid, UUID blockedUuid) { List blockedPlayers = blockList.get(blockingUuid); if (blockedPlayers == null) blockedPlayers = new ArrayList<>(); - blockedPlayers.removeIf(block -> - block.blockedPlayerUUID().equals(blockedUuid)); + blockedPlayers.removeIf(block -> block.getBlockedPlayerUUID().equals(blockedUuid)); blockList.put(blockingUuid, blockedPlayers); } + private static void populateNullNames(UUID uuidToCheck) { + List playerBlocks = blockList.get(uuidToCheck); + if (playerBlocks == null || playerBlocks.isEmpty()) return; + for (PlayerBlock block : playerBlocks) { + if (block.getBlockedPlayerName() == null || block.getBlockedPlayerName().isEmpty()) { + String newName = Bukkit.getOfflinePlayer(block.getBlockedPlayerUUID()).getName(); + if (newName == null) newName = LocaleMessage.ERROR_NAME_NOT_FOUND.getMessage(); + block.setBlockedPlayerName(newName); + } + } + blockList.put(uuidToCheck, playerBlocks); + } + + public static Set getSpyingPlayers() { + return spyingPlayers; + } } diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index 446fa33..2315e9f 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -17,7 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import java.util.function.Consumer; +import java.util.concurrent.CompletableFuture; @SuppressWarnings({"CallToPrintStackTrace", "SqlResolve", "StringTemplateMigration"}) public class SqlHandler { @@ -48,6 +48,7 @@ public void init() { CREATE TABLE IF NOT EXISTS blocklist ( player_uuid VARCHAR (36) NOT NULL, blocked_player_uuid VARCHAR(36) NOT NULL, + blocked_player_name VARCHAR(256), block_reason VARCHAR(256), PRIMARY KEY (player_uuid, blocked_player_uuid) );"""); @@ -64,8 +65,16 @@ player_uuid VARCHAR (36) NOT NULL PRIMARY KEY, } } - public void getSettings(UUID playerUUID, Consumer callback) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + public void reloadDatabase() { + logger.info("Reconnecting to SimplePMs database..."); + shutdownConnection(); + setupConfig(); + logger.info("Database reloaded successfully"); + } + + + public CompletableFuture getSettings(UUID playerUUID) { + return CompletableFuture.supplyAsync(() -> { String queryString = "SELECT socialspy_enabled, messages_disabled FROM settings WHERE player_uuid = ?;"; PlayerSettings settings = null; try (Connection connection = getConnection()) { @@ -84,19 +93,42 @@ public void getSettings(UUID playerUUID, Consumer callback) { } catch (SQLException e) { logger.warn("Failed to retrieve settings from database: {}", e.getMessage(), e); } - PlayerSettings finalSettings = settings; - Bukkit.getScheduler().runTask(plugin, () -> callback.accept(finalSettings)); + return settings; }); } - public void addBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID, String reason) { + public CompletableFuture> getBlockedPlayers(UUID playerUUID) { + return CompletableFuture.supplyAsync(() -> { + String queryString = "SELECT blocked_player_uuid, block_reason, blocked_player_name from blocklist WHERE player_uuid = ?;"; + List blockedPlayers = new ArrayList<>(); + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(queryString); + statement.setString(1, String.valueOf(playerUUID)); + try (ResultSet resultSet = statement.executeQuery()) { + while (resultSet.next()) { + UUID blockedPlayerUUID = UUID.fromString(resultSet.getString("blocked_player_uuid")); + String blockedPlayerName = resultSet.getString("blocked_player_name"); + String reason = resultSet.getString("block_reason"); + PlayerBlock block = new PlayerBlock(playerUUID, blockedPlayerName, blockedPlayerUUID, reason); + blockedPlayers.add(block); + } + } + } catch (SQLException e) { + logger.warn("Failed to get blocked players: {}", e.getMessage(), e); + } + return blockedPlayers; + }); + } + + public void addBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID, String blockedPlayerName, String reason) { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - String queryString = "REPLACE INTO blocklist (player_uuid, blocked_player_uuid, block_reason) VALUES (?, ?, ?);"; + String queryString = "REPLACE INTO blocklist (player_uuid, blocked_player_uuid, blocked_player_name, block_reason) VALUES (?, ?, ?, ?);"; try (Connection connection = getConnection()) { PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1, String.valueOf(playerUUID)); statement.setString(2, String.valueOf(blockedPlayerUUID)); - statement.setString(3, reason); + statement.setString(3, blockedPlayerName); + statement.setString(4, reason); statement.executeUpdate(); } catch (SQLException e) { logger.warn("Failed to add blocked player: {}", e.getMessage(), e); @@ -119,27 +151,6 @@ public void removeBlockedPlayer(UUID playerUUID, UUID blockedPlayerUUID) { }); } - public void getBlockedPlayers(UUID playerUUID, Consumer> callback) { - String queryString = "SELECT blocked_player_uuid, block_reason from blocklist WHERE player_uuid = ?;"; - List blockedPlayers = new ArrayList<>(); - try (Connection connection = getConnection()) { - PreparedStatement statement = connection.prepareStatement(queryString); - statement.setString(1, String.valueOf(playerUUID)); - try (ResultSet resultSet = statement.executeQuery()) { - while (resultSet.next()) { - UUID blockedPlayerUUID = UUID.fromString(resultSet.getString("blocked_player_uuid")); - String blockedPlayerName = Bukkit.getOfflinePlayer(blockedPlayerUUID).getName(); - String reason = resultSet.getString("block_reason"); - PlayerBlock block = new PlayerBlock(playerUUID, blockedPlayerName, blockedPlayerUUID, reason); - blockedPlayers.add(block); - } - } - Bukkit.getScheduler().runTask(plugin, () -> callback.accept(blockedPlayers)); - } catch (SQLException e) { - logger.warn("Failed to get blocked players: {}", e.getMessage(), e); - } - } - public void updateSettings(UUID playerUUID, boolean socialSpyEnabled, boolean messagesDisabled) { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { String queryString = "REPLACE INTO settings (player_uuid, socialspy_enabled, messages_disabled) VALUES (?, ?, ?);"; @@ -159,6 +170,7 @@ public void updateSettings(UUID playerUUID, boolean socialSpyEnabled, boolean me private void setupConfig() { if (!ConfigHandler.getInstance().isMysqlEnabled()) { hikariConfig.setJdbcUrl("jdbc:sqlite:" + SimplePMs.getInstance().getDataFolder() + "/simple-pms.db"); + hikariConfig.setConnectionTestQuery("PRAGMA journal_mode = WAL;"); dataSource = new HikariDataSource(hikariConfig); return; } @@ -171,4 +183,11 @@ private void setupConfig() { private static Connection getConnection() throws SQLException { return dataSource.getConnection(); } + + public void shutdownConnection() { + if (dataSource == null || dataSource.isClosed()) return; + dataSource.close(); + dataSource = null; + logger.info("Closed existing database connection"); + } } diff --git a/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java b/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java index 737ff54..c68cc50 100644 --- a/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java +++ b/src/main/java/simplexity/simplepms/saving/objects/PlayerBlock.java @@ -2,13 +2,50 @@ import java.util.UUID; -@SuppressWarnings("StringTemplateMigration") -public record PlayerBlock(UUID blockingPlayerUUID, String blockedPlayerName, UUID blockedPlayerUUID, String blockReason) { +@SuppressWarnings({"StringTemplateMigration", "unused"}) +public class PlayerBlock { + + private final UUID blockingPlayerUUID; + private final UUID blockedPlayerUUID; + private String blockedPlayerName; + private String blockReason; + + public PlayerBlock(UUID blockingPlayerUUID, String blockedPlayerName, UUID blockedPlayerUUID, String blockReason) { + this.blockingPlayerUUID = blockingPlayerUUID; + this.blockedPlayerUUID = blockedPlayerUUID; + this.blockedPlayerName = blockedPlayerName; + this.blockReason = blockReason; + } + + public UUID getBlockingPlayerUUID() { + return blockingPlayerUUID; + } + + public UUID getBlockedPlayerUUID() { + return blockedPlayerUUID; + } + + public String getBlockedPlayerName() { + return blockedPlayerName; + } + + public void setBlockedPlayerName(String name) { + blockedPlayerName = name; + } + + public String getBlockReason() { + return blockReason; + } + + public void setBlockReason(String reason) { + blockReason = reason; + } + public String toString() { return "PlayerBlock [" + "blockingPlayerUUID=" + blockingPlayerUUID - + ", blockedPlayerName=" + blockedPlayerName - + "blockedPlayerUUID=" + blockedPlayerUUID - + ", blockReason=" + blockReason + "]"; + + ", blockedPlayerName=" + blockedPlayerName + + "blockedPlayerUUID=" + blockedPlayerUUID + + ", blockReason=" + blockReason + "]"; } } From 4a90b1d97765c5fad0f2c8cc3f8fae5bb0806afe Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Fri, 6 Jun 2025 10:54:49 -0700 Subject: [PATCH 08/10] yes this is definitely a normal way to have settings migrate mhm --- .../simplepms/saving/SqlHandler.java | 65 ++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/java/simplexity/simplepms/saving/SqlHandler.java b/src/main/java/simplexity/simplepms/saving/SqlHandler.java index 2315e9f..86d0851 100644 --- a/src/main/java/simplexity/simplepms/saving/SqlHandler.java +++ b/src/main/java/simplexity/simplepms/saving/SqlHandler.java @@ -11,6 +11,7 @@ import simplexity.simplepms.saving.objects.PlayerSettings; import java.sql.Connection; +import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -19,7 +20,7 @@ import java.util.UUID; import java.util.concurrent.CompletableFuture; -@SuppressWarnings({"CallToPrintStackTrace", "SqlResolve", "StringTemplateMigration"}) +@SuppressWarnings({"CallToPrintStackTrace", "SqlResolve", "StringTemplateMigration", "SameParameterValue"}) public class SqlHandler { private SqlHandler() { @@ -60,6 +61,7 @@ player_uuid VARCHAR (36) NOT NULL PRIMARY KEY, messages_disabled BOOLEAN NOT NULL );"""); playerSettingsInitStatement.execute(); + updateDatabaseColumns(); } catch (SQLException e) { logger.warn("Failed to connect to database: {}", e.getMessage(), e); } @@ -167,6 +169,67 @@ public void updateSettings(UUID playerUUID, boolean socialSpyEnabled, boolean me } + private void updateDatabaseColumns() { + if (ConfigHandler.getInstance().isMysqlEnabled()) { + doesMysqlColumnExist("blocklist", "blocked_player_name").thenAccept(exists -> { + if (!exists) { + addColumn("blocklist", "blocked_player_name", "VARCHAR(256)", ""); + } + }); + } else { + doesSqliteColumnExist("blocklist", "blocked_player_name").thenAccept(exists -> { + if (!exists) { + addColumn("blocklist", "blocked_player_name", "VARCHAR(256)", ""); + } + }); + } + } + + private CompletableFuture doesSqliteColumnExist(String tableName, String columnName) { + return CompletableFuture.supplyAsync(() -> { + String query = "PRAGMA table_info(" + tableName + ")"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(query); + ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + if (columnName.equalsIgnoreCase(resultSet.getString("name"))) { + return true; + } + } + } catch (SQLException e) { + logger.warn("Failed to to check for column {} in table {}: {}", columnName, tableName, e.getMessage(), e); + } + return false; + }); + } + + private CompletableFuture doesMysqlColumnExist(String tableName, String columnName) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + DatabaseMetaData metaData = connection.getMetaData(); + ResultSet resultSet = metaData.getColumns(null, null, tableName, columnName); + return resultSet.next(); + } catch (SQLException e) { + logger.warn("Failed to check for column {} in table {}: {}", columnName, tableName, e.getMessage(), e); + } + return false; + }); + } + + // Possibly extremely cursed way to do this :cackle: + + private void addColumn(String tableName, String columnName, String dataType, String constraints) { + String query = "ALTER TABLE " + tableName + " ADD COLUMN " + columnName + dataType + constraints + ";"; + try (Connection connection = getConnection()) { + PreparedStatement statement = connection.prepareStatement(query); + statement.executeUpdate(); + logger.info("Added new column '{}' to table '{}'", columnName, tableName); + } catch (SQLException e) { + logger.warn("Failed to add new column {} to table {}: {}", columnName, tableName, e.getMessage(), e); + } + } + + private void setupConfig() { if (!ConfigHandler.getInstance().isMysqlEnabled()) { hikariConfig.setJdbcUrl("jdbc:sqlite:" + SimplePMs.getInstance().getDataFolder() + "/simple-pms.db"); From bd25b93697d0b63db095e84989fda466bc6d9acf Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Fri, 6 Jun 2025 12:57:53 -0700 Subject: [PATCH 09/10] asd;lfkjasdfj --- pom.xml | 2 +- .../java/simplexity/simplepms/SimplePMs.java | 13 +++++ .../simplexity/simplepms/commands/Reload.java | 2 +- .../simplepms/config/ConfigHandler.java | 37 ++++++------- .../simplepms/config/LocaleMessage.java | 4 +- .../simplexity/simplepms/logic/Constants.java | 51 ++++++++++++++---- .../simplexity/simplepms/logic/PMHandler.java | 5 +- .../simplepms/logic/SpyHandler.java | 3 +- src/main/resources/config.yml | 8 +-- src/main/resources/paper-plugin.yml | 10 ++++ src/main/resources/plugin.yml | 54 ------------------- 11 files changed, 97 insertions(+), 92 deletions(-) create mode 100644 src/main/resources/paper-plugin.yml delete mode 100644 src/main/resources/plugin.yml diff --git a/pom.xml b/pom.xml index cd4e89f..f128934 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ simplexity SimplePMs - 2.3.2 + 2.4.0 jar SimplePMs diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index 15e9cb0..ddea4be 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -17,6 +17,7 @@ import simplexity.simplepms.listeners.JoinListener; import simplexity.simplepms.listeners.PreCommandListener; import simplexity.simplepms.listeners.QuitListener; +import simplexity.simplepms.logic.Constants; import simplexity.simplepms.saving.SqlHandler; @SuppressWarnings("UnstableApiUsage") @@ -57,6 +58,18 @@ public void onEnable() { commands.registrar().register(Reload.createCommand()); commands.registrar().register(Blocklist.createCommand()); }); + getServer().getPluginManager().addPermission(Constants.MESSAGE_BASIC); + getServer().getPluginManager().addPermission(Constants.MESSAGE_ADMIN); + getServer().getPluginManager().addPermission(Constants.MESSAGE_SEND); + getServer().getPluginManager().addPermission(Constants.MESSAGE_RECEIVE); + getServer().getPluginManager().addPermission(Constants.MESSAGE_TOGGLE); + getServer().getPluginManager().addPermission(Constants.MESSAGE_BLOCK); + getServer().getPluginManager().addPermission(Constants.PLUGIN_RELOAD); + getServer().getPluginManager().addPermission(Constants.ADMIN_OVERRIDE); + getServer().getPluginManager().addPermission(Constants.ADMIN_SOCIAL_SPY); + getServer().getPluginManager().addPermission(Constants.ADMIN_CONSOLE_SPY); + getServer().getPluginManager().addPermission(Constants.BYPASS_SOCIAL_SPY); + getServer().getPluginManager().addPermission(Constants.BYPASS_COMMAND_SPY); } @Override diff --git a/src/main/java/simplexity/simplepms/commands/Reload.java b/src/main/java/simplexity/simplepms/commands/Reload.java index 5422114..9cc8677 100644 --- a/src/main/java/simplexity/simplepms/commands/Reload.java +++ b/src/main/java/simplexity/simplepms/commands/Reload.java @@ -15,7 +15,7 @@ public class Reload { public static LiteralCommandNode createCommand() { return Commands.literal("spmreload") - .requires(css -> css.getSender().hasPermission(Constants.RELOAD)) + .requires(css -> css.getSender().hasPermission(Constants.PLUGIN_RELOAD)) .executes(ctx -> { CommandSender sender = ctx.getSource().getSender(); ConfigHandler.getInstance().loadConfigValues(); diff --git a/src/main/java/simplexity/simplepms/config/ConfigHandler.java b/src/main/java/simplexity/simplepms/config/ConfigHandler.java index 2e35180..5108a50 100644 --- a/src/main/java/simplexity/simplepms/config/ConfigHandler.java +++ b/src/main/java/simplexity/simplepms/config/ConfigHandler.java @@ -1,5 +1,8 @@ package simplexity.simplepms.config; +import net.kyori.adventure.key.Key; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.Sound; import org.bukkit.configuration.file.FileConfiguration; import simplexity.simplepms.SimplePMs; @@ -20,7 +23,7 @@ public static ConfigHandler getInstance() { private final Logger logger = SimplePMs.getInstance().getLogger(); private boolean mysqlEnabled, playersSendToConsole, playersSendToHiddenPlayers, consoleHasSocialSpy, commandSpyEnabled, consoleHasCommandSpy, receiveSoundEnabled, sendSoundEnabled, spySoundEnabled; - private Sound receiveSound, sendSound, spySound; + private NamespacedKey receiveSound, sendSound, spySound; private float receivePitch, receiveVolume, sendPitch, sendVolume, spyPitch, spyVolume; private String mysqlIp, mysqlName, mysqlUsername, mysqlPassword, normalFormat, socialSpyFormat; private final List validNamesForConsole = new ArrayList<>(); @@ -60,38 +63,36 @@ private void updateHashSet(HashSet set, List list) { } private void loadReceiveSoundInfo(FileConfiguration config) { - String soundString = config.getString("sounds.received.sound", "BLOCK_NOTE_BLOCK_XYLOPHONE"); - receiveSound = getValidSound(soundString, Sound.BLOCK_NOTE_BLOCK_XYLOPHONE); + String soundString = config.getString("sounds.received.sound", "minecraft:block.note_block.xylophone"); + receiveSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.BLOCK_NOTE_BLOCK_XYLOPHONE)); receivePitch = getValidFloat(config.getDouble("sounds.received.pitch", 1.8)); receiveVolume = getValidFloat(config.getDouble("sounds.received.volume", 0.5)); } private void loadSendSoundInfo(FileConfiguration config){ - String soundString = config.getString("sounds.sent.sound", "ENTITY_ALLAY_ITEM_THROWN"); - sendSound = getValidSound(soundString, Sound.ENTITY_ALLAY_ITEM_THROWN); + String soundString = config.getString("sounds.sent.sound", "minecraft:entity.allay.item_thrown"); + sendSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.ENTITY_ALLAY_ITEM_THROWN)); sendPitch = getValidFloat(config.getDouble("sounds.sent.pitch", 1.8)); sendVolume = getValidFloat(config.getDouble("sounds.sent.volume", 0.5)); } private void loadSpySoundInfo(FileConfiguration config){ - String soundString = config.getString("sounds.spy.sound", "ENTITY_ITEM_FRAME_ROTATE_ITEM"); - spySound = getValidSound(soundString, Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM); + String soundString = config.getString("sounds.spy.sound", "minecraft:entity.item_frame.rotate_item"); + spySound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM)); spyPitch = getValidFloat(config.getDouble("sounds.spy.pitch", 1.8)); spyVolume = getValidFloat(config.getDouble("sounds.spy.volume", 0.5)); } - private Sound getValidSound(String soundString, Sound defaultSound){ - Sound sound; - try { - sound = Sound.valueOf(soundString); - } catch (IllegalArgumentException exception) { + private NamespacedKey getValidSound(String soundString, NamespacedKey defaultSound){ + NamespacedKey key = NamespacedKey.fromString(soundString); + if (key == null || Registry.SOUNDS.get(key) == null) { String warning = LocaleMessage.LOG_ERROR_SOUND_NOT_VALID.getMessage().replace("%sound-string%", soundString); - String warning2 = LocaleMessage.LOG_ERROR_USING_DEFAULT_SOUND.getMessage().replace("%default-sound%", defaultSound.name()); + String warning2 = LocaleMessage.LOG_ERROR_USING_DEFAULT_SOUND.getMessage().replace("%default-sound%", defaultSound.getKey()); logger.warning(warning); logger.warning(warning2); - sound = defaultSound; + return defaultSound; } - return sound; + return key; } private float getValidFloat(double numberToCheck){ @@ -178,15 +179,15 @@ public String getSocialSpyFormat() { return socialSpyFormat; } - public Sound getReceiveSound() { + public NamespacedKey getReceiveSound() { return receiveSound; } - public Sound getSendSound() { + public NamespacedKey getSendSound() { return sendSound; } - public Sound getSpySound() { + public NamespacedKey getSpySound() { return spySound; } diff --git a/src/main/java/simplexity/simplepms/config/LocaleMessage.java b/src/main/java/simplexity/simplepms/config/LocaleMessage.java index 4b180ee..6499972 100644 --- a/src/main/java/simplexity/simplepms/config/LocaleMessage.java +++ b/src/main/java/simplexity/simplepms/config/LocaleMessage.java @@ -32,7 +32,9 @@ public enum LocaleMessage { ERROR_CANNOT_MESSAGE_CONSOLE("error.cannot-message-console", "Sorry, you cannot message the server"), ERROR_SOMETHING_WENT_WRONG("error.something-wrong", "Sorry, something went wrong, please check console for more information"), ERROR_NAME_NOT_FOUND("error.name-not-found", "Name not found"), - LOG_ERROR_SOUND_NOT_VALID("console-error.sound-not-valid", "Warning! The sound you have input: '%sound-string%' is invalid! Please be sure you use a sound that is listed on https://jd.papermc.io/paper/1.21.4/org/bukkit/Sound.html"), + LOG_ERROR_SOUND_NOT_VALID("console-error.sound-not-valid", "Warning! The sound you have input: '%sound-string%' is invalid! " + + "Sounds must now be in namespaced-key format, you can find the namespaced versions here: " + + "https://jd.papermc.io/paper/1.21.5/io/papermc/paper/registry/keys/SoundEventKeys.html"), LOG_ERROR_USING_DEFAULT_SOUND("console-error.using-default-sound", "Using %default-sound% until a valid sound is provided"), LOG_ERROR_FLOAT_OUT_OF_RANGE("console-error.float-out-of-range", "The number %number% is out of range! Volume and pitch values must be a number between 0 and 2!"), LOG_ERROR_USING_DEFAULT_FLOAT("console-error.using-default-float", "Setting to 1.0 until a valid value is provided"); diff --git a/src/main/java/simplexity/simplepms/logic/Constants.java b/src/main/java/simplexity/simplepms/logic/Constants.java index 402537d..c89439e 100644 --- a/src/main/java/simplexity/simplepms/logic/Constants.java +++ b/src/main/java/simplexity/simplepms/logic/Constants.java @@ -1,16 +1,47 @@ package simplexity.simplepms.logic; import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +import java.util.Map; public class Constants { - public static Permission MESSAGE_SEND = new Permission("message.basic.send"); - public static Permission MESSAGE_RECEIVE = new Permission("message.basic.receive"); - public static Permission MESSAGE_TOGGLE = new Permission("message.basic.toggle"); - public static Permission MESSAGE_BLOCK = new Permission("message.basic.block"); - public static Permission RELOAD = new Permission("message.reload"); - public static Permission ADMIN_OVERRIDE = new Permission("message.admin.override"); - public static Permission ADMIN_SOCIAL_SPY = new Permission("message.admin.social-spy"); - public static Permission ADMIN_CONSOLE_SPY = new Permission("message.admin.console-spy"); - public static Permission BYPASS_SOCIAL_SPY = new Permission("message.bypass.social-spy"); - public static Permission BYPASS_COMMAND_SPY = new Permission("message.bypass.command-spy"); + public static Permission MESSAGE_BASIC = new Permission("message.basic", "Base permission for basic functionality", + PermissionDefault.TRUE, Map.of( + "message.basic.send", true, + "message.basic.receive", true, + "message.basic.toggle", true, + "message.basic.block", true + )); + public static Permission MESSAGE_ADMIN = new Permission("message.admin", "Base permission for the admin commands", + PermissionDefault.OP, Map.of( + "message.admin.override", true, + "message.admin.social-spy", true, + "message.admin.console-spy", true + )); + + public static Permission MESSAGE_SEND = new Permission("message.basic.send", + "Allows sending messages", PermissionDefault.TRUE); + public static Permission MESSAGE_RECEIVE = new Permission("message.basic.receive", + "Allows receiving messages", PermissionDefault.TRUE); + public static Permission MESSAGE_TOGGLE = new Permission("message.basic.toggle", + "Allows enabling/disabling direct messages", PermissionDefault.TRUE); + public static Permission MESSAGE_BLOCK = new Permission("message.basic.block", + "Allows blocking direct messages from and to specific users", PermissionDefault.TRUE); + public static Permission PLUGIN_RELOAD = new Permission("message.reload", + "Reloads the Simple PMs plugin", PermissionDefault.OP); + public static Permission ADMIN_OVERRIDE = new Permission("message.admin.override", + "Allows messaging someone who has their messages currently disabled, " + + "has you blocked or does not have permissions to usually see messages", PermissionDefault.OP); + public static Permission ADMIN_SOCIAL_SPY = new Permission("message.admin.social-spy", + "Shows the direct messages of other players for moderation purposes", PermissionDefault.OP); + public static Permission ADMIN_CONSOLE_SPY = new Permission("message.admin.console-spy", + "Shows the direct messages sent to and from the console sender (from this plugin) " + + "to other players", PermissionDefault.OP); + public static Permission BYPASS_SOCIAL_SPY = new Permission("message.bypass.social-spy", + "Prevents messages to and from this player from showing in social spy, " + + "does not prevent the message from being formatted on console", PermissionDefault.OP); + public static Permission BYPASS_COMMAND_SPY = new Permission("message.bypass.command-spy", + "Stops your commands from being shown to others with command spy (if they are configured to be tracked). " + + "Does not prevent the message from being formatted on console", PermissionDefault.OP); } diff --git a/src/main/java/simplexity/simplepms/logic/PMHandler.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java index 6d67a26..c4cc3b9 100644 --- a/src/main/java/simplexity/simplepms/logic/PMHandler.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -1,5 +1,6 @@ package simplexity.simplepms.logic; +import org.bukkit.Registry; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; @@ -37,7 +38,7 @@ private static void handleMessageSend(CommandSender initiator, CommandSender tar if (!ConfigHandler.getInstance().sendingMessagePlaysSound()) return; if (!(initiator instanceof Player player)) return; player.playSound(player, - ConfigHandler.getInstance().getSendSound(), + Registry.SOUNDS.get(ConfigHandler.getInstance().getSendSound()), ConfigHandler.getInstance().getSendVolume(), ConfigHandler.getInstance().getSendPitch()); } @@ -49,7 +50,7 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender if (!ConfigHandler.getInstance().receivingMessagePlaysSound()) return; if (!(target instanceof Player player)) return; player.playSound(player, - ConfigHandler.getInstance().getReceiveSound(), + Registry.SOUNDS.get(ConfigHandler.getInstance().getReceiveSound()), ConfigHandler.getInstance().getReceiveVolume(), ConfigHandler.getInstance().getReceivePitch()); } diff --git a/src/main/java/simplexity/simplepms/logic/SpyHandler.java b/src/main/java/simplexity/simplepms/logic/SpyHandler.java index 0fca2bf..278b806 100644 --- a/src/main/java/simplexity/simplepms/logic/SpyHandler.java +++ b/src/main/java/simplexity/simplepms/logic/SpyHandler.java @@ -1,6 +1,7 @@ package simplexity.simplepms.logic; import net.kyori.adventure.text.Component; +import org.bukkit.Registry; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; @@ -65,7 +66,7 @@ public static void handleConsoleSpy(PrivateMessageEvent messageEvent) { private static void playSpySound(Player spyingPlayer) { if (!ConfigHandler.getInstance().messagePlaysSoundForSpy()) return; spyingPlayer.playSound(spyingPlayer, - ConfigHandler.getInstance().getSpySound(), + Registry.SOUNDS.get(ConfigHandler.getInstance().getSpySound()), ConfigHandler.getInstance().getSpyVolume(), ConfigHandler.getInstance().getSpyPitch()); } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 7e2349d..1729f97 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -37,16 +37,16 @@ command-spy: sounds: received: enabled: false - sound: BLOCK_NOTE_BLOCK_XYLOPHONE + sound: minecraft:block.note_block.xylophone pitch: 1.8 volume: 0.5 sent: enabled: false - sound: ENTITY_ALLAY_ITEM_THROWN + sound: minecraft:entity.allay.item_thrown pitch: 1.8 volume: 0.5 spy: enabled: false - sound: ENTITY_ITEM_FRAME_ROTATE_ITEM + sound: minecraft:entity.item_frame.rotate_item pitch: 1.8 - volume: 0.5 \ No newline at end of file + volume: 0.5 diff --git a/src/main/resources/paper-plugin.yml b/src/main/resources/paper-plugin.yml new file mode 100644 index 0000000..cef7ba5 --- /dev/null +++ b/src/main/resources/paper-plugin.yml @@ -0,0 +1,10 @@ +name: SimplePMs +version: '${project.version}' +main: simplexity.simplepms.SimplePMs +api-version: 1.20.6 +description: Plugin focused on simple private messaging. +dependencies: + server: + PlaceholderAPI: + load: OMIT + required: false diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml deleted file mode 100644 index fec4653..0000000 --- a/src/main/resources/plugin.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: SimplePMs -version: '${project.version}' -main: simplexity.simplepms.SimplePMs -api-version: 1.20.6 -authors: [ Rhythmic, Peashooter101 ] -description: Plugin focused on simple private messaging. -softdepend: - - PlaceholderAPI -permissions: - message.basic: - default: true - description: Base permission for basic functionality - children: - message.basic.send: true - message.basic.receive: true - message.basic.toggle: true - message.basic.block: true - message.basic.send: - default: true - description: Allows sending messages - message.basic.receive: - default: true - description: Allows receiving messages - message.basic.toggle: - default: true - description: Allows enabling/disabling direct messages - message.basic.block: - default: true - description: Allows blocking direct messages from and to specific users - message.reload: - default: op - description: reloads the config and locale - message.admin: - default: op - description: Base permission for the admin commands - children: - message.admin.override: true - message.admin.social-spy: true - message.admin.console-spy: true - message.admin.override: - default: op - description: Allows messaging someone who has their messages currently disabled, has you blocked or does not have permissions to usually see messages - message.admin.social-spy: - default: op - description: Shows the direct messages of other players for moderation purposes - message.admin.console-spy: - default: op - description: Shows the direct messages sent to and from the console sender (from this plugin) to other players - message.bypass.social-spy: - default: op - description: Prevents messages to and from you from showing in social spy, does not prevent the formatted console spy message - message.bypass.command-spy: - default: op - description: Stops your commands from being shown to others with command spy (if they are configured to be tracked). Does not prevent the formatted console spy message From 692882341f839eeac7e595381c2ab62aa7ac9375 Mon Sep 17 00:00:00 2001 From: Rhythmic System Date: Fri, 6 Jun 2025 13:48:40 -0700 Subject: [PATCH 10/10] cleanup --- .../java/simplexity/simplepms/SimplePMs.java | 33 ++++++++++++++----- .../simplepms/commands/PrivateMessage.java | 4 +-- .../simplepms/commands/SocialSpy.java | 6 ++-- .../simplepms/commands/Unblock.java | 2 +- .../commands/arguments/TargetArgument.java | 3 +- .../commands/util/MessageChecks.java | 25 ++++++++------ .../simplepms/config/ConfigHandler.java | 27 ++++++++------- .../simplepms/events/BlockUserEvent.java | 2 ++ .../simplepms/events/PrivateMessageEvent.java | 5 ++- .../simplepms/events/UnblockUserEvent.java | 1 + .../simplepms/logic/BlockHandler.java | 4 +-- .../simplepms/logic/MessageUtils.java | 4 +-- .../simplexity/simplepms/logic/PMHandler.java | 13 ++++---- .../simplepms/logic/SpyHandler.java | 6 ++-- .../simplepms/logic/UnblockHandler.java | 2 +- .../saving/objects/PlayerSettings.java | 4 +-- src/main/resources/paper-plugin.yml | 2 +- 17 files changed, 86 insertions(+), 57 deletions(-) diff --git a/src/main/java/simplexity/simplepms/SimplePMs.java b/src/main/java/simplexity/simplepms/SimplePMs.java index ddea4be..c62e689 100644 --- a/src/main/java/simplexity/simplepms/SimplePMs.java +++ b/src/main/java/simplexity/simplepms/SimplePMs.java @@ -32,19 +32,32 @@ public final class SimplePMs extends JavaPlugin { @Override public void onEnable() { instance = this; - this.getServer().getPluginManager().registerEvents(new QuitListener(), this); - this.getServer().getPluginManager().registerEvents(new PreCommandListener(), this); - this.getServer().getPluginManager().registerEvents(new JoinListener(), this); - if (this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { + consoleSender = getServer().getConsoleSender(); + if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { papiEnabled = true; } - consoleSender = this.getServer().getConsoleSender(); - this.saveDefaultConfig(); + SqlHandler.getInstance().init(); + loadConfigStuff(); + registerListeners(); + registerCommands(); + registerPermissions(); + } + + private void registerListeners() { + getServer().getPluginManager().registerEvents(new QuitListener(), this); + getServer().getPluginManager().registerEvents(new PreCommandListener(), this); + getServer().getPluginManager().registerEvents(new JoinListener(), this); + } + + private void loadConfigStuff() { + saveDefaultConfig(); getConfig().options().copyDefaults(true); saveConfig(); ConfigHandler.getInstance().loadConfigValues(); - SqlHandler.getInstance().init(); - this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { + } + + private void registerCommands() { + getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> { commands.registrar().register(PrivateMessage.createCommand()); commands.registrar().register(PrivateMessage.createTellAlias()); commands.registrar().register(PrivateMessage.createWhisperAlias()); @@ -58,6 +71,9 @@ public void onEnable() { commands.registrar().register(Reload.createCommand()); commands.registrar().register(Blocklist.createCommand()); }); + } + + private void registerPermissions() { getServer().getPluginManager().addPermission(Constants.MESSAGE_BASIC); getServer().getPluginManager().addPermission(Constants.MESSAGE_ADMIN); getServer().getPluginManager().addPermission(Constants.MESSAGE_SEND); @@ -73,7 +89,6 @@ public void onEnable() { } @Override - public void onDisable() { SqlHandler.getInstance().shutdownConnection(); } diff --git a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java index 77ba420..977de2a 100644 --- a/src/main/java/simplexity/simplepms/commands/PrivateMessage.java +++ b/src/main/java/simplexity/simplepms/commands/PrivateMessage.java @@ -9,11 +9,11 @@ import io.papermc.paper.command.brigadier.CommandSourceStack; import io.papermc.paper.command.brigadier.Commands; import org.bukkit.command.CommandSender; +import simplexity.simplepms.commands.arguments.Target; import simplexity.simplepms.commands.arguments.TargetArgument; import simplexity.simplepms.commands.util.MessageChecks; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.PMHandler; -import simplexity.simplepms.commands.arguments.Target; @SuppressWarnings("UnstableApiUsage") public class PrivateMessage { @@ -40,7 +40,7 @@ public static LiteralCommandNode createWhisperAlias() { .then(messageArg())).build(); } - private static RequiredArgumentBuilder targetArg(){ + private static RequiredArgumentBuilder targetArg() { TargetArgument targetArg = new TargetArgument(); return Commands.argument("target", targetArg) .suggests(targetArg::suggestOnlinePlayers); diff --git a/src/main/java/simplexity/simplepms/commands/SocialSpy.java b/src/main/java/simplexity/simplepms/commands/SocialSpy.java index 1fef05d..8e805a7 100644 --- a/src/main/java/simplexity/simplepms/commands/SocialSpy.java +++ b/src/main/java/simplexity/simplepms/commands/SocialSpy.java @@ -16,19 +16,19 @@ @SuppressWarnings({"UnstableApiUsage", "SameReturnValue"}) public class SocialSpy { - public static LiteralCommandNode createCommand(){ + public static LiteralCommandNode createCommand() { return Commands.literal("socialspy") .requires(SocialSpy::canExecute) .executes(SocialSpy::execute).build(); } - public static LiteralCommandNode createAlias(){ + public static LiteralCommandNode createAlias() { return Commands.literal("ss") .requires(SocialSpy::canExecute) .executes(SocialSpy::execute).build(); } - private static boolean canExecute(CommandSourceStack css){ + private static boolean canExecute(CommandSourceStack css) { if (!(css.getSender() instanceof Player)) return false; return css.getSender().hasPermission(Constants.ADMIN_SOCIAL_SPY); } diff --git a/src/main/java/simplexity/simplepms/commands/Unblock.java b/src/main/java/simplexity/simplepms/commands/Unblock.java index 96f2a9e..072aaf3 100644 --- a/src/main/java/simplexity/simplepms/commands/Unblock.java +++ b/src/main/java/simplexity/simplepms/commands/Unblock.java @@ -18,8 +18,8 @@ import simplexity.simplepms.config.LocaleMessage; import simplexity.simplepms.logic.Constants; import simplexity.simplepms.logic.UnblockHandler; -import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; +import simplexity.simplepms.saving.objects.PlayerBlock; import java.util.List; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java index 0760243..1f48525 100644 --- a/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java +++ b/src/main/java/simplexity/simplepms/commands/arguments/TargetArgument.java @@ -28,7 +28,8 @@ public class TargetArgument implements CustomArgumentType { @Override public @NotNull Target parse(@NotNull StringReader reader) throws CommandSyntaxException { String targetName = reader.readString(); - if (ConfigHandler.getInstance().getValidNamesForConsole().contains(targetName.toLowerCase())) return new Target(consoleSender, targetName); + if (ConfigHandler.getInstance().getValidNamesForConsole().contains(targetName.toLowerCase())) + return new Target(consoleSender, targetName); Player targetPlayer = Bukkit.getPlayerExact(targetName); if (targetPlayer != null) return new Target(targetPlayer, targetName); throw Exceptions.ERROR_INVALID_USER.create(targetName); diff --git a/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java index bd07c5f..48b191e 100644 --- a/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java +++ b/src/main/java/simplexity/simplepms/commands/util/MessageChecks.java @@ -5,9 +5,9 @@ import org.bukkit.entity.Player; import simplexity.simplepms.config.ConfigHandler; import simplexity.simplepms.logic.Constants; +import simplexity.simplepms.saving.Cache; import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.objects.PlayerSettings; -import simplexity.simplepms.saving.Cache; import java.util.List; @@ -15,17 +15,17 @@ public class MessageChecks { public static void userChecks(CommandSender initiator, CommandSender target, String providedName) throws CommandSyntaxException { - if (target instanceof Player playerTarget) { - if (!initiator.hasPermission(Constants.ADMIN_OVERRIDE)) { - targetCanGetMessageCheck(playerTarget); - } - if (initiator instanceof Player playerInitiator) { - MessageChecks.ownMessagesDisabledCheck(playerInitiator); - MessageChecks.initiatorBlockedTargetCheck(playerInitiator, playerTarget); + if (initiator instanceof Player playerInitiator) { + ownMessagesDisabledCheck(playerInitiator); + if (target instanceof Player playerTarget) { + initiatorBlockedTargetCheck(playerInitiator, playerTarget); if (!initiator.hasPermission(Constants.ADMIN_OVERRIDE)) { - MessageChecks.targetBlockedInitiatorCheck(playerInitiator, playerTarget); - MessageChecks.vanishCheck(playerInitiator, playerTarget, providedName); + targetCanGetMessageCheck(playerTarget); + targetBlockedInitiatorCheck(playerInitiator, playerTarget); + vanishCheck(playerInitiator, playerTarget, providedName); } + } else { + canSendToConsole(providedName); } } } @@ -58,6 +58,11 @@ private static void initiatorBlockedTargetCheck(Player initiatingPlayer, Player throw Exceptions.ERROR_CANNOT_MESSAGE_SOMEONE_YOU_HAVE_BLOCKED.create(); } + private static void canSendToConsole(String providedName) throws CommandSyntaxException { + if (!ConfigHandler.getInstance().canPlayersSendToConsole()) + throw Exceptions.ERROR_INVALID_USER.create(providedName); + } + private static boolean userBlocked(Player blocklistPlayer, Player potentialBlock) { List playerBlocks = Cache.blockList.get(blocklistPlayer.getUniqueId()); if (playerBlocks == null) { diff --git a/src/main/java/simplexity/simplepms/config/ConfigHandler.java b/src/main/java/simplexity/simplepms/config/ConfigHandler.java index 5108a50..8940e2d 100644 --- a/src/main/java/simplexity/simplepms/config/ConfigHandler.java +++ b/src/main/java/simplexity/simplepms/config/ConfigHandler.java @@ -1,10 +1,10 @@ package simplexity.simplepms.config; -import net.kyori.adventure.key.Key; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.Sound; import org.bukkit.configuration.file.FileConfiguration; +import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import java.util.ArrayList; @@ -23,7 +23,9 @@ public static ConfigHandler getInstance() { private final Logger logger = SimplePMs.getInstance().getLogger(); private boolean mysqlEnabled, playersSendToConsole, playersSendToHiddenPlayers, consoleHasSocialSpy, commandSpyEnabled, consoleHasCommandSpy, receiveSoundEnabled, sendSoundEnabled, spySoundEnabled; - private NamespacedKey receiveSound, sendSound, spySound; + private NamespacedKey receiveSound = Registry.SOUNDS.getKey(Sound.BLOCK_NOTE_BLOCK_XYLOPHONE); + private NamespacedKey sendSound = Registry.SOUNDS.getKey(Sound.ENTITY_ALLAY_ITEM_THROWN); + private NamespacedKey spySound = Registry.SOUNDS.getKey(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM); private float receivePitch, receiveVolume, sendPitch, sendVolume, spyPitch, spyVolume; private String mysqlIp, mysqlName, mysqlUsername, mysqlPassword, normalFormat, socialSpyFormat; private final List validNamesForConsole = new ArrayList<>(); @@ -64,26 +66,26 @@ private void updateHashSet(HashSet set, List list) { private void loadReceiveSoundInfo(FileConfiguration config) { String soundString = config.getString("sounds.received.sound", "minecraft:block.note_block.xylophone"); - receiveSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.BLOCK_NOTE_BLOCK_XYLOPHONE)); + receiveSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.BLOCK_NOTE_BLOCK_XYLOPHONE)); receivePitch = getValidFloat(config.getDouble("sounds.received.pitch", 1.8)); receiveVolume = getValidFloat(config.getDouble("sounds.received.volume", 0.5)); } - private void loadSendSoundInfo(FileConfiguration config){ + private void loadSendSoundInfo(FileConfiguration config) { String soundString = config.getString("sounds.sent.sound", "minecraft:entity.allay.item_thrown"); - sendSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.ENTITY_ALLAY_ITEM_THROWN)); + sendSound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.ENTITY_ALLAY_ITEM_THROWN)); sendPitch = getValidFloat(config.getDouble("sounds.sent.pitch", 1.8)); sendVolume = getValidFloat(config.getDouble("sounds.sent.volume", 0.5)); } - private void loadSpySoundInfo(FileConfiguration config){ + private void loadSpySoundInfo(FileConfiguration config) { String soundString = config.getString("sounds.spy.sound", "minecraft:entity.item_frame.rotate_item"); spySound = getValidSound(soundString, Registry.SOUNDS.getKey(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM)); spyPitch = getValidFloat(config.getDouble("sounds.spy.pitch", 1.8)); spyVolume = getValidFloat(config.getDouble("sounds.spy.volume", 0.5)); } - private NamespacedKey getValidSound(String soundString, NamespacedKey defaultSound){ + private NamespacedKey getValidSound(String soundString, NamespacedKey defaultSound) { NamespacedKey key = NamespacedKey.fromString(soundString); if (key == null || Registry.SOUNDS.get(key) == null) { String warning = LocaleMessage.LOG_ERROR_SOUND_NOT_VALID.getMessage().replace("%sound-string%", soundString); @@ -95,7 +97,7 @@ private NamespacedKey getValidSound(String soundString, NamespacedKey defaultSou return key; } - private float getValidFloat(double numberToCheck){ + private float getValidFloat(double numberToCheck) { if (numberToCheck <= 2 && numberToCheck >= 0) return (float) numberToCheck; String warning = LocaleMessage.LOG_ERROR_FLOAT_OUT_OF_RANGE.getMessage().replace("%number%", String.valueOf(numberToCheck)); logger.warning(warning); @@ -159,15 +161,15 @@ public boolean isCommandSpyEnabled() { return commandSpyEnabled; } - public boolean receivingMessagePlaysSound(){ + public boolean receivingMessagePlaysSound() { return receiveSoundEnabled; } - public boolean sendingMessagePlaysSound(){ + public boolean sendingMessagePlaysSound() { return sendSoundEnabled; } - public boolean messagePlaysSoundForSpy(){ + public boolean messagePlaysSoundForSpy() { return spySoundEnabled; } @@ -179,14 +181,17 @@ public String getSocialSpyFormat() { return socialSpyFormat; } + @NotNull public NamespacedKey getReceiveSound() { return receiveSound; } + @NotNull public NamespacedKey getSendSound() { return sendSound; } + @NotNull public NamespacedKey getSpySound() { return spySound; } diff --git a/src/main/java/simplexity/simplepms/events/BlockUserEvent.java b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java index a7ce1bf..d2ddf64 100644 --- a/src/main/java/simplexity/simplepms/events/BlockUserEvent.java +++ b/src/main/java/simplexity/simplepms/events/BlockUserEvent.java @@ -69,6 +69,7 @@ public static HandlerList getHandlerList() { /** * Gets the UUID of the player doing the blocking + * * @return UUID */ @@ -129,6 +130,7 @@ public String getBlockedPlayerName() { * This is solely for player-readable identification * This is used in the block list and in the unblock command, but UUID is used for actual verification. * Display names can be used here + * * @param blockedPlayerName String name */ public void setBlockedPlayerName(@NotNull String blockedPlayerName) { diff --git a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java index 515ffe5..498a913 100644 --- a/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java +++ b/src/main/java/simplexity/simplepms/events/PrivateMessageEvent.java @@ -68,7 +68,7 @@ public CommandSender getRecipient() { * @param recipient CommandSender */ - public void setRecipient(CommandSender recipient){ + public void setRecipient(CommandSender recipient) { this.recipient = recipient; } @@ -88,7 +88,7 @@ public String getMessageContent() { * @param messageContent String */ - public void setMessageContent(String messageContent){ + public void setMessageContent(String messageContent) { this.messageContent = messageContent; } @@ -139,4 +139,3 @@ public static HandlerList getHandlerList() { return handlers; } } - diff --git a/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java index 9ff215f..fc91969 100644 --- a/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java +++ b/src/main/java/simplexity/simplepms/events/UnblockUserEvent.java @@ -21,6 +21,7 @@ public UnblockUserEvent(UUID initiatorUuid, UUID blockedPlayerUuid) { /** * Gets whether this event has been cancelled + * * @return boolean Cancelled */ diff --git a/src/main/java/simplexity/simplepms/logic/BlockHandler.java b/src/main/java/simplexity/simplepms/logic/BlockHandler.java index c8c6217..d8349c5 100644 --- a/src/main/java/simplexity/simplepms/logic/BlockHandler.java +++ b/src/main/java/simplexity/simplepms/logic/BlockHandler.java @@ -5,8 +5,8 @@ import org.jetbrains.annotations.NotNull; import simplexity.simplepms.SimplePMs; import simplexity.simplepms.events.BlockUserEvent; -import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; +import simplexity.simplepms.saving.objects.PlayerBlock; import javax.annotation.Nullable; @@ -23,7 +23,7 @@ public static void addBlockedPlayer(@NotNull Player blockingPlayer, @NotNull Off Cache.addBlockedUser(blockingPlayer.getUniqueId(), playerBlock); } - private static BlockUserEvent callBlockEvent(@NotNull Player blockingPlayer, @NotNull OfflinePlayer playerToBlock, @Nullable String reason){ + private static BlockUserEvent callBlockEvent(@NotNull Player blockingPlayer, @NotNull OfflinePlayer playerToBlock, @Nullable String reason) { String blockedPlayerName = playerToBlock.getName(); if (blockedPlayerName == null) blockedPlayerName = "[NO NAME FOUND]"; BlockUserEvent blockUserEvent = new BlockUserEvent(blockingPlayer.getUniqueId(), playerToBlock.getUniqueId(), blockedPlayerName, reason); diff --git a/src/main/java/simplexity/simplepms/logic/MessageUtils.java b/src/main/java/simplexity/simplepms/logic/MessageUtils.java index 5768281..bebb868 100644 --- a/src/main/java/simplexity/simplepms/logic/MessageUtils.java +++ b/src/main/java/simplexity/simplepms/logic/MessageUtils.java @@ -46,8 +46,6 @@ public Component parseMessage(String localeMessage, @NotNull CommandSender initi } - - private Component getCommmandSenderComponent(CommandSender sender, boolean socialSpy) { if (!(sender instanceof Player player)) { if (socialSpy) return miniMessage.deserialize(LocaleMessage.CONSOLE_NAME_SOCIAL_SPY.getMessage()); @@ -80,7 +78,7 @@ private Component parsePapiName(Player player, String message) { public TagResolver papiTag(final Player player) { if (player == null) return TagResolver.empty(); - return TagResolver.resolver("papi", (argumentQueue, context) -> { + return TagResolver.resolver("papi", (argumentQueue, _) -> { final String papiPlaceholder = argumentQueue.popOr("PLACEHOLDER API NEEDS ARGUMENT").value(); final String parsedPlaceholder = PlaceholderAPI.setPlaceholders(player, '%' + papiPlaceholder + '%'); final Component componentPlaceholder = LegacyComponentSerializer.legacySection().deserialize(parsedPlaceholder); diff --git a/src/main/java/simplexity/simplepms/logic/PMHandler.java b/src/main/java/simplexity/simplepms/logic/PMHandler.java index c4cc3b9..ca17c7b 100644 --- a/src/main/java/simplexity/simplepms/logic/PMHandler.java +++ b/src/main/java/simplexity/simplepms/logic/PMHandler.java @@ -1,6 +1,7 @@ package simplexity.simplepms.logic; import org.bukkit.Registry; +import org.bukkit.Sound; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; @@ -37,8 +38,9 @@ private static void handleMessageSend(CommandSender initiator, CommandSender tar initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().sendingMessagePlaysSound()) return; if (!(initiator instanceof Player player)) return; - player.playSound(player, - Registry.SOUNDS.get(ConfigHandler.getInstance().getSendSound()), + Sound sound = Registry.SOUNDS.get(ConfigHandler.getInstance().getSendSound()); + if (sound == null) return; + player.playSound(player, sound, ConfigHandler.getInstance().getSendVolume(), ConfigHandler.getInstance().getSendPitch()); } @@ -49,15 +51,14 @@ private static void handleMessageReceive(CommandSender initiator, CommandSender initiator, target, messageContent, false)); if (!ConfigHandler.getInstance().receivingMessagePlaysSound()) return; if (!(target instanceof Player player)) return; - player.playSound(player, - Registry.SOUNDS.get(ConfigHandler.getInstance().getReceiveSound()), + Sound sound = Registry.SOUNDS.get(ConfigHandler.getInstance().getReceiveSound()); + if (sound == null) return; + player.playSound(player, sound, ConfigHandler.getInstance().getReceiveVolume(), ConfigHandler.getInstance().getReceivePitch()); } - - private static PrivateMessageEvent callPMEvent(CommandSender initiator, CommandSender target, String messageContent) { PrivateMessageEvent messageEvent = new PrivateMessageEvent(initiator, target, messageContent, Cache.getSpyingPlayers()); SimplePMs.getInstance().getServer().getPluginManager().callEvent(messageEvent); diff --git a/src/main/java/simplexity/simplepms/logic/SpyHandler.java b/src/main/java/simplexity/simplepms/logic/SpyHandler.java index 278b806..5847f8f 100644 --- a/src/main/java/simplexity/simplepms/logic/SpyHandler.java +++ b/src/main/java/simplexity/simplepms/logic/SpyHandler.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import org.bukkit.Registry; +import org.bukkit.Sound; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import simplexity.simplepms.SimplePMs; @@ -65,8 +66,9 @@ public static void handleConsoleSpy(PrivateMessageEvent messageEvent) { private static void playSpySound(Player spyingPlayer) { if (!ConfigHandler.getInstance().messagePlaysSoundForSpy()) return; - spyingPlayer.playSound(spyingPlayer, - Registry.SOUNDS.get(ConfigHandler.getInstance().getSpySound()), + Sound sound = Registry.SOUNDS.get(ConfigHandler.getInstance().getSpySound()); + if (sound == null) return; + spyingPlayer.playSound(spyingPlayer, sound, ConfigHandler.getInstance().getSpyVolume(), ConfigHandler.getInstance().getSpyPitch()); } diff --git a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java index 97b6650..4b71693 100644 --- a/src/main/java/simplexity/simplepms/logic/UnblockHandler.java +++ b/src/main/java/simplexity/simplepms/logic/UnblockHandler.java @@ -6,8 +6,8 @@ import org.jetbrains.annotations.NotNull; import simplexity.simplepms.commands.util.Exceptions; import simplexity.simplepms.events.UnblockUserEvent; -import simplexity.simplepms.saving.objects.PlayerBlock; import simplexity.simplepms.saving.Cache; +import simplexity.simplepms.saving.objects.PlayerBlock; import java.util.List; import java.util.UUID; diff --git a/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java b/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java index 8a1e62f..7edb289 100644 --- a/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java +++ b/src/main/java/simplexity/simplepms/saving/objects/PlayerSettings.java @@ -22,8 +22,8 @@ public PlayerSettings(UUID playerUUID) { public String toString() { return "Player UUID: " + playerUUID.toString() - + "\nSocial Spy Enabled: " + socialSpyEnabled - + "\nMessages Enabled: " + messagesDisabled; + + "\nSocial Spy Enabled: " + socialSpyEnabled + + "\nMessages Enabled: " + messagesDisabled; } public UUID getPlayerUUID() { diff --git a/src/main/resources/paper-plugin.yml b/src/main/resources/paper-plugin.yml index cef7ba5..b7235b7 100644 --- a/src/main/resources/paper-plugin.yml +++ b/src/main/resources/paper-plugin.yml @@ -6,5 +6,5 @@ description: Plugin focused on simple private messaging. dependencies: server: PlaceholderAPI: - load: OMIT + load: BEFORE required: false