From cd34a7071e8cd448355c87af8f02c4cc47dab788 Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 15 Sep 2024 20:24:24 +0930 Subject: [PATCH 01/45] Project cleanup --- src/main/java/io/shantek/PostOffice.java | 9 +++------ src/main/java/io/shantek/functions/Commands.java | 3 --- src/main/java/io/shantek/functions/Helpers.java | 9 +++++---- src/main/java/io/shantek/functions/PluginConfig.java | 9 +++++---- src/main/java/io/shantek/functions/TabCompleter.java | 1 - 5 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 2302812..eb849d5 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -1,16 +1,13 @@ package io.shantek; +import io.shantek.functions.*; +import io.shantek.listeners.*; + import java.io.File; import java.io.IOException; import java.util.logging.*; import java.util.stream.Collectors; - -import io.shantek.functions.*; -import io.shantek.listeners.*; import org.bukkit.Bukkit; -import org.bukkit.command.PluginCommand; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.permissions.Permission; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 0fe4a70..7a8a59a 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -6,9 +6,6 @@ import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; -import java.util.ArrayList; -import java.util.List; - public class Commands implements CommandExecutor { public PostOffice postOffice; diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index ac6d1d1..462034a 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -1,6 +1,11 @@ package io.shantek.functions; import io.shantek.PostOffice; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.logging.Level; + import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.block.Barrel; @@ -8,10 +13,6 @@ import org.bukkit.block.BlockFace; import org.bukkit.inventory.ItemStack; -import java.io.IOException; -import java.nio.file.Files; -import java.util.logging.Level; - public class Helpers { private final PostOffice postOffice; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 024cb43..6601302 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -1,17 +1,18 @@ package io.shantek.functions; +import io.shantek.PostOffice; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.logging.Level; +import java.nio.file.*; +import java.util.*; -import io.shantek.PostOffice; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import java.nio.file.*; -import java.util.*; -@SuppressWarnings("SameParameterValue") + public class PluginConfig { private final PostOffice postOffice; diff --git a/src/main/java/io/shantek/functions/TabCompleter.java b/src/main/java/io/shantek/functions/TabCompleter.java index d81b585..58cb227 100644 --- a/src/main/java/io/shantek/functions/TabCompleter.java +++ b/src/main/java/io/shantek/functions/TabCompleter.java @@ -3,7 +3,6 @@ import io.shantek.PostOffice; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; - import java.util.ArrayList; import java.util.List; From 2b4b8afbd7bab4a4df362e52bda3f98b8f819a3f Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 15 Sep 2024 20:32:45 +0930 Subject: [PATCH 02/45] Refactoring code --- src/main/java/io/shantek/PostOffice.java | 3 - .../java/io/shantek/functions/Helpers.java | 66 ++++++++++++++----- .../shantek/listeners/BarrelProtection.java | 35 +--------- .../io/shantek/listeners/InventoryClick.java | 2 + .../io/shantek/listeners/InventoryClose.java | 1 + .../io/shantek/listeners/InventoryOpen.java | 1 + 6 files changed, 56 insertions(+), 52 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index eb849d5..8bd4ffa 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -25,9 +25,7 @@ public final class PostOffice extends JavaPlugin { public Helpers helpers; public BarrelProtection barrelProtection; public TabCompleter tabCompleter; - public static PostOffice instance; - public String customBarrelName = "pobox"; public File mailFile; public int previousItemCount = 0; @@ -136,5 +134,4 @@ private void registerPluginPermissions() { pm.addPermission(updateNotificationPermission); } - } \ No newline at end of file diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 462034a..17d58de 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -21,15 +21,32 @@ public Helpers(PostOffice postOffice) { this.postOffice = postOffice; } - public void saveMailFile() { - try { - if (postOffice.consoleLogs) { - postOffice.getLogger().info("The mail list has been updated."); + public boolean hasBarrelNearby(Block block) { + // Check if the given block is a barrel with the custom name + if (block.getType() == Material.BARREL) { + Barrel barrel = (Barrel) block.getState(); + String barrelCustomName = barrel.getCustomName(); + + if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + return true; + } + } + + // Check if any nearby block is a barrel with the custom name + for (BlockFace blockFace : BlockFace.values()) { + Block relativeBlock = block.getRelative(blockFace); + + if (relativeBlock.getType() == Material.BARREL) { + Barrel barrel = (Barrel) relativeBlock.getState(); + String barrelCustomName = barrel.getCustomName(); + + if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + return true; + } } - Files.write(postOffice.mailFile.toPath(), postOffice.playersWithMail); - } catch (IOException e) { - postOffice.getLogger().log(Level.SEVERE, "Error updating the mail file.", e); } + + return false; } public int countNonNullItems(ItemStack[] items) { @@ -42,16 +59,6 @@ public int countNonNullItems(ItemStack[] items) { return count; } - public void checkForDataFolder() { - if (!postOffice.getDataFolder().exists()) { - if (postOffice.getDataFolder().mkdir()) { - postOffice.getLogger().info("Data folder created successfully."); - } else { - postOffice.getLogger().warning("Error creating the data folder."); - } - } - } - public boolean isProtectedPostBox(Block block) { if (block.getType() == Material.BARREL) { Barrel barrel = (Barrel) block.getState(); @@ -80,4 +87,29 @@ public boolean isSignNextToProtectedBarrel(Block signBlock) { } return false; } + + //region Plugin Configuration + + public void checkForDataFolder() { + if (!postOffice.getDataFolder().exists()) { + if (postOffice.getDataFolder().mkdir()) { + postOffice.getLogger().info("Data folder created successfully."); + } else { + postOffice.getLogger().warning("Error creating the data folder."); + } + } + } + + public void saveMailFile() { + try { + if (postOffice.consoleLogs) { + postOffice.getLogger().info("The mail list has been updated."); + } + Files.write(postOffice.mailFile.toPath(), postOffice.playersWithMail); + } catch (IOException e) { + postOffice.getLogger().log(Level.SEVERE, "Error updating the mail file.", e); + } + } + + //endregion } diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index d88df86..e343736 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -2,7 +2,6 @@ import io.shantek.PostOffice; import org.bukkit.ChatColor; -import org.bukkit.Material; import org.bukkit.block.*; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; @@ -37,7 +36,7 @@ public void onSignChange(SignChangeEvent event) { Player player = event.getPlayer(); Block signBlock = event.getBlock(); - if (hasBarrelNearby(signBlock)) { + if (postOffice.helpers.hasBarrelNearby(signBlock)) { if (!player.isOp() && !player.hasPermission("shantek.postoffice.create")) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.createError)); event.setCancelled(true); @@ -76,7 +75,7 @@ public void onBlockBreak(BlockBreakEvent event) { // Check if the broken block is a sign if (brokenBlock.getState() instanceof Sign) { - if (hasBarrelNearby(brokenBlock)) { + if (postOffice.helpers.hasBarrelNearby(brokenBlock)) { if (!player.isOp() && !player.hasPermission("shantek.postoffice.break")) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); event.setCancelled(true); @@ -94,7 +93,7 @@ public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); Block placedBlock = event.getBlockPlaced(); - if (placedBlock.getState() instanceof Sign && hasBarrelNearby(placedBlock)) { + if (placedBlock.getState() instanceof Sign && postOffice.helpers.hasBarrelNearby(placedBlock)) { if (!player.isOp() && !player.hasPermission("shantek.postoffice.create")) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.createError)); placedBlock.breakNaturally(); @@ -102,34 +101,6 @@ public void onBlockPlace(BlockPlaceEvent event) { } } - private boolean hasBarrelNearby(Block block) { - // Check if the given block is a barrel with the custom name - if (block.getType() == Material.BARREL) { - Barrel barrel = (Barrel) block.getState(); - String barrelCustomName = barrel.getCustomName(); - - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - return true; - } - } - - // Check if any nearby block is a barrel with the custom name - for (BlockFace blockFace : BlockFace.values()) { - Block relativeBlock = block.getRelative(blockFace); - - if (relativeBlock.getType() == Material.BARREL) { - Barrel barrel = (Barrel) relativeBlock.getState(); - String barrelCustomName = barrel.getCustomName(); - - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - return true; - } - } - } - - return false; - } - @EventHandler public void onInventoryMoveItem(InventoryMoveItemEvent event) { if (!postOffice.postBoxProtection) { diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index e6ccedf..e08c821 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -21,6 +21,7 @@ public class InventoryClick implements Listener { public PostOffice postOffice; + public InventoryClick(PostOffice postOffice) { this.postOffice = postOffice; } @@ -149,4 +150,5 @@ public void onInventoryClick(InventoryClickEvent event) { } } } + } \ No newline at end of file diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 6983d52..40316db 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -98,4 +98,5 @@ public void onInventoryClose(InventoryCloseEvent event) { } } } + } \ No newline at end of file diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index 294d377..4060be9 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -15,6 +15,7 @@ public class InventoryOpen implements Listener { public PostOffice postOffice; + public InventoryOpen(PostOffice postOffice) { this.postOffice = postOffice; } From 5ec167ae7fe56edd99ec93057322d3706daf0048 Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 15 Sep 2024 20:33:37 +0930 Subject: [PATCH 03/45] Added exception logging for config file --- src/main/java/io/shantek/functions/PluginConfig.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 6601302..f652eae 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -209,6 +209,7 @@ private void saveConfigSilently(FileConfiguration config) { config.save(new File(postOffice.getDataFolder(), "config.yml")); } catch (IOException e) { // Log the exception or handle it as needed (e.g., printStackTrace()) + postOffice.getLogger().log(Level.SEVERE, "An error occurred while updating the config file", e); } } From b53fc1d441e363775c759bb6cb77dbbce8f212ec Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 15 Sep 2024 20:35:14 +0930 Subject: [PATCH 04/45] Refactoring code --- .../io/shantek/functions/PluginConfig.java | 19 ------------------- .../io/shantek/listeners/InventoryOpen.java | 1 - src/main/resources/plugin.yml | 2 +- 3 files changed, 1 insertion(+), 21 deletions(-) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index f652eae..89d068c 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -213,23 +213,4 @@ private void saveConfigSilently(FileConfiguration config) { } } - public void setCustomBarrelName(String newCustomBarrelName) { - try { - File configFile = new File(postOffice.getDataFolder(), "config.yml"); - FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Update the custom barrel name in the configuration - config.set("custom-barrel-name", newCustomBarrelName); - - // Save the updated configuration - saveConfigSilently(config); - - // Update the custom barrel name in the PostOffice instance - postOffice.customBarrelName = newCustomBarrelName; - - } catch (Exception e) { - postOffice.getLogger().log(Level.SEVERE, "An error occurred while updating the custom barrel name", e); - } - } - } diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index 4060be9..258ef99 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -35,7 +35,6 @@ public void onInventoryOpen(InventoryOpenEvent event) { Barrel barrel = (Barrel) blockState; if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 91d49eb..773a7f7 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: PostOffice api-version: 1.15 -version: 1.6.3 +version: '${project.version}' author: Shantek.io main: io.shantek.PostOffice From dea49a28857be44763bb702c0cb475cb538ef4ab Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 15 Sep 2024 20:47:12 +0930 Subject: [PATCH 05/45] Adding postbox sign notifications --- src/main/java/io/shantek/PostOffice.java | 1 + .../io/shantek/functions/PluginConfig.java | 6 ++-- .../io/shantek/listeners/InventoryClose.java | 29 +++++++++++++++---- src/main/resources/config.yml | 4 +++ src/main/resources/config/config.yml | 4 +++ 5 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 8bd4ffa..2a3cc9f 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -35,6 +35,7 @@ public final class PostOffice extends JavaPlugin { public boolean postBoxProtection = true; public boolean consoleLogs = true; public boolean gotMailDelay = true; + public boolean signNotification = true; public void onEnable() { diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 89d068c..38e44b4 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -68,7 +68,7 @@ public void reloadConfigFile() { postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); postOffice.consoleLogs = getBoolean(config, "console-logs", true); postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); - + postOffice.signNotification = getBoolean(config, "sign-notification", true); } } catch (Exception e) { @@ -83,7 +83,7 @@ private boolean checkForMissingKeys(FileConfiguration config) { List keysToCheck = Arrays.asList( "custom-barrel-name", "cant-stack-items", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay"); + "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification"); // Check for missing keys for (String key : keysToCheck) { @@ -102,7 +102,7 @@ private Map saveMissingKeyValues(FileConfiguration config) { List keysToCheck = Arrays.asList( "custom-barrel-name", "cant-stack-items", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay"); + "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification"); // Save existing values of missing keys for (String key : keysToCheck) { diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 40316db..4eb75ae 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -1,10 +1,7 @@ package io.shantek.listeners; import io.shantek.PostOffice; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; +import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -44,11 +41,15 @@ public void onInventoryClose(InventoryCloseEvent event) { boolean isOwner = false; String ownerName = ""; + Sign sign = null; + boolean foundSign = false; + for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) { Block relativeBlock = clickedBlock.getRelative(face); if (relativeBlock.getType().name().toUpperCase().contains("SIGN")) { - Sign sign = (Sign) relativeBlock.getState(); + foundSign = true; + sign = (Sign) relativeBlock.getState(); ownerName = sign.getLine(1); if (sign.getLine(1).equalsIgnoreCase(event.getPlayer().getName())) { @@ -58,11 +59,20 @@ public void onInventoryClose(InventoryCloseEvent event) { } } + if (!ownerName.isEmpty()) { if (!isOwner) { postOffice.newItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); if (postOffice.newItemCount > postOffice.previousItemCount) { + // Set their sign to notify them they have mail + if (postOffice.signNotification && foundSign) { + + sign.setLine(2, ChatColor.GREEN + "You have mail"); + sign.update(); + + } + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.sentMessage .replace("%sender%", player.getName()) @@ -88,6 +98,15 @@ public void onInventoryClose(InventoryCloseEvent event) { } } } else { + + // Set their sign to notify them they have mail + if (postOffice.signNotification && foundSign) { + + sign.setLine(2, ""); + sign.update(); + + } + // If they were the owner, and it was their barrel, remove them from the mail list postOffice.playersWithMail.remove(event.getPlayer().getName()); postOffice.helpers.saveMailFile(); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 62edf35..a9abd58 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -2,6 +2,10 @@ # will be treated as a Post Box custom-barrel-name: "pobox" +# Display mail state on post box signs. When enabled, a notification will be +# added to the third line of the post box sign +sign-notification: true + # Message sent to the sender when closing the Post Box sent-message: "&a[Post Office] &aMail sent to %receiver%." diff --git a/src/main/resources/config/config.yml b/src/main/resources/config/config.yml index 62edf35..a9abd58 100644 --- a/src/main/resources/config/config.yml +++ b/src/main/resources/config/config.yml @@ -2,6 +2,10 @@ # will be treated as a Post Box custom-barrel-name: "pobox" +# Display mail state on post box signs. When enabled, a notification will be +# added to the third line of the post box sign +sign-notification: true + # Message sent to the sender when closing the Post Box sent-message: "&a[Post Office] &aMail sent to %receiver%." From e5ee7e3c8bfd2d76cdc6b169d40c04b9da1093f1 Mon Sep 17 00:00:00 2001 From: Kris Date: Mon, 16 Sep 2024 06:29:44 +0930 Subject: [PATCH 06/45] Adding additional helper classes --- .../java/io/shantek/functions/Helpers.java | 284 ++++++++++++++++-- 1 file changed, 267 insertions(+), 17 deletions(-) diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 17d58de..a3dba45 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -2,15 +2,26 @@ import io.shantek.PostOffice; +import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; import java.util.logging.Level; +import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.Tag; import org.bukkit.block.Barrel; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class Helpers { @@ -19,8 +30,19 @@ public class Helpers { public Helpers(PostOffice postOffice) { this.postOffice = postOffice; + barrelsCache = new HashMap<>(); + loadBarrelsIntoCache(); // Load data from barrels.yml into the cache at startup } + // In-memory cache to store barrel data (key: block location, value: owner UUID) + private Map barrelsCache; + + private FileConfiguration barrelsConfig = null; + private File barrelsConfigFile = null; + + //region Barrel Operations + + // Check if there's a barrel with the custom name nearby public boolean hasBarrelNearby(Block block) { // Check if the given block is a barrel with the custom name if (block.getType() == Material.BARREL) { @@ -49,16 +71,7 @@ public boolean hasBarrelNearby(Block block) { return false; } - public int countNonNullItems(ItemStack[] items) { - int count = 0; - for (ItemStack item : items) { - if (item != null && item.getType() != Material.AIR) { - count += item.getAmount(); - } - } - return count; - } - + // Check if the block is a protected post box public boolean isProtectedPostBox(Block block) { if (block.getType() == Material.BARREL) { Barrel barrel = (Barrel) block.getState(); @@ -70,6 +83,7 @@ public boolean isProtectedPostBox(Block block) { return false; } + // Check if a sign is next to a protected barrel public boolean isSignNextToProtectedBarrel(Block signBlock) { BlockFace[] adjacentFaces = { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN @@ -88,18 +102,168 @@ public boolean isSignNextToProtectedBarrel(Block signBlock) { return false; } - //region Plugin Configuration + // Check for a sign attached to a barrel + public Block getAttachedSign(Block barrelBlock) { + for (BlockFace face : BlockFace.values()) { + Block relativeBlock = barrelBlock.getRelative(face); + if (Tag.SIGNS.isTagged(relativeBlock.getType())) { + return relativeBlock; // Return the block if it's a sign + } + } + return null; // No sign found + } + + //region Barrel Caching and Config Operations - public void checkForDataFolder() { - if (!postOffice.getDataFolder().exists()) { - if (postOffice.getDataFolder().mkdir()) { - postOffice.getLogger().info("Data folder created successfully."); - } else { - postOffice.getLogger().warning("Error creating the data folder."); + // Load the contents of barrels.yml into memory (cache) + private void loadBarrelsIntoCache() { + FileConfiguration barrelsConfig = getBarrelsConfig(); + if (barrelsConfig.contains("barrels")) { + for (String key : barrelsConfig.getConfigurationSection("barrels").getKeys(false)) { + String path = "barrels." + key; + UUID ownerUUID = UUID.fromString(barrelsConfig.getString(path + ".owner")); + barrelsCache.put(key, ownerUUID); // Add to cache } } } + // Add barrel and sign to in-memory cache and save to disk if necessary + public void addBarrelWithSign(Block barrelBlock, Block signBlock, UUID ownerUUID) { + if (barrelBlock.getType() != Material.BARREL || !Tag.SIGNS.isTagged(signBlock.getType())) { + return; // Only proceed if the block is a barrel and the sign is valid + } + + String barrelLocationString = getBlockLocationString(barrelBlock); + String signLocationString = getBlockLocationString(signBlock); + + // Check if barrel already exists in the cache + if (!barrelsCache.containsKey(barrelLocationString)) { + // Barrel does not exist, add it to the cache with owner UUID + barrelsCache.put(barrelLocationString, ownerUUID); + + // Also store the sign's location in the config + barrelsConfig.set("barrels." + barrelLocationString + ".sign", signLocationString); + + // Save the updated cache and config to barrels.yml + saveBarrelsToDisk(); + } + } + + // Remove barrel from in-memory cache and save to disk if necessary + public void removeBarrel(Block block) { + String blockLocationString = getBlockLocationString(block); + + // Check if the barrel exists in the cache + if (barrelsCache.containsKey(blockLocationString)) { + // Barrel exists, remove it from the cache + barrelsCache.remove(blockLocationString); + + // Remove the barrel from the config as well + barrelsConfig.set("barrels." + blockLocationString, null); + + // Save the updated cache to barrels.yml + saveBarrelsToDisk(); + } + } + + // Save the in-memory cache to barrels.yml + public void saveBarrelsToDisk() { + FileConfiguration barrelsConfig = getBarrelsConfig(); + + barrelsConfig.set("barrels", null); // Clear existing entries in the file + for (Map.Entry entry : barrelsCache.entrySet()) { + String path = "barrels." + entry.getKey(); + UUID ownerUUID = entry.getValue(); + + barrelsConfig.set(path + ".owner", ownerUUID.toString()); + + // You may want to store coordinates if needed as well + String[] parts = entry.getKey().split("_"); + barrelsConfig.set(path + ".world", parts[0]); + barrelsConfig.set(path + ".x", Integer.parseInt(parts[1])); + barrelsConfig.set(path + ".y", Integer.parseInt(parts[2])); + barrelsConfig.set(path + ".z", Integer.parseInt(parts[3])); + + // Ensure the sign's location is stored if present + String signLocation = barrelsConfig.getString(path + ".sign"); + if (signLocation != null) { + barrelsConfig.set(path + ".sign", signLocation); + } + } + + saveBarrelsConfig(); // Save changes to barrels.yml + } + + // Get the string representing the block's location + private String getBlockLocationString(Block block) { + return block.getWorld().getName() + "_" + block.getX() + "_" + block.getY() + "_" + block.getZ(); + } + + //endregion + + //region Retrieving Sign Information + + // Retrieve the location of the sign attached to a barrel + public Block getSignForBarrel(Block barrelBlock) { + String barrelLocationString = getBlockLocationString(barrelBlock); + + // Retrieve the sign's location from the config + String signLocationString = barrelsConfig.getString("barrels." + barrelLocationString + ".sign"); + + if (signLocationString != null) { + String[] parts = signLocationString.split("_"); + String worldName = parts[0]; + int x = Integer.parseInt(parts[1]); + int y = Integer.parseInt(parts[2]); + int z = Integer.parseInt(parts[3]); + + return postOffice.getServer().getWorld(worldName).getBlockAt(x, y, z); + } + + return null; // No sign found for this barrel + } + + //endregion + + //region Plugin Configuration (YAML Management) + + // Load the barrels.yml configuration + public void reloadBarrelsConfig() { + if (barrelsConfigFile == null) { + barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); + } + barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); + + // Create the file if it doesn't exist + if (!barrelsConfigFile.exists()) { + postOffice.saveResource("barrels.yml", false); + } + } + + // Get the barrels.yml configuration + public FileConfiguration getBarrelsConfig() { + if (barrelsConfig == null) { + reloadBarrelsConfig(); + } + return barrelsConfig; + } + + // Save changes to barrels.yml + public void saveBarrelsConfig() { + if (barrelsConfig == null || barrelsConfigFile == null) { + return; + } + try { + barrelsConfig.save(barrelsConfigFile); + } catch (IOException e) { + postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + } + } + + //endregion + + //region Mail and Item Operations + public void saveMailFile() { try { if (postOffice.consoleLogs) { @@ -111,5 +275,91 @@ public void saveMailFile() { } } + public int countNonNullItems(ItemStack[] items) { + int count = 0; + for (ItemStack item : items) { + if (item != null && item.getType() != Material.AIR) { + count += item.getAmount(); + } + } + return count; + } + + public void checkForDataFolder() { + if (!postOffice.getDataFolder().exists()) { + if (postOffice.getDataFolder().mkdir()) { + postOffice.getLogger().info("Data folder created successfully."); + } else { + postOffice.getLogger().warning("Error creating the data folder."); + } + } + } + + public String getOwnerName(UUID ownerUuid) { + OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerUuid); + + String ownerName = owner.getName(); + if (ownerName != null) { + return ownerName; + } else { + return ownerUuid.toString(); + } + + } + + public boolean isBarrelInConfig(Block block) { + if (block.getType() != Material.BARREL) { + return false; // Only check if it's a barrel + } + + // Check if it matches the custom barrel name + BlockState blockState = block.getState(); + Barrel barrel = (Barrel) blockState; + + if (!Objects.requireNonNull(barrel.getCustomName()).equalsIgnoreCase(postOffice.customBarrelName)) { + return false; + } + + + String blockLocationString = getBlockLocationString(block); // Get the block's location string + + // Check if the location exists in the cache or config + return barrelsCache.containsKey(blockLocationString); + } + + public UUID getOwnerUUID(Block block) { + if (block.getType() != Material.BARREL) { + return null; // Only work with barrels + } + + String blockLocationString = getBlockLocationString(block); // Get the block's location string + + // Return the owner's UUID if the block exists in the cache + return barrelsCache.get(blockLocationString); + } + + // Method to get a player's name by UUID, checking both online and offline players + public String getPlayerName(UUID uuid) { + // Check if the player is online + Player onlinePlayer = Bukkit.getPlayer(uuid); + if (onlinePlayer != null) { + return onlinePlayer.getName(); + } + + // If the player is offline, use getOfflinePlayer + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + return offlinePlayer.getName(); // This may return null if the player's name is not available + } + + public UUID getPlayerUUID(Player player) { + return player.getUniqueId(); + } + + // Method to check if a player is online by UUID + public boolean isPlayerOnline(UUID uuid) { + Player player = Bukkit.getPlayer(uuid); + return player != null; + } + //endregion } From e03e5d128eaffc62a392d4e9fb1edecd7a97c5bd Mon Sep 17 00:00:00 2001 From: Kris Date: Mon, 16 Sep 2024 06:32:09 +0930 Subject: [PATCH 07/45] Added default barrels.yml --- src/main/resources/barrels.yml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/main/resources/barrels.yml diff --git a/src/main/resources/barrels.yml b/src/main/resources/barrels.yml new file mode 100644 index 0000000..bc7fbe9 --- /dev/null +++ b/src/main/resources/barrels.yml @@ -0,0 +1,7 @@ +# +# This config stores the location and owner of all post box barrels on your server. +# +# Never manually edit this file as it's managed by the plugin when creating +# or destroying post boxes. +# + From cb14d38da2b7f8075e94d27c7176ca92a8926075 Mon Sep 17 00:00:00 2001 From: Kris Date: Mon, 16 Sep 2024 06:32:48 +0930 Subject: [PATCH 08/45] Added config functionality for barrels.yml --- .../io/shantek/functions/PluginConfig.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 38e44b4..5c9c47f 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -21,6 +21,9 @@ public PluginConfig(PostOffice postOffice) { this.postOffice = postOffice; } + private FileConfiguration barrelsConfig = null; + private File barrelsConfigFile = null; + public void reloadConfigFile() { try { postOffice.getLogger().info("Reloading config file."); // Print to the console @@ -213,4 +216,38 @@ private void saveConfigSilently(FileConfiguration config) { } } + public void reloadBarrelsConfig() { + if (barrelsConfigFile == null) { + barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); + } + barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); + + // Check if the file exists, and if not, create it + if (!barrelsConfigFile.exists()) { + postOffice.saveResource("barrels.yml", false); + } + } + + // Get the barrels.yml configuration + public FileConfiguration getBarrelsConfig() { + if (barrelsConfig == null) { + reloadBarrelsConfig(); + } + return barrelsConfig; + } + + // Save changes to barrels.yml + public void saveBarrelsConfig() { + if (barrelsConfig == null || barrelsConfigFile == null) { + return; + } + try { + barrelsConfig.save(barrelsConfigFile); + } catch (IOException e) { + postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + } + } + + + } From 7006fe78bcfbe0c2886c0a208c772e44a26eee72 Mon Sep 17 00:00:00 2001 From: Kris Date: Mon, 16 Sep 2024 10:48:52 +0930 Subject: [PATCH 09/45] Progress of updating barrel ownership logic --- src/main/java/io/shantek/PostOffice.java | 6 + .../java/io/shantek/functions/BarrelData.java | 27 ++ .../java/io/shantek/functions/Commands.java | 256 ++++++++++- .../java/io/shantek/functions/Helpers.java | 402 ++++++++++++++---- .../io/shantek/listeners/InventoryClose.java | 132 +++--- 5 files changed, 672 insertions(+), 151 deletions(-) create mode 100644 src/main/java/io/shantek/functions/BarrelData.java diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 2a3cc9f..73a8798 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -112,6 +112,12 @@ public static PostOffice getInstance() { return instance; } + @Override + public void onDisable() { + // Save the cache to file when the plugin is disabled + helpers.saveCacheToFile(); + } + public void printInfoMessage(String message) { getLogger().info(message); // Print to the console } diff --git a/src/main/java/io/shantek/functions/BarrelData.java b/src/main/java/io/shantek/functions/BarrelData.java new file mode 100644 index 0000000..af0aaaa --- /dev/null +++ b/src/main/java/io/shantek/functions/BarrelData.java @@ -0,0 +1,27 @@ +package io.shantek.functions; + +import java.util.UUID; + +public class BarrelData { + private final UUID ownerUUID; + private final String signLocation; + private final String state; + + public BarrelData(UUID ownerUUID, String signLocation, String state) { + this.ownerUUID = ownerUUID; + this.signLocation = signLocation; + this.state = state; + } + + public UUID getOwnerUUID() { + return ownerUUID; + } + + public String getSignLocation() { + return signLocation; + } + + public String getState() { + return state; + } +} diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 7a8a59a..fb5ed59 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -1,10 +1,16 @@ package io.shantek.functions; import io.shantek.PostOffice; -import org.bukkit.ChatColor; +import org.bukkit.*; +import org.bukkit.block.Barrel; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.UUID; public class Commands implements CommandExecutor { @@ -22,6 +28,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String // Reload all the config and language file postOffice.pluginConfig.reloadConfigFile(); + postOffice.helpers.saveCacheToFile(); // Save cache instead of config directly + postOffice.helpers.reloadBarrelsConfig(); sender.sendMessage(ChatColor.GREEN + "Post Office config file has been reloaded."); return true; } else { @@ -29,6 +37,250 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String sender.sendMessage(ChatColor.RED + "You don't have access to this command!"); return false; } + } else if (args[0].equalsIgnoreCase("info")) { + if (sender instanceof Player) { + Player player = (Player) sender; + + Block targetBlock = player.getTargetBlock(null, 10); // Get the block the player is looking at + + Block barrelBlock = null; + + // Check if the player is looking at a sign + if (Tag.SIGNS.isTagged(targetBlock.getType())) { + // Look up the barrel using the sign's location from the config + barrelBlock = postOffice.helpers.getBarrelFromSign(targetBlock); + + // If there's no attached barrel or it's not a valid post box, show unregistered + if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "This isn't a valid post box."); + return true; + } + + } else if (targetBlock.getType() == Material.BARREL) { + // The player is directly looking at a barrel + barrelBlock = targetBlock; + } + + // Ensure we have a valid barrel block + if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "This isn't a valid post box."); + return true; + } + + // Use the helper to get the owner and state information + String barrelLocation = postOffice.helpers.getBlockLocationString(barrelBlock); + String owner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); // Get the owner name + String state = postOffice.helpers.getStateFromConfig(barrelLocation); // Get the post box state + + // If there's an owner, print it. Otherwise, print the state. + if (owner != null && !owner.equals("none")) { + player.sendMessage(ChatColor.GREEN + "This post box is owned by: " + ChatColor.YELLOW + owner); + } else if (state != null && state.equals("registered")) { + player.sendMessage(ChatColor.GREEN + "This post box is currently registered but not claimed."); + } else { + player.sendMessage(ChatColor.RED + "This isn't a valid postbox."); + } + + return true; + } + } else if (args[0].equalsIgnoreCase("register")) { + + if (sender instanceof Player) { + Player player = (Player) sender; + if (sender.hasPermission("shantek.postoffice.create") || sender.isOp()) { + + // Ensure they are looking at a sign + Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks + if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { + player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + return true; + } + + // Ensure the sign is attached to a barrel + Block signBlock = targetBlock; + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + return true; + } + + // Get the location of the barrel and check its state + String barrelLocation = postOffice.helpers.getBlockLocationString(attachedBarrel); + String currentOwner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); // Get the owner name + String currentState = postOffice.helpers.getStateFromConfig(barrelLocation); // Get the post box state + + // Check if the post box is already registered or claimed + if (currentOwner != null && !currentOwner.equals("none")) { + player.sendMessage(ChatColor.RED + "This post box is already claimed by: " + ChatColor.YELLOW + currentOwner); + return true; + } + if (currentState != null && currentState.equals("registered")) { + player.sendMessage(ChatColor.RED + "This post box is already registered."); + return true; + } + + // Register the post box and update the barrel name + Barrel barrel = (Barrel) attachedBarrel.getState(); + barrel.setCustomName(postOffice.customBarrelName); + barrel.update(); + + // Register the barrel and sign in the plugin config + UUID barrelOwnerUUID = null; // No owner yet + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, barrelOwnerUUID, "registered"); + + // Update the sign with "Unclaimed" on the second line in red text + Sign sign = (Sign) signBlock.getState(); + sign.setLine(1, ChatColor.RED + "Unclaimed"); + sign.update(); // Make sure to update the sign to apply the changes + + postOffice.helpers.saveCacheToFile(); // Save the cache to disk + + player.sendMessage(ChatColor.GREEN + "Post box registered successfully."); + return true; + + } + } else { + sender.sendMessage(ChatColor.RED + "This command can only be used by players."); + return true; + } + } else if (args[0].equalsIgnoreCase("claim") && args.length == 2) { + if (sender.hasPermission("shantek.postoffice.admin") || sender.isOp()) { + + // Ensure they are looking at a sign + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "This command can only be used by players."); + return true; + } + + Player player = (Player) sender; + Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks + if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { + player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + return true; + } + + // Ensure the sign is attached to a barrel + Block signBlock = targetBlock; + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + return true; + } + + // Check if the sign exists in the config (if the post box has been registered) + Block savedSign = postOffice.helpers.getSignForBarrel(attachedBarrel); // Retrieve saved sign + if (savedSign == null) { + player.sendMessage(ChatColor.RED + "This post box has not been registered yet."); + return true; + } + + // Get the location of the barrel + String barrelLocation = postOffice.helpers.getBlockLocationString(attachedBarrel); + + // Get the target player's name and UUID + String targetPlayerName = args[1]; + OfflinePlayer targetPlayer = Bukkit.getOfflinePlayer(targetPlayerName); + + if (!targetPlayer.hasPlayedBefore()) { + player.sendMessage(ChatColor.RED + "The player " + targetPlayerName + " has not played on this server."); + return true; + } + + UUID targetPlayerUUID = targetPlayer.getUniqueId(); + + // Check if the player already has a post box + if (postOffice.helpers.doesPlayerHavePostBox(targetPlayerUUID)) { + String existingPostBoxLocation = postOffice.helpers.getPlayerPostBoxLocation(targetPlayerUUID); // Get world and coordinates + player.sendMessage(ChatColor.RED + targetPlayerName + " already has a post box at: " + ChatColor.YELLOW + existingPostBoxLocation); + return true; + } + + // Check if the post box is already claimed + String currentOwner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); + if (currentOwner != null && !currentOwner.equals("none")) { + player.sendMessage(ChatColor.RED + "This post box is already claimed."); + return true; + } + + // Claim the post box for the target player and update the state to 'claimed' + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, targetPlayerUUID, "claimed"); + + // Update the sign to display the player's name on the second line + if (signBlock != null && signBlock.getState() instanceof Sign) { + Sign sign = (Sign) signBlock.getState(); + sign.setLine(1, targetPlayer.getName()); // Set the player's name on the 2nd line + sign.update(); + } + + player.sendMessage(ChatColor.GREEN + "The post box has been claimed for " + targetPlayerName + "."); + + postOffice.helpers.saveCacheToFile(); // Save the cache to disk + return true; + } + } else if (args[0].equalsIgnoreCase("claim")) { + if (sender instanceof Player) { + Player player = (Player) sender; + UUID playerUUID = player.getUniqueId(); + + if (sender.hasPermission("shantek.postoffice.create") || sender.isOp()) { + + // Ensure they are looking at a sign + Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks + if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { + player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + return true; + } + + // Ensure the sign is attached to a barrel + Block signBlock = targetBlock; + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + return true; + } + + // Check if the sign exists in the config (if the post box has been registered) + Block savedSign = postOffice.helpers.getSignForBarrel(attachedBarrel); // Retrieve saved sign + if (savedSign == null) { + player.sendMessage(ChatColor.RED + "This post box has not been registered yet."); + return true; + } + + // Get the location of the barrel + String barrelLocation = postOffice.helpers.getBlockLocationString(attachedBarrel); + + // Check if the post box is already claimed + String currentOwner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); + if (currentOwner != null && !currentOwner.equals("none")) { + player.sendMessage(ChatColor.RED + "This post box is already claimed."); + return true; + } + + // Check if the player already has a post box + if (postOffice.helpers.doesPlayerHavePostBox(playerUUID)) { + String existingPostBoxLocation = postOffice.helpers.getPlayerPostBoxLocation(playerUUID); // Get world and coordinates + player.sendMessage(ChatColor.RED + "You already have a post box at: " + ChatColor.YELLOW + existingPostBoxLocation); + return true; + } + + // Claim the post box for the player and update the state to 'claimed' + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, playerUUID, "claimed"); + player.sendMessage(ChatColor.GREEN + "You have successfully claimed this post box."); + + // Update the sign to display the player's name on the second line + if (signBlock != null && signBlock.getState() instanceof Sign) { + Sign sign = (Sign) signBlock.getState(); + sign.setLine(1, player.getName()); // Set the player's name on the 2nd line + sign.update(); + } + + postOffice.helpers.saveCacheToFile(); // Save the cache to disk + return true; + } + } else { + sender.sendMessage(ChatColor.RED + "This command can only be used by players."); + return true; + } } else { // Invalid command format sender.sendMessage(ChatColor.RED + "Unknown command or insufficient permission."); @@ -37,6 +289,4 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } return false; } - } - diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index a3dba45..8c9b362 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -5,20 +5,15 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; +import java.util.*; import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.Tag; +import org.bukkit.*; import org.bukkit.block.Barrel; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; @@ -35,7 +30,7 @@ public Helpers(PostOffice postOffice) { } // In-memory cache to store barrel data (key: block location, value: owner UUID) - private Map barrelsCache; + private Map barrelsCache; private FileConfiguration barrelsConfig = null; private File barrelsConfigFile = null; @@ -71,6 +66,27 @@ public boolean hasBarrelNearby(Block block) { return false; } + // Method to check if the block the player is looking at is a custom barrel + public boolean isLookingAtCustomBarrel(Player player) { + + // Get the block the player is looking at (with a max distance of 10) + Block targetBlock = player.getTargetBlock((Set) null, 10); + + if (targetBlock.getType() == Material.BARREL) { + BlockState state = targetBlock.getState(); + + if (state instanceof Barrel) { + Barrel barrel = (Barrel) state; + String barrelCustomName = barrel.getCustomName(); + + // Check if the barrel has the custom name + return barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName); + } + } + + return false; // Not looking at a valid custom barrel + } + // Check if the block is a protected post box public boolean isProtectedPostBox(Block block) { if (block.getType() == Material.BARREL) { @@ -115,20 +131,43 @@ public Block getAttachedSign(Block barrelBlock) { //region Barrel Caching and Config Operations - // Load the contents of barrels.yml into memory (cache) private void loadBarrelsIntoCache() { + barrelsCache.clear(); // Clear the cache before reloading + FileConfiguration barrelsConfig = getBarrelsConfig(); if (barrelsConfig.contains("barrels")) { - for (String key : barrelsConfig.getConfigurationSection("barrels").getKeys(false)) { + Set keys = barrelsConfig.getConfigurationSection("barrels").getKeys(false); + postOffice.getLogger().info("Loading barrels into cache. Found keys: " + keys); + + for (String key : keys) { String path = "barrels." + key; - UUID ownerUUID = UUID.fromString(barrelsConfig.getString(path + ".owner")); - barrelsCache.put(key, ownerUUID); // Add to cache + String ownerUUIDString = barrelsConfig.getString(path + ".owner"); + String state = barrelsConfig.getString(path + ".state", "unregistered"); // Default to "unregistered" + String signLocation = barrelsConfig.getString(path + ".sign"); + + UUID ownerUUID = null; + if (ownerUUIDString != null && !ownerUUIDString.equalsIgnoreCase("none")) { + try { + ownerUUID = UUID.fromString(ownerUUIDString); + } catch (IllegalArgumentException e) { + postOffice.getLogger().warning("Invalid UUID found for barrel at " + key); + continue; // Skip this barrel if UUID is invalid + } + } + + // Create a BarrelData object and store it in the cache + BarrelData barrelData = new BarrelData(ownerUUID, state, signLocation); + barrelsCache.put(key, barrelData); // Add to cache + + postOffice.getLogger().info("Added barrel to cache at location: " + key + ", Owner: " + + (ownerUUID != null ? ownerUUID : "none") + ", State: " + state + ", Sign: " + signLocation); } + } else { + postOffice.getLogger().warning("No barrels found in barrels.yml during cache load."); } } - // Add barrel and sign to in-memory cache and save to disk if necessary - public void addBarrelWithSign(Block barrelBlock, Block signBlock, UUID ownerUUID) { + public void addBarrelWithSign(Block barrelBlock, Block signBlock, UUID newOwnerUUID, String state) { if (barrelBlock.getType() != Material.BARREL || !Tag.SIGNS.isTagged(signBlock.getType())) { return; // Only proceed if the block is a barrel and the sign is valid } @@ -136,17 +175,18 @@ public void addBarrelWithSign(Block barrelBlock, Block signBlock, UUID ownerUUID String barrelLocationString = getBlockLocationString(barrelBlock); String signLocationString = getBlockLocationString(signBlock); - // Check if barrel already exists in the cache - if (!barrelsCache.containsKey(barrelLocationString)) { - // Barrel does not exist, add it to the cache with owner UUID - barrelsCache.put(barrelLocationString, ownerUUID); + // Create or update the BarrelData + BarrelData barrelData = new BarrelData(newOwnerUUID, state, signLocationString); - // Also store the sign's location in the config - barrelsConfig.set("barrels." + barrelLocationString + ".sign", signLocationString); + // Add or update the barrel data in the cache + barrelsCache.put(barrelLocationString, barrelData); - // Save the updated cache and config to barrels.yml - saveBarrelsToDisk(); - } + // Log for debugging purposes + postOffice.getLogger().info("Adding/Updating barrel at: " + barrelLocationString); + postOffice.getLogger().info("Sign location for barrel: " + signLocationString); + + // Save the updated cache to disk + saveBarrelsToDisk(); } // Remove barrel from in-memory cache and save to disk if necessary @@ -170,35 +210,158 @@ public void removeBarrel(Block block) { public void saveBarrelsToDisk() { FileConfiguration barrelsConfig = getBarrelsConfig(); - barrelsConfig.set("barrels", null); // Clear existing entries in the file - for (Map.Entry entry : barrelsCache.entrySet()) { - String path = "barrels." + entry.getKey(); - UUID ownerUUID = entry.getValue(); + // Clear existing entries in the file + barrelsConfig.set("barrels", null); + + // Iterate over the cache and save each barrel's data + for (Map.Entry entry : barrelsCache.entrySet()) { + String barrelLocationString = entry.getKey(); + BarrelData barrelData = entry.getValue(); + + String path = "barrels." + barrelLocationString; - barrelsConfig.set(path + ".owner", ownerUUID.toString()); + // Set the owner UUID, or "none" if no owner is set + barrelsConfig.set(path + ".owner", barrelData.getOwnerUUID() != null ? barrelData.getOwnerUUID().toString() : "none"); - // You may want to store coordinates if needed as well - String[] parts = entry.getKey().split("_"); - barrelsConfig.set(path + ".world", parts[0]); - barrelsConfig.set(path + ".x", Integer.parseInt(parts[1])); - barrelsConfig.set(path + ".y", Integer.parseInt(parts[2])); - barrelsConfig.set(path + ".z", Integer.parseInt(parts[3])); + // Set the state (e.g., "claimed", "registered") + barrelsConfig.set(path + ".state", barrelData.getState()); - // Ensure the sign's location is stored if present - String signLocation = barrelsConfig.getString(path + ".sign"); - if (signLocation != null) { - barrelsConfig.set(path + ".sign", signLocation); + // Set the sign location if it exists + barrelsConfig.set(path + ".sign", barrelData.getSignLocation()); + + // Parse and store the world and coordinates from the barrel location string + String[] parts = barrelLocationString.split("_"); + if (parts.length == 4) { + barrelsConfig.set(path + ".world", parts[0]); + barrelsConfig.set(path + ".x", Integer.parseInt(parts[1])); + barrelsConfig.set(path + ".y", Integer.parseInt(parts[2])); + barrelsConfig.set(path + ".z", Integer.parseInt(parts[3])); } } + // Save the updated configuration to barrels.yml + saveBarrelsConfig(); + } + + + public void registerBarrelWithSign(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { + String barrelLocationString = getBlockLocationString(barrelBlock); + String signLocationString = getBlockLocationString(signBlock); + + FileConfiguration barrelsConfig = getBarrelsConfig(); + + // Register barrel and sign in barrels.yml with proper world and coordinates + barrelsConfig.set("barrels." + barrelLocationString + ".state", state); // Set the state to registered/claimed + barrelsConfig.set("barrels." + barrelLocationString + ".owner", ownerUUID != null ? ownerUUID.toString() : "none"); + barrelsConfig.set("barrels." + barrelLocationString + ".sign", signLocationString); + barrelsConfig.set("barrels." + barrelLocationString + ".world", barrelBlock.getWorld().getName()); + barrelsConfig.set("barrels." + barrelLocationString + ".x", barrelBlock.getX()); + barrelsConfig.set("barrels." + barrelLocationString + ".y", barrelBlock.getY()); + barrelsConfig.set("barrels." + barrelLocationString + ".z", barrelBlock.getZ()); + + // Log the barrel and sign registration for debugging purposes + postOffice.getLogger().info("Registering barrel at: " + barrelLocationString); + postOffice.getLogger().info("Sign location for barrel: " + signLocationString); + saveBarrelsConfig(); // Save changes to barrels.yml + reloadBarrelsConfig(); + } + + public Block getSignFromConfig(Block barrelBlock) { + String barrelLocationString = getBlockLocationString(barrelBlock); // Convert block to location string + String path = "barrels." + barrelLocationString + ".sign"; // Use this location string in the config + + // Look up the sign location in the config + if (barrelsConfig.contains(path)) { + String signLocation = barrelsConfig.getString(path); + String[] parts = signLocation.split("_"); + + if (parts.length == 4) { + String worldName = parts[0]; + int x = Integer.parseInt(parts[1]); + int y = Integer.parseInt(parts[2]); + int z = Integer.parseInt(parts[3]); + + World world = Bukkit.getWorld(worldName); + if (world != null) { + return world.getBlockAt(x, y, z); // Return the block at the saved sign location + } + } + } + return null; // Sign not found in the config } - // Get the string representing the block's location - private String getBlockLocationString(Block block) { + // Helper method to get block location string + public String getBlockLocationString(Block block) { return block.getWorld().getName() + "_" + block.getX() + "_" + block.getY() + "_" + block.getZ(); } + // Get the owner name from the barrels.yml config + public String getOwnerNameFromConfig(String barrelLocationString) { + FileConfiguration barrelsConfig = getBarrelsConfig(); + + String ownerUUIDString = barrelsConfig.getString("barrels." + barrelLocationString + ".owner"); + + if (ownerUUIDString != null && !ownerUUIDString.equals("none")) { + UUID ownerUUID = UUID.fromString(ownerUUIDString); + return getPlayerName(ownerUUID); // Retrieve player's name from UUID + } + + return "none"; // No owner + } + + // Get the state of the post box from the barrels.yml config + public String getStateFromConfig(String barrelLocationString) { + FileConfiguration barrelsConfig = getBarrelsConfig(); + return barrelsConfig.getString("barrels." + barrelLocationString + ".state", "unregistered"); // Default to "registered" + } + + public boolean doesPlayerHavePostBox(UUID playerUUID) { + FileConfiguration barrelsConfig = getBarrelsConfig(); + + // Check if the 'barrels' section exists before accessing it + if (barrelsConfig.contains("barrels")) { + ConfigurationSection barrelsSection = barrelsConfig.getConfigurationSection("barrels"); + + // Loop through all barrels to check if any are owned by this player + for (String barrelLocation : barrelsSection.getKeys(false)) { + String ownerUUIDString = barrelsConfig.getString("barrels." + barrelLocation + ".owner"); + if (ownerUUIDString != null && ownerUUIDString.equals(playerUUID.toString())) { + return true; // The player already owns a post box + } + } + } + return false; // The player does not have a post box + } + + + public String getPlayerPostBoxLocation(UUID playerUUID) { + FileConfiguration barrelsConfig = getBarrelsConfig(); + + // Loop through all barrels to find the one owned by the player + for (String barrelLocation : barrelsConfig.getConfigurationSection("barrels").getKeys(false)) { + String ownerUUIDString = barrelsConfig.getString("barrels." + barrelLocation + ".owner"); + if (ownerUUIDString != null && ownerUUIDString.equals(playerUUID.toString())) { + + // Check if world, x, y, z are stored properly + String worldName = barrelsConfig.getString("barrels." + barrelLocation + ".world", "Unknown World"); + int x = barrelsConfig.getInt("barrels." + barrelLocation + ".x", Integer.MIN_VALUE); + int y = barrelsConfig.getInt("barrels." + barrelLocation + ".y", Integer.MIN_VALUE); + int z = barrelsConfig.getInt("barrels." + barrelLocation + ".z", Integer.MIN_VALUE); + + // Check if coordinates are valid (i.e., not the fallback value) + if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE || z == Integer.MIN_VALUE) { + return "Unknown location"; // Coordinates are not valid + } + + // Return formatted location string + return worldName + " [" + x + ", " + y + ", " + z + "]"; + } + } + return "Unknown location"; // Fallback if no post box is found + } + + //endregion //region Retrieving Sign Information @@ -223,6 +386,51 @@ public Block getSignForBarrel(Block barrelBlock) { return null; // No sign found for this barrel } + // Method to check if the sign is attached to a barrel + public Block getAttachedBarrel(Block signBlock) { + for (BlockFace face : BlockFace.values()) { + Block attachedBlock = signBlock.getRelative(face); + if (attachedBlock.getType() == Material.BARREL) { + return attachedBlock; + } + } + return null; // No barrel found attached to the sign + } + + public Block getBarrelFromSign(Block signBlock) { + String signLocationString = getBlockLocationString(signBlock); + FileConfiguration barrelsConfig = getBarrelsConfig(); + + // Ensure we have a valid configuration section for barrels + ConfigurationSection section = barrelsConfig.getConfigurationSection("barrels"); + if (section == null) { + postOffice.getLogger().severe("Barrels section is missing in the config"); + return null; + } + + // Loop through all stored barrels to find one with this sign location + for (String barrelLocation : section.getKeys(false)) { + String storedSignLocation = barrelsConfig.getString("barrels." + barrelLocation + ".sign"); + + if (signLocationString.equals(storedSignLocation)) { + // The sign matches, get the barrel block + String[] parts = barrelLocation.split("_"); + if (parts.length == 4) { + String worldName = parts[0]; + int x = Integer.parseInt(parts[1]); + int y = Integer.parseInt(parts[2]); + int z = Integer.parseInt(parts[3]); + + World world = Bukkit.getWorld(worldName); + if (world != null) { + return world.getBlockAt(x, y, z); // Return the barrel block + } + } + } + } + return null; // No barrel found for this sign + } + //endregion //region Plugin Configuration (YAML Management) @@ -238,6 +446,14 @@ public void reloadBarrelsConfig() { if (!barrelsConfigFile.exists()) { postOffice.saveResource("barrels.yml", false); } + + // Debugging to check if it's loading correctly + if (barrelsConfig.contains("barrels")) { + Set keys = barrelsConfig.getConfigurationSection("barrels").getKeys(false); + postOffice.getLogger().info("Keys in barrels.yml after reload: " + keys.toString()); + } else { + postOffice.getLogger().warning("No barrels found in barrels.yml during reload."); + } } // Get the barrels.yml configuration @@ -295,49 +511,30 @@ public void checkForDataFolder() { } } - public String getOwnerName(UUID ownerUuid) { - OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerUuid); - - String ownerName = owner.getName(); - if (ownerName != null) { - return ownerName; - } else { - return ownerUuid.toString(); - } - + public OfflinePlayer getPlayer(UUID uuid) { + return Bukkit.getOfflinePlayer(uuid); } - public boolean isBarrelInConfig(Block block) { - if (block.getType() != Material.BARREL) { - return false; // Only check if it's a barrel - } - - // Check if it matches the custom barrel name - BlockState blockState = block.getState(); - Barrel barrel = (Barrel) blockState; - - if (!Objects.requireNonNull(barrel.getCustomName()).equalsIgnoreCase(postOffice.customBarrelName)) { - return false; - } + public OfflinePlayer getPlayerReference(UUID ownerUuid) { + return Bukkit.getOfflinePlayer(ownerUuid); + } + public boolean isPostBoxOwner(Block block, Player player) { + UUID playerUUID = player.getUniqueId(); + return getOwnerUUID(block).equals(playerUUID); - String blockLocationString = getBlockLocationString(block); // Get the block's location string + } - // Check if the location exists in the cache or config + public boolean isBarrelInConfig(Block block) { + String blockLocationString = getBlockLocationString(block); return barrelsCache.containsKey(blockLocationString); } public UUID getOwnerUUID(Block block) { - if (block.getType() != Material.BARREL) { - return null; // Only work with barrels - } - - String blockLocationString = getBlockLocationString(block); // Get the block's location string - - // Return the owner's UUID if the block exists in the cache - return barrelsCache.get(blockLocationString); + String blockLocationString = getBlockLocationString(block); + BarrelData barrelData = barrelsCache.get(blockLocationString); + return barrelData != null ? barrelData.getOwnerUUID() : null; } - // Method to get a player's name by UUID, checking both online and offline players public String getPlayerName(UUID uuid) { // Check if the player is online @@ -362,4 +559,61 @@ public boolean isPlayerOnline(UUID uuid) { } //endregion + + + + public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { + String barrelLocationString = getBlockLocationString(barrelBlock); + String signLocationString = getBlockLocationString(signBlock); + + // Update the cache with the new data + barrelsCache.put(barrelLocationString, new BarrelData(ownerUUID, signLocationString, state)); + + // Optionally, you could save the cache to file immediately here: + saveCacheToFile(); + } + + public void removeBarrelFromCache(Block barrelBlock) { + String barrelLocationString = getBlockLocationString(barrelBlock); + + // Remove the barrel from the cache + barrelsCache.remove(barrelLocationString); + + // Optionally, you could save the cache to file immediately here: + // saveCacheToFile(); + } + + public void saveCacheToFile() { + FileConfiguration barrelsConfig = getBarrelsConfig(); + + // Clear the existing barrels section in the config + barrelsConfig.set("barrels", null); + + // Iterate over the cache and save each barrel to the config + for (Map.Entry entry : barrelsCache.entrySet()) { + String barrelLocationString = entry.getKey(); + BarrelData barrelData = entry.getValue(); + + String path = "barrels." + barrelLocationString; + barrelsConfig.set(path + ".owner", barrelData.getOwnerUUID() != null ? barrelData.getOwnerUUID().toString() : "none"); + barrelsConfig.set(path + ".sign", barrelData.getSignLocation()); + barrelsConfig.set(path + ".state", barrelData.getState()); + + // Parse location from the key (world, x, y, z) + String[] parts = barrelLocationString.split("_"); + if (parts.length == 4) { + barrelsConfig.set(path + ".world", parts[0]); + barrelsConfig.set(path + ".x", Integer.parseInt(parts[1])); + barrelsConfig.set(path + ".y", Integer.parseInt(parts[2])); + barrelsConfig.set(path + ".z", Integer.parseInt(parts[3])); + } + } + + // Save the config to disk + saveBarrelsConfig(); + } + + + + } diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 4eb75ae..49bcaf9 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -23,93 +23,73 @@ public InventoryClose(PostOffice postOffice) { @EventHandler public void onInventoryClose(InventoryCloseEvent event) { - PostOffice plugin = PostOffice.getInstance(); Inventory inventory = event.getInventory(); - Player player = (Player) event.getPlayer(); + + // Check if the inventory is a barrel if (inventory.getType() == InventoryType.BARREL) { Block clickedBlock = Objects.requireNonNull(event.getInventory().getLocation()).getBlock(); if (clickedBlock.getType() == Material.BARREL) { - BlockState blockState = clickedBlock.getState(); - - if (blockState instanceof Barrel) { - Barrel barrel = (Barrel) blockState; - - if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - boolean isOwner = false; - String ownerName = ""; - - Sign sign = null; - boolean foundSign = false; + if (postOffice.helpers.isBarrelInConfig(clickedBlock)) { - for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) { - Block relativeBlock = clickedBlock.getRelative(face); + // This barrel is in the config, treat it as a valid post box + UUID boxOwnerUUID = postOffice.helpers.getOwnerUUID(clickedBlock); - if (relativeBlock.getType().name().toUpperCase().contains("SIGN")) { - foundSign = true; - sign = (Sign) relativeBlock.getState(); - ownerName = sign.getLine(1); + if (boxOwnerUUID == null) { + player.sendMessage(ChatColor.RED + "This post box is unclaimed."); + } else { + OfflinePlayer boxOwner = postOffice.helpers.getPlayer(boxOwnerUUID); + player.sendMessage("Closing valid post box. Owner: " + boxOwner.getName()); + } - if (sign.getLine(1).equalsIgnoreCase(event.getPlayer().getName())) { - isOwner = true; - break; - } - } + // Check if the player owns the post box + if (boxOwnerUUID != null && postOffice.helpers.isPostBoxOwner(clickedBlock, player)) { + // Player owns the post box - clear the "You have mail" message from the sign + Block signBlock = postOffice.helpers.getSignFromConfig(clickedBlock); + if (signBlock != null && signBlock.getState() instanceof Sign) { + Sign sign = (Sign) signBlock.getState(); + sign.setLine(2, ""); // Clear the 3rd line + sign.update(); } + // Remove any mail notifications (from the internal mail list) + postOffice.playersWithMail.remove(player.getName()); + postOffice.helpers.saveMailFile(); + + } else if (boxOwnerUUID != null) { + // Player does not own the post box - check for item changes + postOffice.newItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); + if (postOffice.newItemCount > postOffice.previousItemCount) { + // Update the sign to notify the owner of mail + Block signBlock = postOffice.helpers.getSignFromConfig(clickedBlock); + if (postOffice.signNotification && signBlock != null && signBlock.getState() instanceof Sign) { + Sign sign = (Sign) signBlock.getState(); + sign.setLine(2, ChatColor.GREEN + "You have mail"); // Set "You have mail" on the 3rd line + sign.update(); + } - if (!ownerName.isEmpty()) { - if (!isOwner) { - postOffice.newItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); - if (postOffice.newItemCount > postOffice.previousItemCount) { - - // Set their sign to notify them they have mail - if (postOffice.signNotification && foundSign) { - - sign.setLine(2, ChatColor.GREEN + "You have mail"); - sign.update(); - - } - - player.sendMessage(ChatColor.translateAlternateColorCodes('&', - postOffice.language.sentMessage - .replace("%sender%", player.getName()) - .replace("%receiver%", ownerName))); - - // Get owner UUID - OfflinePlayer postBoxOwner = Bukkit.getOfflinePlayer(ownerName); - UUID ownerUUID = postBoxOwner.getUniqueId(); - - // Add owners to mail list if someone else is adding items - if (postOffice.consoleLogs) { - plugin.getLogger().info(player.getName() + " added mail for " + ownerName); - } - postOffice.playersWithMail.add(ownerName); - postOffice.helpers.saveMailFile(); - - Player owner = Bukkit.getPlayer(ownerName); - if (owner != null) { - owner.sendMessage(ChatColor.translateAlternateColorCodes('&', - postOffice.language.receivedMessage - .replace("%sender%", player.getName()) - .replace("%receiver%", owner.getName()))); - } - } - } else { - - // Set their sign to notify them they have mail - if (postOffice.signNotification && foundSign) { - - sign.setLine(2, ""); - sign.update(); - - } + // Send message to the player + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.sentMessage + .replace("%sender%", player.getName()) + .replace("%receiver%", Bukkit.getOfflinePlayer(boxOwnerUUID).getName()))); - // If they were the owner, and it was their barrel, remove them from the mail list - postOffice.playersWithMail.remove(event.getPlayer().getName()); - postOffice.helpers.saveMailFile(); + // Add the owner to the mail list + if (postOffice.consoleLogs) { + plugin.getLogger().info(player.getName() + " added mail for " + Bukkit.getOfflinePlayer(boxOwnerUUID).getName()); + } + postOffice.playersWithMail.add(Bukkit.getOfflinePlayer(boxOwnerUUID).getName()); + postOffice.helpers.saveMailFile(); + + // Notify the owner if they are online + Player owner = Bukkit.getPlayer(boxOwnerUUID); + if (owner != null) { + owner.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.receivedMessage + .replace("%sender%", player.getName()) + .replace("%receiver%", owner.getName()))); } } } @@ -118,4 +98,8 @@ public void onInventoryClose(InventoryCloseEvent event) { } } -} \ No newline at end of file + +} + + + From a29a8e3ce2ab5b10eca13960b4ad661baf1add21 Mon Sep 17 00:00:00 2001 From: Kris Date: Tue, 17 Sep 2024 21:53:56 +0930 Subject: [PATCH 10/45] Added /postoffice remove command to unregister a post box --- .../java/io/shantek/functions/Commands.java | 62 ++++++++++++++++++- .../java/io/shantek/functions/Helpers.java | 53 ++++++++++------ 2 files changed, 94 insertions(+), 21 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index fb5ed59..d4710c6 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -23,7 +23,67 @@ public Commands(PostOffice postOffice) { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("postoffice")) { - if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { + + // Postoffice remove command + if (args[0].equalsIgnoreCase("remove")) { + if (sender instanceof Player) { + Player player = (Player) sender; + + // Ensure they have the proper permission + if (player.hasPermission("shantek.postoffice.remove") || player.isOp()) { + + // Get the block the player is looking at (sign or barrel) + Block targetBlock = player.getTargetBlock(null, 10); + + Block barrelBlock = null; + + // Check if the player is looking at a sign + if (Tag.SIGNS.isTagged(targetBlock.getType())) { + // Retrieve the attached barrel + barrelBlock = postOffice.helpers.getAttachedBarrel(targetBlock); + } else if (targetBlock.getType() == Material.BARREL) { + // Player is looking directly at a barrel + barrelBlock = targetBlock; + } + + // Ensure we have a valid barrel block + if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { + player.sendMessage(ChatColor.RED + "You must be looking at a barrel or a sign attached to a barrel."); + return true; + } + + // Check if the barrel exists in the config (registered post box) + if (!postOffice.helpers.isBarrelInConfig(barrelBlock)) { + player.sendMessage(ChatColor.RED + "This isn't a registered post box."); + return true; + } + + // Call the helper to remove the barrel from the cache and config + postOffice.helpers.removeBarrelFromCache(barrelBlock); + + // Optionally clear the sign associated with the post box + Block signBlock = postOffice.helpers.getSignForBarrel(barrelBlock); + if (signBlock != null && signBlock.getState() instanceof Sign) { + Sign sign = (Sign) signBlock.getState(); + sign.setLine(1, ""); // Clear the second line + sign.setLine(2, ""); // Clear the third line + sign.update(); // Update the sign + } + + player.sendMessage(ChatColor.GREEN + "Post box removed successfully."); + + return true; + } else { + player.sendMessage(ChatColor.RED + "You don't have permission to use this command."); + return true; + } + } else { + sender.sendMessage(ChatColor.RED + "This command can only be used by players."); + return true; + } + } + + else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("shantek.postoffice.reload") || sender.isOp()) { // Reload all the config and language file diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 8c9b362..1cc5839 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -9,10 +9,7 @@ import java.util.logging.Level; import org.bukkit.*; -import org.bukkit.block.Barrel; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; +import org.bukkit.block.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -515,10 +512,6 @@ public OfflinePlayer getPlayer(UUID uuid) { return Bukkit.getOfflinePlayer(uuid); } - public OfflinePlayer getPlayerReference(UUID ownerUuid) { - return Bukkit.getOfflinePlayer(ownerUuid); - } - public boolean isPostBoxOwner(Block block, Player player) { UUID playerUUID = player.getUniqueId(); return getOwnerUUID(block).equals(playerUUID); @@ -548,16 +541,6 @@ public String getPlayerName(UUID uuid) { return offlinePlayer.getName(); // This may return null if the player's name is not available } - public UUID getPlayerUUID(Player player) { - return player.getUniqueId(); - } - - // Method to check if a player is online by UUID - public boolean isPlayerOnline(UUID uuid) { - Player player = Bukkit.getPlayer(uuid); - return player != null; - } - //endregion @@ -576,13 +559,43 @@ public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ow public void removeBarrelFromCache(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); + // Retrieve the associated sign before removing the barrel from the cache + BarrelData barrelData = barrelsCache.get(barrelLocationString); + if (barrelData != null) { + String signLocationString = barrelData.getSignLocation(); + if (signLocationString != null) { + // Get the sign block from its location string + String[] parts = signLocationString.split("_"); + if (parts.length == 4) { + World world = Bukkit.getWorld(parts[0]); + int x = Integer.parseInt(parts[1]); + int y = Integer.parseInt(parts[2]); + int z = Integer.parseInt(parts[3]); + + if (world != null) { + Block signBlock = world.getBlockAt(x, y, z); + if (signBlock.getState() instanceof Sign) { + // Clear the sign text (e.g., remove the player's name and "Unclaimed" message) + Sign sign = (Sign) signBlock.getState(); + sign.setLine(0, ""); // Clear the first line + sign.setLine(1, ""); // Clear the second line + sign.setLine(2, ""); // Clear the third line + sign.setLine(3, ""); // Clear the fourth line + sign.update(); // Update the sign + } + } + } + } + } + // Remove the barrel from the cache barrelsCache.remove(barrelLocationString); - // Optionally, you could save the cache to file immediately here: - // saveCacheToFile(); + // Save the cache to file immediately + saveCacheToFile(); } + public void saveCacheToFile() { FileConfiguration barrelsConfig = getBarrelsConfig(); From 1b6c53f4493edc0be5236aed0a3fbe62d93d3776 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:01:10 +0930 Subject: [PATCH 11/45] Updated readme with new permission and command information --- README.md | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 720c8fc..8db1763 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ [![License: GPL](https://img.shields.io/badge/license-GPL-blue.svg)](LICENSE) [![Discord](https://img.shields.io/discord/628396916639793152.svg?color=%237289da&label=discord)](https://shantek.co/discord) +## Version 2.0.0 is in active development. Do not use this build in its current state until further notice. + #### Looking for the latest dev builds? You can find them [here!](https://shantek.dev/job/PostOffice/) ### Post Office is a fully functional Minecraft Post Office plugin for your Bukkit based Minecraft servers. @@ -23,20 +25,45 @@ Available now on [Modrinth](https://modrinth.com/plugin/postoffice), [CurgeForge ![Plugin Usage Stats](https://bstats.org/signatures/bukkit/Post%20Office.svg) +## Commands +Below are the commands used to manage the post office barrels and plugin: + +### /postoffice register +Place a barrel and a sign on the front. Run this command while looking at the sign to register the post box in the config. + +### /postoffice claim +If players have the claim permission, this command will allow them to claim an already registered post box. + +### /postoffice claim playername +Used for an admin/mod to claim a post box on behalf of another player. + +### /postoffice remove +Run while looking at a registered or claimed post box to remove the owner and the post box from the config. + +### /postoffice info +Run while looking at a post box barrel to get information about the registration state/owner. + + ## Permissions The below permissions are intended for giving your mods extra access and abilities within your post office. By default, players will be able to access their own post box without any additional permission nodes being granted. +### shantek.postoffice.use +This permission prevents a player from using/interacting with the post office. All players have this by default, so use this to deny access to any players you wish to ban from the post box system. + ### shantek.postoffice.removeitems -Allow these players to remove items from any post box +Allow these players to remove items from any post box. + +### shantek.postoffice.register +Allow a player to register/remove a post box in the config. -### shantek.postoffice.create -Allow a player to create a post box +### shantek.postoffice.claim +Allow a player to claim their own post box. -### shantek.postoffice.break -Allow a player to break any post box +### shantek.postoffice.claim.others +Allow a player to claim a post box for other players (generally used by admin/mods). ### shantek.postoffice.updatenotification -Any player with this permission will be notified if there is an update to the plugin +Any player with this permission will be notified if there is an update to the plugin. ## External Links From d65d59e498e550a919007df697428bd9577940b0 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:01:45 +0930 Subject: [PATCH 12/45] Implemented the new commands and permissions --- .../java/io/shantek/functions/Commands.java | 14 +++---- src/main/resources/plugin.yml | 41 +++++++++++++++++-- 2 files changed, 44 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index d4710c6..2f13675 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -30,7 +30,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String Player player = (Player) sender; // Ensure they have the proper permission - if (player.hasPermission("shantek.postoffice.remove") || player.isOp()) { + if (player.hasPermission("shantek.postoffice.register") || player.isOp()) { // Get the block the player is looking at (sign or barrel) Block targetBlock = player.getTargetBlock(null, 10); @@ -58,9 +58,6 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - // Call the helper to remove the barrel from the cache and config - postOffice.helpers.removeBarrelFromCache(barrelBlock); - // Optionally clear the sign associated with the post box Block signBlock = postOffice.helpers.getSignForBarrel(barrelBlock); if (signBlock != null && signBlock.getState() instanceof Sign) { @@ -70,6 +67,9 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String sign.update(); // Update the sign } + // Call the helper to remove the barrel from the cache and config + postOffice.helpers.removeBarrelFromCache(barrelBlock); + player.sendMessage(ChatColor.GREEN + "Post box removed successfully."); return true; @@ -147,7 +147,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { if (sender instanceof Player) { Player player = (Player) sender; - if (sender.hasPermission("shantek.postoffice.create") || sender.isOp()) { + if (sender.hasPermission("shantek.postoffice.register") || sender.isOp()) { // Ensure they are looking at a sign Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks @@ -204,7 +204,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { return true; } } else if (args[0].equalsIgnoreCase("claim") && args.length == 2) { - if (sender.hasPermission("shantek.postoffice.admin") || sender.isOp()) { + if (sender.hasPermission("shantek.postoffice.claim.others") || sender.isOp()) { // Ensure they are looking at a sign if (!(sender instanceof Player)) { @@ -282,7 +282,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { Player player = (Player) sender; UUID playerUUID = player.getUniqueId(); - if (sender.hasPermission("shantek.postoffice.create") || sender.isOp()) { + if (sender.hasPermission("shantek.postoffice.claim") || sender.isOp()) { // Ensure they are looking at a sign Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 773a7f7..f3e9753 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -6,7 +6,40 @@ main: io.shantek.PostOffice commands: postoffice: - description: Reload the PostOffice plugin - usage: /postoffice reload - permission: shantek.postoffice.reload - default: op \ No newline at end of file + description: Post office plugin commands + aliases: [po] + usage: /postoffice [subcommand] + permission: shantek.postoffice.use + +permissions: + shantek.postoffice.use: + description: Allows usage of the Post Office commands. + default: true + + shantek.postoffice.register: + description: Allows the player to register a post box in the config. + default: op + + shantek.postoffice.remove: + description: Allows the player to remove a post box from the config file. + default: op + + shantek.postoffice.reload: + description: Allows the player to reload the post office plugin config. + default: op + + shantek.postoffice.claim: + description: Allows players to claim their own post box. + default: op + + shantek.postoffice.claim.others: + description: Allows admin/mods to claim a post box for others. + default: op + + shantek.postoffice.removeitems: + description: Allows admin/mods to remove items from other post boxes. + default: op + + shantek.postoffice.updatenotification: + description: Notifies OPs/admins/mods of a plugin update. + default: op From 032a65faa60ce86fa3ae811440d4f3bff55814aa Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:05:52 +0930 Subject: [PATCH 13/45] Added permission check when opening a barrel. Deny if they don't have the use permission. --- .../java/io/shantek/listeners/InventoryOpen.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index 258ef99..6616162 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -1,10 +1,12 @@ package io.shantek.listeners; import io.shantek.PostOffice; +import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Barrel; import org.bukkit.block.Block; import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryOpenEvent; @@ -24,6 +26,7 @@ public InventoryOpen(PostOffice postOffice) { public void onInventoryOpen(InventoryOpenEvent event) { Inventory inventory = event.getInventory(); + Player player = (Player) event.getPlayer(); if (inventory.getType() == InventoryType.BARREL) { @@ -35,7 +38,16 @@ public void onInventoryOpen(InventoryOpenEvent event) { Barrel barrel = (Barrel) blockState; if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); + + if (player.hasPermission("shantek.postoffice.use")) { + + // They have permission to use the post office system. Let them open the post box + postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); + } + else { + player.sendMessage(ChatColor.RED + "You don't have permission to interact with post boxes."); + } + } } } From 76609a3e81ad1a784d9ff9160481b90edfb79b67 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:16:31 +0930 Subject: [PATCH 14/45] Prevent sign editing for a registered barrel --- .../shantek/listeners/BarrelProtection.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index e343736..6270daf 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -2,6 +2,7 @@ import io.shantek.PostOffice; import org.bukkit.ChatColor; +import org.bukkit.Material; import org.bukkit.block.*; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; @@ -34,20 +35,14 @@ public void onSignChange(SignChangeEvent event) { } Player player = event.getPlayer(); + + // Ensure the sign is attached to a barrel + // If this is a post box barrel, cancel the sign editing Block signBlock = event.getBlock(); + Block attachedBarrel = postOffice.helpers.getBarrelFromSign(signBlock); - if (postOffice.helpers.hasBarrelNearby(signBlock)) { - if (!player.isOp() && !player.hasPermission("shantek.postoffice.create")) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.createError)); - event.setCancelled(true); - } else { - String line2 = event.getLine(1); - if (line2 != null && !line2.isEmpty()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', - postOffice.language.postboxCreated - .replace("%username%", line2))); - } - } + if (postOffice.helpers.isBarrelInConfig(attachedBarrel)) { + event.setCancelled(true); } } From ebd70c61a08f96f450c5b4318e295438e17c4cb5 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:20:44 +0930 Subject: [PATCH 15/45] Removed unused helpers --- .../java/io/shantek/functions/Helpers.java | 137 ------------------ 1 file changed, 137 deletions(-) diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 1cc5839..e5e43a5 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -28,7 +28,6 @@ public Helpers(PostOffice postOffice) { // In-memory cache to store barrel data (key: block location, value: owner UUID) private Map barrelsCache; - private FileConfiguration barrelsConfig = null; private File barrelsConfigFile = null; @@ -63,27 +62,6 @@ public boolean hasBarrelNearby(Block block) { return false; } - // Method to check if the block the player is looking at is a custom barrel - public boolean isLookingAtCustomBarrel(Player player) { - - // Get the block the player is looking at (with a max distance of 10) - Block targetBlock = player.getTargetBlock((Set) null, 10); - - if (targetBlock.getType() == Material.BARREL) { - BlockState state = targetBlock.getState(); - - if (state instanceof Barrel) { - Barrel barrel = (Barrel) state; - String barrelCustomName = barrel.getCustomName(); - - // Check if the barrel has the custom name - return barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName); - } - } - - return false; // Not looking at a valid custom barrel - } - // Check if the block is a protected post box public boolean isProtectedPostBox(Block block) { if (block.getType() == Material.BARREL) { @@ -115,17 +93,6 @@ public boolean isSignNextToProtectedBarrel(Block signBlock) { return false; } - // Check for a sign attached to a barrel - public Block getAttachedSign(Block barrelBlock) { - for (BlockFace face : BlockFace.values()) { - Block relativeBlock = barrelBlock.getRelative(face); - if (Tag.SIGNS.isTagged(relativeBlock.getType())) { - return relativeBlock; // Return the block if it's a sign - } - } - return null; // No sign found - } - //region Barrel Caching and Config Operations private void loadBarrelsIntoCache() { @@ -164,106 +131,6 @@ private void loadBarrelsIntoCache() { } } - public void addBarrelWithSign(Block barrelBlock, Block signBlock, UUID newOwnerUUID, String state) { - if (barrelBlock.getType() != Material.BARREL || !Tag.SIGNS.isTagged(signBlock.getType())) { - return; // Only proceed if the block is a barrel and the sign is valid - } - - String barrelLocationString = getBlockLocationString(barrelBlock); - String signLocationString = getBlockLocationString(signBlock); - - // Create or update the BarrelData - BarrelData barrelData = new BarrelData(newOwnerUUID, state, signLocationString); - - // Add or update the barrel data in the cache - barrelsCache.put(barrelLocationString, barrelData); - - // Log for debugging purposes - postOffice.getLogger().info("Adding/Updating barrel at: " + barrelLocationString); - postOffice.getLogger().info("Sign location for barrel: " + signLocationString); - - // Save the updated cache to disk - saveBarrelsToDisk(); - } - - // Remove barrel from in-memory cache and save to disk if necessary - public void removeBarrel(Block block) { - String blockLocationString = getBlockLocationString(block); - - // Check if the barrel exists in the cache - if (barrelsCache.containsKey(blockLocationString)) { - // Barrel exists, remove it from the cache - barrelsCache.remove(blockLocationString); - - // Remove the barrel from the config as well - barrelsConfig.set("barrels." + blockLocationString, null); - - // Save the updated cache to barrels.yml - saveBarrelsToDisk(); - } - } - - // Save the in-memory cache to barrels.yml - public void saveBarrelsToDisk() { - FileConfiguration barrelsConfig = getBarrelsConfig(); - - // Clear existing entries in the file - barrelsConfig.set("barrels", null); - - // Iterate over the cache and save each barrel's data - for (Map.Entry entry : barrelsCache.entrySet()) { - String barrelLocationString = entry.getKey(); - BarrelData barrelData = entry.getValue(); - - String path = "barrels." + barrelLocationString; - - // Set the owner UUID, or "none" if no owner is set - barrelsConfig.set(path + ".owner", barrelData.getOwnerUUID() != null ? barrelData.getOwnerUUID().toString() : "none"); - - // Set the state (e.g., "claimed", "registered") - barrelsConfig.set(path + ".state", barrelData.getState()); - - // Set the sign location if it exists - barrelsConfig.set(path + ".sign", barrelData.getSignLocation()); - - // Parse and store the world and coordinates from the barrel location string - String[] parts = barrelLocationString.split("_"); - if (parts.length == 4) { - barrelsConfig.set(path + ".world", parts[0]); - barrelsConfig.set(path + ".x", Integer.parseInt(parts[1])); - barrelsConfig.set(path + ".y", Integer.parseInt(parts[2])); - barrelsConfig.set(path + ".z", Integer.parseInt(parts[3])); - } - } - - // Save the updated configuration to barrels.yml - saveBarrelsConfig(); - } - - - public void registerBarrelWithSign(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { - String barrelLocationString = getBlockLocationString(barrelBlock); - String signLocationString = getBlockLocationString(signBlock); - - FileConfiguration barrelsConfig = getBarrelsConfig(); - - // Register barrel and sign in barrels.yml with proper world and coordinates - barrelsConfig.set("barrels." + barrelLocationString + ".state", state); // Set the state to registered/claimed - barrelsConfig.set("barrels." + barrelLocationString + ".owner", ownerUUID != null ? ownerUUID.toString() : "none"); - barrelsConfig.set("barrels." + barrelLocationString + ".sign", signLocationString); - barrelsConfig.set("barrels." + barrelLocationString + ".world", barrelBlock.getWorld().getName()); - barrelsConfig.set("barrels." + barrelLocationString + ".x", barrelBlock.getX()); - barrelsConfig.set("barrels." + barrelLocationString + ".y", barrelBlock.getY()); - barrelsConfig.set("barrels." + barrelLocationString + ".z", barrelBlock.getZ()); - - // Log the barrel and sign registration for debugging purposes - postOffice.getLogger().info("Registering barrel at: " + barrelLocationString); - postOffice.getLogger().info("Sign location for barrel: " + signLocationString); - - saveBarrelsConfig(); // Save changes to barrels.yml - reloadBarrelsConfig(); - } - public Block getSignFromConfig(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); // Convert block to location string String path = "barrels." + barrelLocationString + ".sign"; // Use this location string in the config @@ -331,7 +198,6 @@ public boolean doesPlayerHavePostBox(UUID playerUUID) { return false; // The player does not have a post box } - public String getPlayerPostBoxLocation(UUID playerUUID) { FileConfiguration barrelsConfig = getBarrelsConfig(); @@ -543,8 +409,6 @@ public String getPlayerName(UUID uuid) { //endregion - - public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { String barrelLocationString = getBlockLocationString(barrelBlock); String signLocationString = getBlockLocationString(signBlock); @@ -595,7 +459,6 @@ public void removeBarrelFromCache(Block barrelBlock) { saveCacheToFile(); } - public void saveCacheToFile() { FileConfiguration barrelsConfig = getBarrelsConfig(); From e9838b3291ef88e648cb2db233bda591fbeca6b9 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 09:27:58 +0930 Subject: [PATCH 16/45] Added new commands to tab completer --- .../io/shantek/functions/TabCompleter.java | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/shantek/functions/TabCompleter.java b/src/main/java/io/shantek/functions/TabCompleter.java index 58cb227..bec2fa7 100644 --- a/src/main/java/io/shantek/functions/TabCompleter.java +++ b/src/main/java/io/shantek/functions/TabCompleter.java @@ -1,14 +1,20 @@ package io.shantek.functions; import io.shantek.PostOffice; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; public class TabCompleter implements org.bukkit.command.TabCompleter { public PostOffice postOffice; + public TabCompleter(PostOffice postOffice) { this.postOffice = postOffice; } @@ -19,13 +25,40 @@ public List onTabComplete(CommandSender sender, Command cmd, String labe if (cmd.getName().equalsIgnoreCase("postoffice")) { if (args.length == 1) { - // Check the first argument - if ("reload".startsWith(args[0].toLowerCase()) && sender.hasPermission("shantek.postoffice.reload")) { + // Add commands based on permissions + if (sender.hasPermission("shantek.postoffice.reload")) { completions.add("reload"); } + if (sender.hasPermission("shantek.postoffice.claim") || sender.hasPermission("shantek.postoffice.claim.others")) { + completions.add("claim"); + } + if (sender.hasPermission("shantek.postoffice.register")) { + completions.add("register"); + completions.add("remove"); + } + + // Commands all players have access to + completions.add("info"); + + // Filter completions based on partial input + return completions.stream() + .filter(c -> c.startsWith(args[0].toLowerCase())) + .sorted() + .collect(Collectors.toList()); + } else if (args.length == 2 && args[0].equalsIgnoreCase("claim") && sender.hasPermission("shantek.postoffice.claim.others")) { + // Populate online players' names for claim.others permission + for (Player player : Bukkit.getOnlinePlayers()) { + completions.add(player.getName()); + } + + // Filter players based on partial input + return completions.stream() + .filter(c -> c.toLowerCase().startsWith(args[1].toLowerCase())) + .sorted() + .collect(Collectors.toList()); } } - return completions; - } + return Collections.emptyList(); + } } From bf928c6407372ed42d2bf6a69eedac23a520ce89 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 10:45:21 +0930 Subject: [PATCH 17/45] Switched players with mail logic to use UUID --- src/main/java/io/shantek/PostOffice.java | 2 +- src/main/java/io/shantek/listeners/InventoryClose.java | 4 ++-- src/main/java/io/shantek/listeners/PlayerJoin.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 73a8798..683db49 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -51,7 +51,7 @@ public void onEnable() { // Check for a data folder, create it if needed helpers.checkForDataFolder(); - this.mailFile = new File(getDataFolder(), "mail.txt"); + this.mailFile = new File(getDataFolder(), "hasmail.txt"); getCommand("postoffice").setExecutor(new Commands(this)); diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 49bcaf9..8771bf7 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -55,7 +55,7 @@ public void onInventoryClose(InventoryCloseEvent event) { } // Remove any mail notifications (from the internal mail list) - postOffice.playersWithMail.remove(player.getName()); + postOffice.playersWithMail.remove(player.getUniqueId().toString()); postOffice.helpers.saveMailFile(); } else if (boxOwnerUUID != null) { @@ -80,7 +80,7 @@ public void onInventoryClose(InventoryCloseEvent event) { if (postOffice.consoleLogs) { plugin.getLogger().info(player.getName() + " added mail for " + Bukkit.getOfflinePlayer(boxOwnerUUID).getName()); } - postOffice.playersWithMail.add(Bukkit.getOfflinePlayer(boxOwnerUUID).getName()); + postOffice.playersWithMail.add(boxOwnerUUID.toString()); postOffice.helpers.saveMailFile(); // Notify the owner if they are online diff --git a/src/main/java/io/shantek/listeners/PlayerJoin.java b/src/main/java/io/shantek/listeners/PlayerJoin.java index 8cd7028..5f6d4da 100644 --- a/src/main/java/io/shantek/listeners/PlayerJoin.java +++ b/src/main/java/io/shantek/listeners/PlayerJoin.java @@ -22,7 +22,7 @@ public void onPlayerLogin(PlayerJoinEvent event) { Player player = event.getPlayer(); - if (postOffice.playersWithMail.contains(player.getName())) { + if (postOffice.playersWithMail.contains(player.getUniqueId().toString())) { // Set initial delay of 1 second long messageDelay = 20L; From 119eceaeacadb5385842da91a7dd5152a711fbc0 Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 15:12:12 +0930 Subject: [PATCH 18/45] Remove old mail.txt file --- src/main/java/io/shantek/PostOffice.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 683db49..112dbbd 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -94,6 +94,17 @@ public void onEnable() { } // Register event listeners registerEventListeners(); + + + // Delete old mail file - remove in a future update + // Now using a new file that stores UUIDs instead + File mailFile = new File("mail.txt"); + if (mailFile.exists()) { + // Attempt to delete the file + if (mailFile.delete()) { + System.out.println("Deleted old mail file."); + } + } } public void registerEventListeners() { From daf7cc2d9e594d10f960dd425bbe7f7efccea7cb Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 15:30:05 +0930 Subject: [PATCH 19/45] Removed old permission registration --- src/main/java/io/shantek/PostOffice.java | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 112dbbd..82879eb 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -8,8 +8,6 @@ import java.util.logging.*; import java.util.stream.Collectors; import org.bukkit.Bukkit; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.nio.file.*; import java.util.*; @@ -60,8 +58,6 @@ public void onEnable() { // Create an instance of PluginConfig this.pluginConfig = new PluginConfig(this); - - registerPluginPermissions(); pluginConfig.reloadConfigFile(); if (this.mailFile.exists()) { @@ -133,23 +129,5 @@ public void printInfoMessage(String message) { getLogger().info(message); // Print to the console } - private void registerPluginPermissions() { - // Register the permission node - Permission removeItemsPermission = new Permission("shantek.postoffice.removeitems"); - PluginManager pm = getServer().getPluginManager(); - pm.addPermission(removeItemsPermission); - - // Permission for breaking Post Boxes - Permission breakPermission = new Permission("shantek.postoffice.break"); - pm.addPermission(breakPermission); - - // Permission for creating Post Boxes - Permission createBoxPermission = new Permission("shantek.postoffice.create"); - pm.addPermission(createBoxPermission); - - // Permission for breaking Post Boxes - Permission updateNotificationPermission = new Permission("shantek.postoffice.updatenotification"); - pm.addPermission(updateNotificationPermission); - } } \ No newline at end of file From ff531c8aca6b1f083dc9d7675995440c415b987c Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 15:30:59 +0930 Subject: [PATCH 20/45] Fixed cancelling post box opening if player doesn't have permission --- .../io/shantek/listeners/InventoryOpen.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index 6616162..ab49c7a 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -31,26 +31,26 @@ public void onInventoryOpen(InventoryOpenEvent event) { if (inventory.getType() == InventoryType.BARREL) { Block clickedBlock = Objects.requireNonNull(inventory.getLocation()).getBlock(); - if (clickedBlock.getType() == Material.BARREL) { - BlockState blockState = clickedBlock.getState(); - if (blockState instanceof Barrel) { - Barrel barrel = (Barrel) blockState; + BlockState blockState = clickedBlock.getState(); - if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { + if (blockState instanceof Barrel) { + Barrel barrel = (Barrel) blockState; - if (player.hasPermission("shantek.postoffice.use")) { + if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - // They have permission to use the post office system. Let them open the post box - postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); - } - else { - player.sendMessage(ChatColor.RED + "You don't have permission to interact with post boxes."); - } + if (player.hasPermission("shantek.postoffice.use")) { + // They have permission to use the post office system. Let them open the post box + postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); + } else { + player.sendMessage(ChatColor.RED + "You don't have permission to interact with post boxes."); + event.setCancelled(true); } + } } + } } From 27ec8ca1a86ecb567b576ab3552c7a05108c6e9a Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 15:50:34 +0930 Subject: [PATCH 21/45] Fixed sign protection --- .../shantek/listeners/BarrelProtection.java | 47 ++++++++----------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index 6270daf..8dbdf2a 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -35,17 +35,22 @@ public void onSignChange(SignChangeEvent event) { } Player player = event.getPlayer(); - - // Ensure the sign is attached to a barrel - // If this is a post box barrel, cancel the sign editing Block signBlock = event.getBlock(); - Block attachedBarrel = postOffice.helpers.getBarrelFromSign(signBlock); - if (postOffice.helpers.isBarrelInConfig(attachedBarrel)) { - event.setCancelled(true); + // Get the attached barrel from the sign + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + + // Ensure the attached block is a barrel and that it is in the config + if (attachedBarrel != null && attachedBarrel.getType() == Material.BARREL) { + if (postOffice.helpers.isBarrelInConfig(attachedBarrel)) { + // Cancel the sign change event if the barrel is in the config (protected post box) + player.sendMessage(ChatColor.RED + "You cannot modify a post box sign."); + event.setCancelled(true); + } } } + @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (!postOffice.postBoxProtection) { @@ -55,30 +60,16 @@ public void onBlockBreak(BlockBreakEvent event) { Player player = event.getPlayer(); Block brokenBlock = event.getBlock(); - // Check if the broken block is a barrel - if (brokenBlock.getState() instanceof Barrel) { - Barrel barrel = (Barrel) brokenBlock.getState(); - String barrelCustomName = barrel.getCustomName(); - - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - if (!player.isOp() && !player.hasPermission("shantek.postoffice.break")) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); - event.setCancelled(true); - } - } - } - - // Check if the broken block is a sign - if (brokenBlock.getState() instanceof Sign) { - if (postOffice.helpers.hasBarrelNearby(brokenBlock)) { - if (!player.isOp() && !player.hasPermission("shantek.postoffice.break")) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); - event.setCancelled(true); - } + // Check if the broken block is a protected post box (either a barrel or a sign) + if (postOffice.helpers.isProtectedPostBox(brokenBlock)) { + if (!player.isOp() && !player.hasPermission("shantek.postoffice.break")) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); + event.setCancelled(true); } } } + @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (!postOffice.postBoxProtection) { @@ -108,13 +99,13 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { // Check if the source is a barrel and the destination is a hopper or hopper minecart if (sourceHolder instanceof Barrel && (destinationHolder instanceof Hopper || destinationHolder instanceof HopperMinecart)) { Barrel barrel = (Barrel) sourceHolder; - String barrelCustomName = barrel.getCustomName(); - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + if (postOffice.helpers.isProtectedPostBox(barrel.getBlock())) { event.setCancelled(true); } } } + @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (!postOffice.postBoxProtection) { From 99eeb6634f8e37e165ade3185a59fba1ae9bfcaf Mon Sep 17 00:00:00 2001 From: Kris Date: Wed, 18 Sep 2024 20:32:38 +0930 Subject: [PATCH 22/45] Fixed command and barrel registration issues --- .../java/io/shantek/functions/Commands.java | 2 + .../java/io/shantek/functions/Helpers.java | 49 ++++++++++++++----- src/main/resources/plugin.yml | 1 - 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 2f13675..d7686bb 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -336,6 +336,8 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { postOffice.helpers.saveCacheToFile(); // Save the cache to disk return true; + } else { + sender.sendMessage(ChatColor.RED + "You don't have permission to claim your own post box."); } } else { sender.sendMessage(ChatColor.RED + "This command can only be used by players."); diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index e5e43a5..77dc32d 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -229,7 +229,6 @@ public String getPlayerPostBoxLocation(UUID playerUUID) { //region Retrieving Sign Information - // Retrieve the location of the sign attached to a barrel public Block getSignForBarrel(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); @@ -238,15 +237,33 @@ public Block getSignForBarrel(Block barrelBlock) { if (signLocationString != null) { String[] parts = signLocationString.split("_"); - String worldName = parts[0]; - int x = Integer.parseInt(parts[1]); - int y = Integer.parseInt(parts[2]); - int z = Integer.parseInt(parts[3]); - return postOffice.getServer().getWorld(worldName).getBlockAt(x, y, z); + // Ensure the parts are valid (should be 4 parts: world, x, y, z) + if (parts.length == 4) { + String worldName = parts[0]; + int x, y, z; + + try { + x = Integer.parseInt(parts[1]); + y = Integer.parseInt(parts[2]); + z = Integer.parseInt(parts[3]); + } catch (NumberFormatException e) { + postOffice.getLogger().warning("Invalid sign coordinates in config for barrel: " + barrelLocationString); + return null; // Invalid coordinates, return null + } + + World world = Bukkit.getWorld(worldName); + if (world != null) { + return world.getBlockAt(x, y, z); // Return the block at the saved sign location + } else { + postOffice.getLogger().warning("World not found for barrel: " + barrelLocationString); + } + } else { + postOffice.getLogger().warning("Invalid sign location string format for barrel: " + barrelLocationString); + } } - return null; // No sign found for this barrel + return null; // Sign not found or invalid format } // Method to check if the sign is attached to a barrel @@ -413,13 +430,22 @@ public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ow String barrelLocationString = getBlockLocationString(barrelBlock); String signLocationString = getBlockLocationString(signBlock); - // Update the cache with the new data - barrelsCache.put(barrelLocationString, new BarrelData(ownerUUID, signLocationString, state)); + // Create the BarrelData object with correct sign location and state + BarrelData barrelData = new BarrelData(ownerUUID, signLocationString, state); + + // Add or update the barrel data in the cache + barrelsCache.put(barrelLocationString, barrelData); + + // Log for debugging purposes + postOffice.getLogger().info("Adding/Updating barrel at: " + barrelLocationString); + postOffice.getLogger().info("Sign location for barrel: " + signLocationString); + postOffice.getLogger().info("Post box state: " + state); - // Optionally, you could save the cache to file immediately here: + // Optionally save the cache to disk immediately saveCacheToFile(); } + public void removeBarrelFromCache(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); @@ -489,7 +515,4 @@ public void saveCacheToFile() { saveBarrelsConfig(); } - - - } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index f3e9753..14917fe 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -8,7 +8,6 @@ commands: postoffice: description: Post office plugin commands aliases: [po] - usage: /postoffice [subcommand] permission: shantek.postoffice.use permissions: From d4baaaf292f8656944561a3e7941bb9563d66090 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 14:39:39 +0930 Subject: [PATCH 23/45] Fix update notification when unable to reach api or using a dev build --- .../io/shantek/functions/UpdateChecker.java | 43 ++++++++++++++++++- .../java/io/shantek/listeners/PlayerJoin.java | 8 +++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/shantek/functions/UpdateChecker.java b/src/main/java/io/shantek/functions/UpdateChecker.java index 788b4ad..47220ff 100644 --- a/src/main/java/io/shantek/functions/UpdateChecker.java +++ b/src/main/java/io/shantek/functions/UpdateChecker.java @@ -54,7 +54,46 @@ private static void checkForUpdates(String currentVersion, Plugin plugin) { } public static boolean isNewVersionAvailable(String currentVersion, String remoteVersion) { - // Directly compare the version strings - return !currentVersion.equals(remoteVersion); + // Check if the remote version is null, return false in that case + if (remoteVersion == null || remoteVersion.isEmpty()) { + return false; + } + + // Split the version strings by '.' to compare major, minor, and patch + String[] currentVersionParts = currentVersion.split("\\."); + String[] remoteVersionParts = remoteVersion.split("\\."); + + // Check if current version is a dev build (contains "-SNAPSHOT" or other pre-release indicators) + boolean isDevBuild = currentVersion.toLowerCase().contains("snapshot") || currentVersion.toLowerCase().contains("dev"); + + // Compare major, minor, and patch versions + for (int i = 0; i < Math.min(currentVersionParts.length, remoteVersionParts.length); i++) { + try { + int currentPart = Integer.parseInt(currentVersionParts[i]); + int remotePart = Integer.parseInt(remoteVersionParts[i]); + + // If the current version part is less than the remote, a new version is available + if (currentPart < remotePart) { + return true; + } + // If the current version part is greater, the current version is newer (possibly a dev build) + if (currentPart > remotePart) { + return false; + } + } catch (NumberFormatException e) { + // In case of non-numeric version parts (like "1.6.2-SNAPSHOT"), treat dev build as newer + if (isDevBuild) { + return false; // Consider dev builds to be newer than any stable release + } + } + } + + // If all version parts are equal, but one version has more parts (e.g., "1.6" vs "1.6.1"), compare lengths + if (currentVersionParts.length < remoteVersionParts.length) { + return true; // Remote version has more parts (e.g., 1.6 -> 1.6.1), so a new version is available + } + + return false; // No new version available } + } \ No newline at end of file diff --git a/src/main/java/io/shantek/listeners/PlayerJoin.java b/src/main/java/io/shantek/listeners/PlayerJoin.java index 5f6d4da..6be27e7 100644 --- a/src/main/java/io/shantek/listeners/PlayerJoin.java +++ b/src/main/java/io/shantek/listeners/PlayerJoin.java @@ -38,8 +38,12 @@ public void onPlayerLogin(PlayerJoinEvent event) { } if (postOffice.updateNotificationEnabled && (player.isOp() || player.hasPermission("shantek.postoffice.updatenotification"))) { - if (UpdateChecker.isNewVersionAvailable(postOffice.getDescription().getVersion(), UpdateChecker.remoteVersion)) { - player.sendMessage("[Post Office] An update is available! New version: " + UpdateChecker.remoteVersion); + String currentVersion = postOffice.getDescription().getVersion(); + String remoteVersion = UpdateChecker.remoteVersion; // Assuming UpdateChecker retrieves the remote version + + // Only notify if a newer version is available + if (UpdateChecker.isNewVersionAvailable(currentVersion, remoteVersion)) { + player.sendMessage("[Post Office] An update is available! New version: " + remoteVersion); } } From 971c263997437e3a1a436c25c7bb58ad91d493b0 Mon Sep 17 00:00:00 2001 From: Shantek Date: Thu, 19 Sep 2024 16:36:26 +0930 Subject: [PATCH 24/45] Update README with setup guide for 2.0 --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8db1763..2cc1893 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ [![License: GPL](https://img.shields.io/badge/license-GPL-blue.svg)](LICENSE) [![Discord](https://img.shields.io/discord/628396916639793152.svg?color=%237289da&label=discord)](https://shantek.co/discord) -## Version 2.0.0 is in active development. Do not use this build in its current state until further notice. - #### Looking for the latest dev builds? You can find them [here!](https://shantek.dev/job/PostOffice/) ### Post Office is a fully functional Minecraft Post Office plugin for your Bukkit based Minecraft servers. @@ -18,9 +16,12 @@ Available now on [Modrinth](https://modrinth.com/plugin/postoffice), [CurgeForge ## How does the plugin work? - Upload the JAR to your server and reboot -- Rename barrels in an anvil to "pobox" - if you want to use a different name, be sure to change this in the config and use /postoffice reload to update your config file. +- Make any desired changes to the config file (not essential), and then type /postoffice reload' as an op. - Place your barrels in your amazing Post Office build. -- Place a sign on the front of the barrel and type the barrel owners name on the second line, this then becomes the owner of the post box. +- Place a blank sign on the front of the barrel. +- While looking at the sign, type '/postoffice register' to register the barrel in the config file. +- Again while looking at the sign, if permitted your players can type '/postoffice claim' on a registered post box to claim it. +- Admin/mods can look at a sign and use '/postoffice claim playername' to claim a post box on behalf of another player. - Enjoy your awesome post office on your SMP! ![Plugin Usage Stats](https://bstats.org/signatures/bukkit/Post%20Office.svg) From 8e11a2d62db914e6d857c494cd8d6f3534808e07 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 18:25:17 +0930 Subject: [PATCH 25/45] Cleaned up update check --- src/main/java/io/shantek/functions/UpdateChecker.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/shantek/functions/UpdateChecker.java b/src/main/java/io/shantek/functions/UpdateChecker.java index 47220ff..8d0e3b8 100644 --- a/src/main/java/io/shantek/functions/UpdateChecker.java +++ b/src/main/java/io/shantek/functions/UpdateChecker.java @@ -89,11 +89,9 @@ public static boolean isNewVersionAvailable(String currentVersion, String remote } // If all version parts are equal, but one version has more parts (e.g., "1.6" vs "1.6.1"), compare lengths - if (currentVersionParts.length < remoteVersionParts.length) { - return true; // Remote version has more parts (e.g., 1.6 -> 1.6.1), so a new version is available - } - - return false; // No new version available + return currentVersionParts.length < remoteVersionParts.length; + // Remote version has more parts (e.g., 1.6 -> 1.6.1), so a new version is available + // No new version available } } \ No newline at end of file From aea5761b70a9728e94a12e3fe6367e442af7e53b Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 18:26:01 +0930 Subject: [PATCH 26/45] Only show new dev debugging console logs if enabled in the config --- .../java/io/shantek/functions/Helpers.java | 2 +- .../io/shantek/listeners/InventoryClick.java | 205 ++++++++---------- 2 files changed, 95 insertions(+), 112 deletions(-) diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 77dc32d..3a9bce4 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -27,7 +27,7 @@ public Helpers(PostOffice postOffice) { } // In-memory cache to store barrel data (key: block location, value: owner UUID) - private Map barrelsCache; + public Map barrelsCache; private FileConfiguration barrelsConfig = null; private File barrelsConfigFile = null; diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index e08c821..94804e1 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -1,7 +1,8 @@ package io.shantek.listeners; +import io.shantek.PostOffice; +import io.shantek.functions.BarrelData; import org.bukkit.ChatColor; -import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.*; import org.bukkit.entity.Player; @@ -14,13 +15,13 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import io.shantek.PostOffice; import java.util.Objects; +import java.util.UUID; public class InventoryClick implements Listener { - public PostOffice postOffice; + private final PostOffice postOffice; public InventoryClick(PostOffice postOffice) { this.postOffice = postOffice; @@ -32,123 +33,105 @@ public void onInventoryClick(InventoryClickEvent event) { Inventory inventory = event.getInventory(); Inventory clickedInventory = event.getClickedInventory(); - // If they aren't opening a barrel, ignore it - if (event.getClickedInventory() == null || inventory.getType() != InventoryType.BARREL) { + // If the clicked inventory isn't a barrel, ignore it + if (clickedInventory == null || inventory.getType() != InventoryType.BARREL) { + return; + } + + Block clickedBlock = Objects.requireNonNull(inventory.getLocation()).getBlock(); + if (clickedBlock.getType() != Material.BARREL) { + return; + } + + // Get the location string for the barrel + String barrelLocationString = postOffice.helpers.getBlockLocationString(clickedBlock); + + // Log barrel location + if (postOffice.consoleLogs) { + postOffice.getLogger().info("Player is interacting with a barrel at location: " + barrelLocationString); + } + + // Fetch the barrel data from the cache + BarrelData barrelData = postOffice.helpers.barrelsCache.get(barrelLocationString); // Use barrelsCache directly + + // Check if barrel data is null (not registered) + if (barrelData == null) { + player.sendMessage(ChatColor.RED + "This is not a registered postbox."); + return; + } + + // Log the owner and the player interacting + UUID ownerUUID = barrelData.getOwnerUUID(); + if (postOffice.consoleLogs) { + postOffice.getLogger().info("Owner of the barrel: " + (ownerUUID != null ? ownerUUID.toString() : "None")); + postOffice.getLogger().info("Player interacting: " + player.getUniqueId()); + } + + // Determine if the player is the owner or has permission + boolean isOwner = ownerUUID != null && ownerUUID.equals(player.getUniqueId()); + boolean hasPermissionToRemove = player.hasPermission("shantek.postoffice.removeitems"); + + // Log the result of the ownership and permission checks + if (postOffice.consoleLogs) { + postOffice.getLogger().info("Is owner: " + isOwner); + postOffice.getLogger().info("Has permission to remove items: " + hasPermissionToRemove); + } + + // Prevent non-owners without permission from interacting with the post box + if (!isOwner && !hasPermissionToRemove) { + if (postOffice.consoleLogs) { + postOffice.getLogger().info("Player " + player.getName() + " tried to interact without permission."); + } + player.sendMessage(ChatColor.RED + postOffice.language.removeItemError); + event.setCancelled(true); return; } - // Prevent the player from double-clicking items in their own inventory to remove items + // Prevent double-clicking items in player's own inventory to remove items if (event.getClick() == ClickType.DOUBLE_CLICK) { if (clickedInventory == player.getInventory() || clickedInventory.getType() == InventoryType.PLAYER) { - Inventory topInventory = player.getOpenInventory().getTopInventory(); - if (topInventory != null && topInventory.getType() == InventoryType.BARREL) { - Block clickedBlock = Objects.requireNonNull(topInventory.getLocation()).getBlock(); - if (clickedBlock.getType() == Material.BARREL) { - BlockState blockState = clickedBlock.getState(); - - if (blockState instanceof Barrel) { - Barrel barrel = (Barrel) blockState; - if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - event.setCancelled(true); - //player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); - return; - } - } - } - } + player.sendMessage(ChatColor.RED + "You cannot double-click items into this postbox."); + event.setCancelled(true); + return; + } + } + + // Prevent item swapping using hotbar + if (event.getClick() == ClickType.NUMBER_KEY) { + ItemStack hotbarItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); + if (hotbarItem != null) { + player.sendMessage(ChatColor.RED + "You cannot use number keys to swap items in this postbox."); + event.setCancelled(true); + return; } } - Block clickedBlock = Objects.requireNonNull(event.getClickedInventory().getLocation()).getBlock(); - if (clickedBlock.getType() == Material.BARREL) { - BlockState blockState = clickedBlock.getState(); - - if (blockState instanceof Barrel) { - Barrel barrel = (Barrel) blockState; - - if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { - - String ownerName = ""; - - for (BlockFace blockFace : BlockFace.values()) { - Block relativeBlock = clickedBlock.getRelative(blockFace); - - if (relativeBlock.getType().name().toUpperCase().contains("SIGN")) { - Sign sign = (Sign) relativeBlock.getState(); - Location signLoc = relativeBlock.getLocation().subtract(blockFace.getDirection()); - - if (sign.getLine(1).equalsIgnoreCase(player.getName()) && signLoc.equals(clickedBlock.getLocation())) { - ownerName = sign.getLine(1); - break; - } - } - } - - boolean isNotOwner = !ownerName.equalsIgnoreCase(player.getName()); - - // Prevent non-owners who do not have OP from taking items or shift-clicking - if (!player.isOp() && isNotOwner && !player.hasPermission("shantek.postoffice.removeitems") && (event.getAction().name().contains("PICKUP") || event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY)) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); - return; - } - - // If player is not the owner and trying to take an item, cancel the event - if (isNotOwner && !player.hasPermission("shantek.postoffice.removeitems") && event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); - return; - } - - if (isNotOwner && !player.hasPermission("shantek.postoffice.removeitems") && !player.isOp()) { - // CHECK IF THE PLAYER DOESN'T HAVE PERMISSION TO USE THIS BARREL, RESTRICT NUMBER KEY CLICKING TO MOVE TO HOTBAR - if (event.getWhoClicked() instanceof Player && event.getClickedInventory() != null) { - ItemStack hotbarItem = event.getClick() == ClickType.NUMBER_KEY ? event.getWhoClicked().getInventory().getItem(event.getHotbarButton()) : null; - - if (hotbarItem != null) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); - return; - } - } - - // Prevent players from swapping items from a barrel while having another item in hand - if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); - return; - } - - if (event.getAction() == InventoryAction.HOTBAR_SWAP) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); - return; - } - - // Prevent the player from dropping items out of the postbox - if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.dropItemError)); - return; - } - } - - // Check if item is already in the barrel - ItemStack[] contents = inventory.getContents(); - for (ItemStack item : contents) { - if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { - // If the player is not the owner and trying to add to an existing stack, cancel the event - if (isNotOwner && !player.hasPermission("shantek.postoffice.removeitems") && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.cantStackItems)); - return; - } - break; - } - } + // Prevent swapping items from a barrel while having another item in hand + if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR || event.getAction() == InventoryAction.HOTBAR_SWAP) { + player.sendMessage(ChatColor.RED + "You cannot swap items with the cursor in this postbox."); + event.setCancelled(true); + return; + } + + // Prevent the player from dropping items out of the postbox + if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { + player.sendMessage(ChatColor.RED + "You cannot drop items out of this postbox."); + event.setCancelled(true); + return; + } + + // Check if the player is adding items to an existing stack in the barrel + ItemStack[] contents = inventory.getContents(); + for (ItemStack item : contents) { + if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { + // If the player is not the owner and trying to add to an existing stack, cancel the event + if (!isOwner && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { + player.sendMessage(ChatColor.RED + "You cannot stack items in this postbox."); + event.setCancelled(true); + return; } + break; } } } - -} \ No newline at end of file +} From 2b20a449ecb33080060b59f9d9522dc1121efa71 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 18:35:52 +0930 Subject: [PATCH 27/45] Cleaned up helper functions --- .../java/io/shantek/functions/Helpers.java | 489 +++++++++--------- 1 file changed, 240 insertions(+), 249 deletions(-) diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 3a9bce4..9936dd2 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -26,134 +26,11 @@ public Helpers(PostOffice postOffice) { loadBarrelsIntoCache(); // Load data from barrels.yml into the cache at startup } - // In-memory cache to store barrel data (key: block location, value: owner UUID) public Map barrelsCache; private FileConfiguration barrelsConfig = null; private File barrelsConfigFile = null; - //region Barrel Operations - - // Check if there's a barrel with the custom name nearby - public boolean hasBarrelNearby(Block block) { - // Check if the given block is a barrel with the custom name - if (block.getType() == Material.BARREL) { - Barrel barrel = (Barrel) block.getState(); - String barrelCustomName = barrel.getCustomName(); - - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - return true; - } - } - - // Check if any nearby block is a barrel with the custom name - for (BlockFace blockFace : BlockFace.values()) { - Block relativeBlock = block.getRelative(blockFace); - - if (relativeBlock.getType() == Material.BARREL) { - Barrel barrel = (Barrel) relativeBlock.getState(); - String barrelCustomName = barrel.getCustomName(); - - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - return true; - } - } - } - - return false; - } - - // Check if the block is a protected post box - public boolean isProtectedPostBox(Block block) { - if (block.getType() == Material.BARREL) { - Barrel barrel = (Barrel) block.getState(); - String barrelCustomName = barrel.getCustomName(); - return barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName); - } else if (Tag.SIGNS.isTagged(block.getType())) { - return isSignNextToProtectedBarrel(block); - } - return false; - } - - // Check if a sign is next to a protected barrel - public boolean isSignNextToProtectedBarrel(Block signBlock) { - BlockFace[] adjacentFaces = { - BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN - }; - - for (BlockFace face : adjacentFaces) { - Block adjacentBlock = signBlock.getRelative(face); - if (adjacentBlock.getType() == Material.BARREL) { - Barrel barrel = (Barrel) adjacentBlock.getState(); - String barrelCustomName = barrel.getCustomName(); - if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { - return true; - } - } - } - return false; - } - - //region Barrel Caching and Config Operations - - private void loadBarrelsIntoCache() { - barrelsCache.clear(); // Clear the cache before reloading - - FileConfiguration barrelsConfig = getBarrelsConfig(); - if (barrelsConfig.contains("barrels")) { - Set keys = barrelsConfig.getConfigurationSection("barrels").getKeys(false); - postOffice.getLogger().info("Loading barrels into cache. Found keys: " + keys); - - for (String key : keys) { - String path = "barrels." + key; - String ownerUUIDString = barrelsConfig.getString(path + ".owner"); - String state = barrelsConfig.getString(path + ".state", "unregistered"); // Default to "unregistered" - String signLocation = barrelsConfig.getString(path + ".sign"); - - UUID ownerUUID = null; - if (ownerUUIDString != null && !ownerUUIDString.equalsIgnoreCase("none")) { - try { - ownerUUID = UUID.fromString(ownerUUIDString); - } catch (IllegalArgumentException e) { - postOffice.getLogger().warning("Invalid UUID found for barrel at " + key); - continue; // Skip this barrel if UUID is invalid - } - } - - // Create a BarrelData object and store it in the cache - BarrelData barrelData = new BarrelData(ownerUUID, state, signLocation); - barrelsCache.put(key, barrelData); // Add to cache - - postOffice.getLogger().info("Added barrel to cache at location: " + key + ", Owner: " - + (ownerUUID != null ? ownerUUID : "none") + ", State: " + state + ", Sign: " + signLocation); - } - } else { - postOffice.getLogger().warning("No barrels found in barrels.yml during cache load."); - } - } - - public Block getSignFromConfig(Block barrelBlock) { - String barrelLocationString = getBlockLocationString(barrelBlock); // Convert block to location string - String path = "barrels." + barrelLocationString + ".sign"; // Use this location string in the config - - // Look up the sign location in the config - if (barrelsConfig.contains(path)) { - String signLocation = barrelsConfig.getString(path); - String[] parts = signLocation.split("_"); - - if (parts.length == 4) { - String worldName = parts[0]; - int x = Integer.parseInt(parts[1]); - int y = Integer.parseInt(parts[2]); - int z = Integer.parseInt(parts[3]); - - World world = Bukkit.getWorld(worldName); - if (world != null) { - return world.getBlockAt(x, y, z); // Return the block at the saved sign location - } - } - } - return null; // Sign not found in the config - } + //region Post box management // Helper method to get block location string public String getBlockLocationString(Block block) { @@ -174,12 +51,6 @@ public String getOwnerNameFromConfig(String barrelLocationString) { return "none"; // No owner } - // Get the state of the post box from the barrels.yml config - public String getStateFromConfig(String barrelLocationString) { - FileConfiguration barrelsConfig = getBarrelsConfig(); - return barrelsConfig.getString("barrels." + barrelLocationString + ".state", "unregistered"); // Default to "registered" - } - public boolean doesPlayerHavePostBox(UUID playerUUID) { FileConfiguration barrelsConfig = getBarrelsConfig(); @@ -188,6 +59,7 @@ public boolean doesPlayerHavePostBox(UUID playerUUID) { ConfigurationSection barrelsSection = barrelsConfig.getConfigurationSection("barrels"); // Loop through all barrels to check if any are owned by this player + assert barrelsSection != null; for (String barrelLocation : barrelsSection.getKeys(false)) { String ownerUUIDString = barrelsConfig.getString("barrels." + barrelLocation + ".owner"); if (ownerUUIDString != null && ownerUUIDString.equals(playerUUID.toString())) { @@ -202,7 +74,7 @@ public String getPlayerPostBoxLocation(UUID playerUUID) { FileConfiguration barrelsConfig = getBarrelsConfig(); // Loop through all barrels to find the one owned by the player - for (String barrelLocation : barrelsConfig.getConfigurationSection("barrels").getKeys(false)) { + for (String barrelLocation : Objects.requireNonNull(barrelsConfig.getConfigurationSection("barrels")).getKeys(false)) { String ownerUUIDString = barrelsConfig.getString("barrels." + barrelLocation + ".owner"); if (ownerUUIDString != null && ownerUUIDString.equals(playerUUID.toString())) { @@ -224,10 +96,46 @@ public String getPlayerPostBoxLocation(UUID playerUUID) { return "Unknown location"; // Fallback if no post box is found } + public int countNonNullItems(ItemStack[] items) { + int count = 0; + for (ItemStack item : items) { + if (item != null && item.getType() != Material.AIR) { + count += item.getAmount(); + } + } + return count; + } + + public OfflinePlayer getPlayer(UUID uuid) { + return Bukkit.getOfflinePlayer(uuid); + } + + public boolean isPostBoxOwner(Block block, Player player) { + UUID playerUUID = player.getUniqueId(); + return getOwnerUUID(block).equals(playerUUID); + + } + + public UUID getOwnerUUID(Block block) { + String blockLocationString = getBlockLocationString(block); + BarrelData barrelData = barrelsCache.get(blockLocationString); + return barrelData != null ? barrelData.getOwnerUUID() : null; + } + + // Method to get a player's name by UUID, checking both online and offline players + public String getPlayerName(UUID uuid) { + // Check if the player is online + Player onlinePlayer = Bukkit.getPlayer(uuid); + if (onlinePlayer != null) { + return onlinePlayer.getName(); + } + + // If the player is offline, use getOfflinePlayer + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + return offlinePlayer.getName(); // This may return null if the player's name is not available + } - //endregion - //region Retrieving Sign Information public Block getSignForBarrel(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); @@ -266,7 +174,6 @@ public Block getSignForBarrel(Block barrelBlock) { return null; // Sign not found or invalid format } - // Method to check if the sign is attached to a barrel public Block getAttachedBarrel(Block signBlock) { for (BlockFace face : BlockFace.values()) { Block attachedBlock = signBlock.getRelative(face); @@ -311,140 +218,69 @@ public Block getBarrelFromSign(Block signBlock) { return null; // No barrel found for this sign } - //endregion - - //region Plugin Configuration (YAML Management) - - // Load the barrels.yml configuration - public void reloadBarrelsConfig() { - if (barrelsConfigFile == null) { - barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); - } - barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); - - // Create the file if it doesn't exist - if (!barrelsConfigFile.exists()) { - postOffice.saveResource("barrels.yml", false); - } - - // Debugging to check if it's loading correctly - if (barrelsConfig.contains("barrels")) { - Set keys = barrelsConfig.getConfigurationSection("barrels").getKeys(false); - postOffice.getLogger().info("Keys in barrels.yml after reload: " + keys.toString()); - } else { - postOffice.getLogger().warning("No barrels found in barrels.yml during reload."); - } - } - - // Get the barrels.yml configuration - public FileConfiguration getBarrelsConfig() { - if (barrelsConfig == null) { - reloadBarrelsConfig(); - } - return barrelsConfig; - } + // Check if there's a barrel with the custom name nearby + public boolean hasBarrelNearby(Block block) { + // Check if the given block is a barrel with the custom name + if (block.getType() == Material.BARREL) { + Barrel barrel = (Barrel) block.getState(); + String barrelCustomName = barrel.getCustomName(); - // Save changes to barrels.yml - public void saveBarrelsConfig() { - if (barrelsConfig == null || barrelsConfigFile == null) { - return; - } - try { - barrelsConfig.save(barrelsConfigFile); - } catch (IOException e) { - postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + return true; + } } - } - //endregion + // Check if any nearby block is a barrel with the custom name + for (BlockFace blockFace : BlockFace.values()) { + Block relativeBlock = block.getRelative(blockFace); - //region Mail and Item Operations + if (relativeBlock.getType() == Material.BARREL) { + Barrel barrel = (Barrel) relativeBlock.getState(); + String barrelCustomName = barrel.getCustomName(); - public void saveMailFile() { - try { - if (postOffice.consoleLogs) { - postOffice.getLogger().info("The mail list has been updated."); + if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + return true; + } } - Files.write(postOffice.mailFile.toPath(), postOffice.playersWithMail); - } catch (IOException e) { - postOffice.getLogger().log(Level.SEVERE, "Error updating the mail file.", e); } - } - public int countNonNullItems(ItemStack[] items) { - int count = 0; - for (ItemStack item : items) { - if (item != null && item.getType() != Material.AIR) { - count += item.getAmount(); - } - } - return count; + return false; } - public void checkForDataFolder() { - if (!postOffice.getDataFolder().exists()) { - if (postOffice.getDataFolder().mkdir()) { - postOffice.getLogger().info("Data folder created successfully."); - } else { - postOffice.getLogger().warning("Error creating the data folder."); - } + // Check if the block is a protected post box + public boolean isProtectedPostBox(Block block) { + if (block.getType() == Material.BARREL) { + Barrel barrel = (Barrel) block.getState(); + String barrelCustomName = barrel.getCustomName(); + return barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName); + } else if (Tag.SIGNS.isTagged(block.getType())) { + return isSignNextToProtectedBarrel(block); } + return false; } - public OfflinePlayer getPlayer(UUID uuid) { - return Bukkit.getOfflinePlayer(uuid); - } - - public boolean isPostBoxOwner(Block block, Player player) { - UUID playerUUID = player.getUniqueId(); - return getOwnerUUID(block).equals(playerUUID); - - } - - public boolean isBarrelInConfig(Block block) { - String blockLocationString = getBlockLocationString(block); - return barrelsCache.containsKey(blockLocationString); - } + // Check if a sign is next to a protected barrel + public boolean isSignNextToProtectedBarrel(Block signBlock) { + BlockFace[] adjacentFaces = { + BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN + }; - public UUID getOwnerUUID(Block block) { - String blockLocationString = getBlockLocationString(block); - BarrelData barrelData = barrelsCache.get(blockLocationString); - return barrelData != null ? barrelData.getOwnerUUID() : null; - } - // Method to get a player's name by UUID, checking both online and offline players - public String getPlayerName(UUID uuid) { - // Check if the player is online - Player onlinePlayer = Bukkit.getPlayer(uuid); - if (onlinePlayer != null) { - return onlinePlayer.getName(); + for (BlockFace face : adjacentFaces) { + Block adjacentBlock = signBlock.getRelative(face); + if (adjacentBlock.getType() == Material.BARREL) { + Barrel barrel = (Barrel) adjacentBlock.getState(); + String barrelCustomName = barrel.getCustomName(); + if (barrelCustomName != null && barrelCustomName.equalsIgnoreCase(postOffice.customBarrelName)) { + return true; + } + } } - - // If the player is offline, use getOfflinePlayer - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); - return offlinePlayer.getName(); // This may return null if the player's name is not available + return false; } //endregion - public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { - String barrelLocationString = getBlockLocationString(barrelBlock); - String signLocationString = getBlockLocationString(signBlock); - - // Create the BarrelData object with correct sign location and state - BarrelData barrelData = new BarrelData(ownerUUID, signLocationString, state); - - // Add or update the barrel data in the cache - barrelsCache.put(barrelLocationString, barrelData); - - // Log for debugging purposes - postOffice.getLogger().info("Adding/Updating barrel at: " + barrelLocationString); - postOffice.getLogger().info("Sign location for barrel: " + signLocationString); - postOffice.getLogger().info("Post box state: " + state); - - // Optionally save the cache to disk immediately - saveCacheToFile(); - } - + //region Configuration loading/saving public void removeBarrelFromCache(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); @@ -485,6 +321,72 @@ public void removeBarrelFromCache(Block barrelBlock) { saveCacheToFile(); } + // Get the state of the post box from the barrels.yml config + public String getStateFromConfig(String barrelLocationString) { + FileConfiguration barrelsConfig = getBarrelsConfig(); + return barrelsConfig.getString("barrels." + barrelLocationString + ".state", "unregistered"); // Default to "registered" + } + + public boolean isBarrelInConfig(Block block) { + String blockLocationString = getBlockLocationString(block); + return barrelsCache.containsKey(blockLocationString); + } + + private void loadBarrelsIntoCache() { + barrelsCache.clear(); // Clear the cache before reloading + + FileConfiguration barrelsConfig = getBarrelsConfig(); + if (barrelsConfig.contains("barrels")) { + Set keys = Objects.requireNonNull(barrelsConfig.getConfigurationSection("barrels")).getKeys(false); + postOffice.getLogger().info("Loading barrels into cache. Found keys: " + keys); + + for (String key : keys) { + String path = "barrels." + key; + String ownerUUIDString = barrelsConfig.getString(path + ".owner"); + String state = barrelsConfig.getString(path + ".state", "unregistered"); // Default to "unregistered" + String signLocation = barrelsConfig.getString(path + ".sign"); + + UUID ownerUUID = null; + if (ownerUUIDString != null && !ownerUUIDString.equalsIgnoreCase("none")) { + try { + ownerUUID = UUID.fromString(ownerUUIDString); + } catch (IllegalArgumentException e) { + postOffice.getLogger().warning("Invalid UUID found for barrel at " + key); + continue; // Skip this barrel if UUID is invalid + } + } + + // Create a BarrelData object and store it in the cache + BarrelData barrelData = new BarrelData(ownerUUID, state, signLocation); + barrelsCache.put(key, barrelData); // Add to cache + + postOffice.getLogger().info("Added barrel to cache at location: " + key + ", Owner: " + + (ownerUUID != null ? ownerUUID : "none") + ", State: " + state + ", Sign: " + signLocation); + } + } else { + postOffice.getLogger().warning("No barrels found in barrels.yml during cache load."); + } + } + + public void addOrUpdateBarrelInCache(Block barrelBlock, Block signBlock, UUID ownerUUID, String state) { + String barrelLocationString = getBlockLocationString(barrelBlock); + String signLocationString = getBlockLocationString(signBlock); + + // Create the BarrelData object with correct sign location and state + BarrelData barrelData = new BarrelData(ownerUUID, signLocationString, state); + + // Add or update the barrel data in the cache + barrelsCache.put(barrelLocationString, barrelData); + + // Log for debugging purposes + postOffice.getLogger().info("Adding/Updating barrel at: " + barrelLocationString); + postOffice.getLogger().info("Sign location for barrel: " + signLocationString); + postOffice.getLogger().info("Post box state: " + state); + + // Optionally save the cache to disk immediately + saveCacheToFile(); + } + public void saveCacheToFile() { FileConfiguration barrelsConfig = getBarrelsConfig(); @@ -515,4 +417,93 @@ public void saveCacheToFile() { saveBarrelsConfig(); } + public void checkForDataFolder() { + if (!postOffice.getDataFolder().exists()) { + if (postOffice.getDataFolder().mkdir()) { + postOffice.getLogger().info("Data folder created successfully."); + } else { + postOffice.getLogger().warning("Error creating the data folder."); + } + } + } + + public void saveMailFile() { + try { + if (postOffice.consoleLogs) { + postOffice.getLogger().info("The mail list has been updated."); + } + Files.write(postOffice.mailFile.toPath(), postOffice.playersWithMail); + } catch (IOException e) { + postOffice.getLogger().log(Level.SEVERE, "Error updating the mail file.", e); + } + } + + // Load the barrels.yml configuration + public void reloadBarrelsConfig() { + if (barrelsConfigFile == null) { + barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); + } + barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); + + // Create the file if it doesn't exist + if (!barrelsConfigFile.exists()) { + postOffice.saveResource("barrels.yml", false); + } + + // Debugging to check if it's loading correctly + if (barrelsConfig.contains("barrels")) { + Set keys = Objects.requireNonNull(barrelsConfig.getConfigurationSection("barrels")).getKeys(false); + postOffice.getLogger().info("Keys in barrels.yml after reload: " + keys.toString()); + } else { + postOffice.getLogger().warning("No barrels found in barrels.yml during reload."); + } + } + + // Get the barrels.yml configuration + public FileConfiguration getBarrelsConfig() { + if (barrelsConfig == null) { + reloadBarrelsConfig(); + } + return barrelsConfig; + } + + // Save changes to barrels.yml + public void saveBarrelsConfig() { + if (barrelsConfig == null || barrelsConfigFile == null) { + return; + } + try { + barrelsConfig.save(barrelsConfigFile); + } catch (IOException e) { + postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + } + } + + public Block getSignFromConfig(Block barrelBlock) { + String barrelLocationString = getBlockLocationString(barrelBlock); // Convert block to location string + String path = "barrels." + barrelLocationString + ".sign"; // Use this location string in the config + + // Look up the sign location in the config + if (barrelsConfig.contains(path)) { + String signLocation = barrelsConfig.getString(path); + assert signLocation != null; + String[] parts = signLocation.split("_"); + + if (parts.length == 4) { + String worldName = parts[0]; + int x = Integer.parseInt(parts[1]); + int y = Integer.parseInt(parts[2]); + int z = Integer.parseInt(parts[3]); + + World world = Bukkit.getWorld(worldName); + if (world != null) { + return world.getBlockAt(x, y, z); // Return the block at the saved sign location + } + } + } + return null; // Sign not found in the config + } + + //endregion + } From b5f633ed068e35132030d7bffa49c879f48bb174 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 18:36:24 +0930 Subject: [PATCH 28/45] Project cleanup --- src/main/java/io/shantek/PostOffice.java | 16 ++---------- .../java/io/shantek/functions/Commands.java | 25 ++++++++----------- .../io/shantek/functions/UpdateChecker.java | 2 +- 3 files changed, 14 insertions(+), 29 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 82879eb..3867e35 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -44,14 +44,14 @@ public void onEnable() { helpers = new Helpers(this); TabCompleter tabCompleter = new TabCompleter(this); - getCommand("postoffice").setTabCompleter(new TabCompleter(this)); + Objects.requireNonNull(getCommand("postoffice")).setTabCompleter(new TabCompleter(this)); // Check for a data folder, create it if needed helpers.checkForDataFolder(); this.mailFile = new File(getDataFolder(), "hasmail.txt"); - getCommand("postoffice").setExecutor(new Commands(this)); + Objects.requireNonNull(getCommand("postoffice")).setExecutor(new Commands(this)); // Create an instance of UpdateChecker this.updateChecker = new UpdateChecker(); @@ -90,17 +90,6 @@ public void onEnable() { } // Register event listeners registerEventListeners(); - - - // Delete old mail file - remove in a future update - // Now using a new file that stores UUIDs instead - File mailFile = new File("mail.txt"); - if (mailFile.exists()) { - // Attempt to delete the file - if (mailFile.delete()) { - System.out.println("Deleted old mail file."); - } - } } public void registerEventListeners() { @@ -115,7 +104,6 @@ public static PostOffice getInstance() { if (instance == null) { instance = new PostOffice(); } - return instance; } diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index d7686bb..61a4755 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -157,8 +157,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } // Ensure the sign is attached to a barrel - Block signBlock = targetBlock; - Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); return true; @@ -186,10 +185,10 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Register the barrel and sign in the plugin config UUID barrelOwnerUUID = null; // No owner yet - postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, barrelOwnerUUID, "registered"); + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, targetBlock, barrelOwnerUUID, "registered"); // Update the sign with "Unclaimed" on the second line in red text - Sign sign = (Sign) signBlock.getState(); + Sign sign = (Sign) targetBlock.getState(); sign.setLine(1, ChatColor.RED + "Unclaimed"); sign.update(); // Make sure to update the sign to apply the changes @@ -220,8 +219,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } // Ensure the sign is attached to a barrel - Block signBlock = targetBlock; - Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); return true; @@ -263,11 +261,11 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } // Claim the post box for the target player and update the state to 'claimed' - postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, targetPlayerUUID, "claimed"); + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, targetBlock, targetPlayerUUID, "claimed"); // Update the sign to display the player's name on the second line - if (signBlock != null && signBlock.getState() instanceof Sign) { - Sign sign = (Sign) signBlock.getState(); + if (targetBlock != null && targetBlock.getState() instanceof Sign) { + Sign sign = (Sign) targetBlock.getState(); sign.setLine(1, targetPlayer.getName()); // Set the player's name on the 2nd line sign.update(); } @@ -292,8 +290,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } // Ensure the sign is attached to a barrel - Block signBlock = targetBlock; - Block attachedBarrel = postOffice.helpers.getAttachedBarrel(signBlock); + Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); return true; @@ -324,12 +321,12 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } // Claim the post box for the player and update the state to 'claimed' - postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, signBlock, playerUUID, "claimed"); + postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, targetBlock, playerUUID, "claimed"); player.sendMessage(ChatColor.GREEN + "You have successfully claimed this post box."); // Update the sign to display the player's name on the second line - if (signBlock != null && signBlock.getState() instanceof Sign) { - Sign sign = (Sign) signBlock.getState(); + if (targetBlock != null && targetBlock.getState() instanceof Sign) { + Sign sign = (Sign) targetBlock.getState(); sign.setLine(1, player.getName()); // Set the player's name on the 2nd line sign.update(); } diff --git a/src/main/java/io/shantek/functions/UpdateChecker.java b/src/main/java/io/shantek/functions/UpdateChecker.java index 8d0e3b8..012128d 100644 --- a/src/main/java/io/shantek/functions/UpdateChecker.java +++ b/src/main/java/io/shantek/functions/UpdateChecker.java @@ -11,7 +11,7 @@ import java.util.logging.Level; public class UpdateChecker { - public String currentVersion = null; + public static String remoteVersion = null; public static void checkForUpdatesAsync(String currentVersion, Plugin plugin) { CompletableFuture.runAsync(() -> checkForUpdates(currentVersion, plugin)); From 349003255609650cc685e45615f683f2ebbdac64 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 20:58:53 +0930 Subject: [PATCH 29/45] Remove post box from config when it gets destroyed --- .../shantek/listeners/BarrelProtection.java | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index 8dbdf2a..335f6fa 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -3,6 +3,7 @@ import io.shantek.PostOffice; import org.bukkit.ChatColor; import org.bukkit.Material; +import org.bukkit.Tag; import org.bukkit.block.*; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; @@ -62,7 +63,33 @@ public void onBlockBreak(BlockBreakEvent event) { // Check if the broken block is a protected post box (either a barrel or a sign) if (postOffice.helpers.isProtectedPostBox(brokenBlock)) { - if (!player.isOp() && !player.hasPermission("shantek.postoffice.break")) { + if (player.isOp() || player.hasPermission("shantek.postoffice.break")) { + Block barrelBlock = null; + + // Check if the player is breaking a sign + if (Tag.SIGNS.isTagged(brokenBlock.getType())) { + // Retrieve the attached barrel if the broken block is a sign + barrelBlock = postOffice.helpers.getAttachedBarrel(brokenBlock); + } else if (brokenBlock.getType() == Material.BARREL) { + // If breaking a barrel directly, set it as the barrelBlock + barrelBlock = brokenBlock; + } + + // Ensure barrelBlock is valid before proceeding + if (barrelBlock == null) { + player.sendMessage(ChatColor.RED + "This isn't a registered post box."); + return; + } + + // Check if the barrel exists in the config (registered post box) + if (postOffice.helpers.isBarrelInConfig(barrelBlock)) { + // Call the helper to remove the barrel from the cache and config + postOffice.helpers.removeBarrelFromCache(barrelBlock); + player.sendMessage(ChatColor.GREEN + "Post box removed from the config."); + } + + } else { + // Prevent the player from breaking the post box if they don't have permission player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); event.setCancelled(true); } @@ -70,6 +97,7 @@ public void onBlockBreak(BlockBreakEvent event) { } + @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (!postOffice.postBoxProtection) { From ca9a2c99b19448635525f64cda9d0bf0ba5a25ca Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 21:02:42 +0930 Subject: [PATCH 30/45] Added additional debugging messaged --- src/main/java/io/shantek/listeners/InventoryClose.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 8771bf7..b6ebcac 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -40,8 +40,12 @@ public void onInventoryClose(InventoryCloseEvent event) { if (boxOwnerUUID == null) { player.sendMessage(ChatColor.RED + "This post box is unclaimed."); } else { - OfflinePlayer boxOwner = postOffice.helpers.getPlayer(boxOwnerUUID); - player.sendMessage("Closing valid post box. Owner: " + boxOwner.getName()); + + if (postOffice.consoleLogs) { + OfflinePlayer boxOwner = postOffice.helpers.getPlayer(boxOwnerUUID); + plugin.getLogger().info("Closing valid post box. Owner: " + boxOwner.getName()); + } + } // Check if the player owns the post box From 17d1b9c9ee15638fbe9f3ee8d5c8d40f4516cc45 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 21:08:26 +0930 Subject: [PATCH 31/45] Fix language colour codes --- .../io/shantek/listeners/InventoryClick.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index 94804e1..4417c97 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -62,10 +62,6 @@ public void onInventoryClick(InventoryClickEvent event) { // Log the owner and the player interacting UUID ownerUUID = barrelData.getOwnerUUID(); - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Owner of the barrel: " + (ownerUUID != null ? ownerUUID.toString() : "None")); - postOffice.getLogger().info("Player interacting: " + player.getUniqueId()); - } // Determine if the player is the owner or has permission boolean isOwner = ownerUUID != null && ownerUUID.equals(player.getUniqueId()); @@ -73,8 +69,7 @@ public void onInventoryClick(InventoryClickEvent event) { // Log the result of the ownership and permission checks if (postOffice.consoleLogs) { - postOffice.getLogger().info("Is owner: " + isOwner); - postOffice.getLogger().info("Has permission to remove items: " + hasPermissionToRemove); + postOffice.getLogger().info("Barrel owner: " + isOwner + ". Remove permission: " + hasPermissionToRemove); } // Prevent non-owners without permission from interacting with the post box @@ -82,7 +77,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (postOffice.consoleLogs) { postOffice.getLogger().info("Player " + player.getName() + " tried to interact without permission."); } - player.sendMessage(ChatColor.RED + postOffice.language.removeItemError); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); event.setCancelled(true); return; } @@ -90,7 +85,7 @@ public void onInventoryClick(InventoryClickEvent event) { // Prevent double-clicking items in player's own inventory to remove items if (event.getClick() == ClickType.DOUBLE_CLICK) { if (clickedInventory == player.getInventory() || clickedInventory.getType() == InventoryType.PLAYER) { - player.sendMessage(ChatColor.RED + "You cannot double-click items into this postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.cantStackItems)); event.setCancelled(true); return; } @@ -100,7 +95,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (event.getClick() == ClickType.NUMBER_KEY) { ItemStack hotbarItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); if (hotbarItem != null) { - player.sendMessage(ChatColor.RED + "You cannot use number keys to swap items in this postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); event.setCancelled(true); return; } @@ -108,14 +103,14 @@ public void onInventoryClick(InventoryClickEvent event) { // Prevent swapping items from a barrel while having another item in hand if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR || event.getAction() == InventoryAction.HOTBAR_SWAP) { - player.sendMessage(ChatColor.RED + "You cannot swap items with the cursor in this postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); event.setCancelled(true); return; } // Prevent the player from dropping items out of the postbox if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { - player.sendMessage(ChatColor.RED + "You cannot drop items out of this postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.dropItemError)); event.setCancelled(true); return; } @@ -126,7 +121,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { // If the player is not the owner and trying to add to an existing stack, cancel the event if (!isOwner && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { - player.sendMessage(ChatColor.RED + "You cannot stack items in this postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.cantStackItems)); event.setCancelled(true); return; } From 0183ba807874b4fd00eaeba4b0a2e25d99babab7 Mon Sep 17 00:00:00 2001 From: Kris Date: Thu, 19 Sep 2024 22:05:53 +0930 Subject: [PATCH 32/45] Updated language config --- .../java/io/shantek/functions/Commands.java | 36 +++++++++--------- .../java/io/shantek/functions/Language.java | 17 ++++++++- .../io/shantek/functions/PluginConfig.java | 32 +++++++++++----- .../shantek/listeners/BarrelProtection.java | 6 +-- .../io/shantek/listeners/InventoryClick.java | 6 +-- .../io/shantek/listeners/InventoryClose.java | 2 +- .../io/shantek/listeners/InventoryOpen.java | 2 +- src/main/resources/config.yml | 37 ++++++++++++++++++- src/main/resources/config/config.yml | 5 ++- 9 files changed, 102 insertions(+), 41 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 61a4755..efc47b8 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -48,13 +48,13 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String // Ensure we have a valid barrel block if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "You must be looking at a barrel or a sign attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.lookAtPostBox)); return true; } // Check if the barrel exists in the config (registered post box) if (!postOffice.helpers.isBarrelInConfig(barrelBlock)) { - player.sendMessage(ChatColor.RED + "This isn't a registered post box."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return true; } @@ -70,11 +70,11 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String // Call the helper to remove the barrel from the cache and config postOffice.helpers.removeBarrelFromCache(barrelBlock); - player.sendMessage(ChatColor.GREEN + "Post box removed successfully."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.postBoxRemoved)); return true; } else { - player.sendMessage(ChatColor.RED + "You don't have permission to use this command."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); return true; } } else { @@ -112,7 +112,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // If there's no attached barrel or it's not a valid post box, show unregistered if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "This isn't a valid post box."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return true; } @@ -123,7 +123,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Ensure we have a valid barrel block if (barrelBlock == null || barrelBlock.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "This isn't a valid post box."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return true; } @@ -152,14 +152,14 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Ensure they are looking at a sign Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { - player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.lookAtPostBox)); return true; } // Ensure the sign is attached to a barrel Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.signOnBarrel)); return true; } @@ -194,7 +194,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { postOffice.helpers.saveCacheToFile(); // Save the cache to disk - player.sendMessage(ChatColor.GREEN + "Post box registered successfully."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.successfulRegistration)); return true; } @@ -214,21 +214,21 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { Player player = (Player) sender; Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { - player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.lookAtPostBox)); return true; } // Ensure the sign is attached to a barrel Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.signOnBarrel)); return true; } // Check if the sign exists in the config (if the post box has been registered) Block savedSign = postOffice.helpers.getSignForBarrel(attachedBarrel); // Retrieve saved sign if (savedSign == null) { - player.sendMessage(ChatColor.RED + "This post box has not been registered yet."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.signOnBarrel)); return true; } @@ -256,7 +256,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Check if the post box is already claimed String currentOwner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); if (currentOwner != null && !currentOwner.equals("none")) { - player.sendMessage(ChatColor.RED + "This post box is already claimed."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.alreadyClaimed)); return true; } @@ -285,21 +285,21 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Ensure they are looking at a sign Block targetBlock = player.getTargetBlock(null, 10); // Max distance 10 blocks if (targetBlock == null || !(targetBlock.getState() instanceof Sign)) { - player.sendMessage(ChatColor.RED + "You must be looking at a sign attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.lookAtPostBox)); return true; } // Ensure the sign is attached to a barrel Block attachedBarrel = postOffice.helpers.getAttachedBarrel(targetBlock); if (attachedBarrel == null || attachedBarrel.getType() != Material.BARREL) { - player.sendMessage(ChatColor.RED + "The sign must be attached to a barrel."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.signOnBarrel)); return true; } // Check if the sign exists in the config (if the post box has been registered) Block savedSign = postOffice.helpers.getSignForBarrel(attachedBarrel); // Retrieve saved sign if (savedSign == null) { - player.sendMessage(ChatColor.RED + "This post box has not been registered yet."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return true; } @@ -309,7 +309,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Check if the post box is already claimed String currentOwner = postOffice.helpers.getOwnerNameFromConfig(barrelLocation); if (currentOwner != null && !currentOwner.equals("none")) { - player.sendMessage(ChatColor.RED + "This post box is already claimed."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.alreadyClaimed)); return true; } @@ -322,7 +322,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Claim the post box for the player and update the state to 'claimed' postOffice.helpers.addOrUpdateBarrelInCache(attachedBarrel, targetBlock, playerUUID, "claimed"); - player.sendMessage(ChatColor.GREEN + "You have successfully claimed this post box."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.successfullyClaimed)); // Update the sign to display the player's name on the second line if (targetBlock != null && targetBlock.getState() instanceof Sign) { diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index a97f6b4..df9bfb4 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -9,18 +9,31 @@ public Language(PostOffice postOffice) { this.postOffice = postOffice; } + public String lookAtPostBox = "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel."; + public String notRegistered = "&a[Post Office] &4This isn't a registered post office box."; + public String postBoxRemoved = "&a[Post Office] &aPost box removed successfully."; + public String signOnBarrel = "&a[Post Office] &4The sign must be attached to a barrel."; + public String successfulRegistration = "&a[Post Office] &aPost box registered successfully."; + public String alreadyClaimed = "&a[Post Office] &4This post box has already been claimed."; + public String successfullyClaimed = "&a[Post Office] &aYou have successfully registered this post box."; + public String modifySign = "&a[Post Office] &4You cannot modify a post box sign."; + public String removeFromConfig = "&a[Post Office] &aPost box successfully removed from the config."; + public String unclaimedPostbox = "&a[Post Office] &4This post box is unclaimed."; + public String userBanned = "&a[Post Office] &4You aren't able to interact with this post box."; + + public String sentMessage = "&a[Post Office] &aMail sent to %receiver%."; public String receivedMessage = "&a[Post Office] &eYou received mail from %sender%!"; public String gotMailMessage = "&a[Post Office] &fYou got mail!"; - public String cantStackItems = "&a[Post Office] &4You don't have permission to do that."; + public String noPermission = "&a[Post Office] &4You don't have permission to do that."; public String removeItemError = "&a[Post Office] &4You don't have permission to remove items."; - public String offHandError = "&a[Post Office] &4No offhand usage while in a Post Box!"; public String hotBarError = "&a[Post Office] &4No hot bar usage while in a Post Box!"; public String breakError = "&a[Post Office] &4You can't break a Post Box."; public String createError = "&a[Post Office] &4You can't create a Post Box."; public String postboxCreated = "&a[Post Office] &4 Box successfully created for %username%"; public String pluginUpToDate = "Your plugin is up-to-date."; public String dropItemError = "&a[Post Office] &4 You can't drop items while in a postbox."; + public UpdateChecker updateChecker; public PluginConfig pluginConfig; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 5c9c47f..b038dd3 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -55,9 +55,8 @@ public void reloadConfigFile() { updateConfigWithMissingKeyValues(config, missingKeyValues); postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); - postOffice.language.cantStackItems = getString(config, "cant-stack-items", postOffice.language.cantStackItems); + postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); postOffice.language.removeItemError = getString(config, "remove-item-error", postOffice.language.removeItemError); - postOffice.language.offHandError = getString(config, "offhand-error", postOffice.language.offHandError); postOffice.language.hotBarError = getString(config, "hotbar-error", postOffice.language.hotBarError); postOffice.language.sentMessage = getString(config, "sent-message", postOffice.language.sentMessage); postOffice.language.receivedMessage = getString(config, "received-message", postOffice.language.receivedMessage); @@ -66,12 +65,25 @@ public void reloadConfigFile() { postOffice.language.breakError = getString(config, "break-error", postOffice.language.breakError); postOffice.language.postboxCreated = getString(config, "postbox-created", postOffice.language.postboxCreated); postOffice.language.pluginUpToDate = getString(config, "plugin-up-to-date", postOffice.language.pluginUpToDate); + postOffice.language.dropItemError = getString(config, "drop-item-error", postOffice.language.pluginUpToDate); postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); postOffice.consoleLogs = getBoolean(config, "console-logs", true); postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); postOffice.signNotification = getBoolean(config, "sign-notification", true); + + postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); + postOffice.language.notRegistered = getString(config, "not-registered", postOffice.language.notRegistered); + postOffice.language.postBoxRemoved = getString(config, "post-box-removed", postOffice.language.postBoxRemoved); + postOffice.language.signOnBarrel = getString(config, "sign-on-barrel", postOffice.language.signOnBarrel); + postOffice.language.successfulRegistration = getString(config, "successful-registration", postOffice.language.successfulRegistration); + postOffice.language.alreadyClaimed = getString(config, "already-claimed", postOffice.language.alreadyClaimed); + postOffice.language.successfullyClaimed = getString(config, "successfully-claimed", postOffice.language.successfullyClaimed); + postOffice.language.modifySign = getString(config, "modify-sign", postOffice.language.modifySign); + postOffice.language.removeFromConfig = getString(config, "remove-from-config", postOffice.language.removeFromConfig); + postOffice.language.unclaimedPostbox = getString(config, "unclaimed-postbox", postOffice.language.unclaimedPostbox); + postOffice.language.userBanned = getString(config, "user-banned", postOffice.language.userBanned); } } catch (Exception e) { @@ -84,9 +96,11 @@ private boolean checkForMissingKeys(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "custom-barrel-name", "cant-stack-items", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "custom-barrel-name", "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification"); + "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", + "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned"); // Check for missing keys for (String key : keysToCheck) { @@ -103,9 +117,12 @@ private Map saveMissingKeyValues(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "custom-barrel-name", "cant-stack-items", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "custom-barrel-name", "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification"); + "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", + "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned"); + // Save existing values of missing keys for (String key : keysToCheck) { @@ -247,7 +264,4 @@ public void saveBarrelsConfig() { postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); } } - - - } diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index 335f6fa..9461fdd 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -45,7 +45,7 @@ public void onSignChange(SignChangeEvent event) { if (attachedBarrel != null && attachedBarrel.getType() == Material.BARREL) { if (postOffice.helpers.isBarrelInConfig(attachedBarrel)) { // Cancel the sign change event if the barrel is in the config (protected post box) - player.sendMessage(ChatColor.RED + "You cannot modify a post box sign."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.modifySign)); event.setCancelled(true); } } @@ -77,7 +77,7 @@ public void onBlockBreak(BlockBreakEvent event) { // Ensure barrelBlock is valid before proceeding if (barrelBlock == null) { - player.sendMessage(ChatColor.RED + "This isn't a registered post box."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return; } @@ -85,7 +85,7 @@ public void onBlockBreak(BlockBreakEvent event) { if (postOffice.helpers.isBarrelInConfig(barrelBlock)) { // Call the helper to remove the barrel from the cache and config postOffice.helpers.removeBarrelFromCache(barrelBlock); - player.sendMessage(ChatColor.GREEN + "Post box removed from the config."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeFromConfig)); } } else { diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index 4417c97..db1ee56 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -56,7 +56,7 @@ public void onInventoryClick(InventoryClickEvent event) { // Check if barrel data is null (not registered) if (barrelData == null) { - player.sendMessage(ChatColor.RED + "This is not a registered postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); return; } @@ -85,7 +85,7 @@ public void onInventoryClick(InventoryClickEvent event) { // Prevent double-clicking items in player's own inventory to remove items if (event.getClick() == ClickType.DOUBLE_CLICK) { if (clickedInventory == player.getInventory() || clickedInventory.getType() == InventoryType.PLAYER) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.cantStackItems)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); event.setCancelled(true); return; } @@ -121,7 +121,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { // If the player is not the owner and trying to add to an existing stack, cancel the event if (!isOwner && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.cantStackItems)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); event.setCancelled(true); return; } diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index b6ebcac..45d639b 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -38,7 +38,7 @@ public void onInventoryClose(InventoryCloseEvent event) { UUID boxOwnerUUID = postOffice.helpers.getOwnerUUID(clickedBlock); if (boxOwnerUUID == null) { - player.sendMessage(ChatColor.RED + "This post box is unclaimed."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.unclaimedPostbox)); } else { if (postOffice.consoleLogs) { diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index ab49c7a..818dadf 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -44,7 +44,7 @@ public void onInventoryOpen(InventoryOpenEvent event) { // They have permission to use the post office system. Let them open the post box postOffice.previousItemCount = postOffice.helpers.countNonNullItems(inventory.getContents()); } else { - player.sendMessage(ChatColor.RED + "You don't have permission to interact with post boxes."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.userBanned)); event.setCancelled(true); } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index a9abd58..e33ee26 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -19,8 +19,9 @@ got-mail-message: "&a[Post Office] &fYou got mail!" # isn't lost in any other messages they receive during connection got-mail-delay: true -# Error shown when the player attempts to stack items in a post box -cant-stack-items: "&a[Post Office] &4You don't have permission to do that." +# Generic no permission error message when a player is attempting to do an action +# that they shouldn't have permission to do +no-permission: "&a[Post Office] &4You don't have permission to do that." # Error shown when a player attempts to remove items without permission remove-item-error: "&a[Post Office] &4You don't have permission to remove items." @@ -37,6 +38,38 @@ create-error: "&a[Post Office] &4You can't create a Post Box." # Error shown when a player tries to break a Post Box break-error: "&a[Post Office] &4You can't break this Post Box." +# Error when running a command and not looking at a configured post box +look-at-post-box: "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel." + +# Error when the post box isn't registered in the config +not-registered: "&a[Post Office] &4This isn't a registered post office box." + +# Message shown when a post box is successfully removed with the remove command +post-box-removed: "&a[Post Office] &aPost box removed successfully." + +# Error when interacting with a sign that isn't attached to the barrel correctly +sign-on-barrel: "&a[Post Office] &4The sign must be attached to a barrel." + +# Message when a post box has been successfully registered in the config +successful-registration: "&a[Post Office] &aPost box registered successfully." + +# Message shown when a post box has already been claimed to another player +already-claimed: "&a[Post Office] &4This post box has already been claimed." + +# Message shown when a post box is successfully claimed with the claim command +successfully-claimed: "&a[Post Office] &aYou have successfully registered this post box." + +# Error when a player is trying to modify a post box sign without the correct permission +modify-sign: "&a[Post Office] &4You cannot modify a post box sign." + +# Message when a post box +remove-from-config: "&a[Post Office] &aPost box successfully removed from the config." +unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." +user-banned: "&a[Post Office] &4You aren't able to interact with this post box." + + + + # Confirmation message shown when a post box has been created # You can use %username% to show the players name postbox-created: "&a[Post Office] &2 Box successfully created for %username%" diff --git a/src/main/resources/config/config.yml b/src/main/resources/config/config.yml index a9abd58..ddcdf32 100644 --- a/src/main/resources/config/config.yml +++ b/src/main/resources/config/config.yml @@ -19,8 +19,9 @@ got-mail-message: "&a[Post Office] &fYou got mail!" # isn't lost in any other messages they receive during connection got-mail-delay: true -# Error shown when the player attempts to stack items in a post box -cant-stack-items: "&a[Post Office] &4You don't have permission to do that." +# Generic no permission error message when a player is attempting to do an action +# that they shouldn't have permission to do +no-permission: "&a[Post Office] &4You don't have permission to do that." # Error shown when a player attempts to remove items without permission remove-item-error: "&a[Post Office] &4You don't have permission to remove items." From 62050e1024558921616d969e3e28dc25437e65f1 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 07:20:36 +0930 Subject: [PATCH 33/45] Updated config with additional language keys. This will be moved to a language file soon. --- src/main/resources/config.yml | 23 ++++++++++------ src/main/resources/config/config.yml | 39 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index e33ee26..1d44ea3 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -38,16 +38,19 @@ create-error: "&a[Post Office] &4You can't create a Post Box." # Error shown when a player tries to break a Post Box break-error: "&a[Post Office] &4You can't break this Post Box." -# Error when running a command and not looking at a configured post box +# Error when running a command and not looking at a configured post box. +# This is a generic error, shown in a lot of different scenarios. look-at-post-box: "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel." -# Error when the post box isn't registered in the config +# Error when the post box isn't registered in the config. Used in instanced like when trying to remove +# a post box, looking up postbox info etc. not-registered: "&a[Post Office] &4This isn't a registered post office box." # Message shown when a post box is successfully removed with the remove command post-box-removed: "&a[Post Office] &aPost box removed successfully." -# Error when interacting with a sign that isn't attached to the barrel correctly +# Warning shown in cases where we haven't found a barrel/sign combo +# resulting in an invalid setup sign-on-barrel: "&a[Post Office] &4The sign must be attached to a barrel." # Message when a post box has been successfully registered in the config @@ -57,18 +60,22 @@ successful-registration: "&a[Post Office] &aPost box registered successfully." already-claimed: "&a[Post Office] &4This post box has already been claimed." # Message shown when a post box is successfully claimed with the claim command -successfully-claimed: "&a[Post Office] &aYou have successfully registered this post box." +successfully-claimed: "&a[Post Office] &aYou have successfully claimed this post box." # Error when a player is trying to modify a post box sign without the correct permission modify-sign: "&a[Post Office] &4You cannot modify a post box sign." -# Message when a post box +# Message when a post box has been broken but was still in the config. The plugin will +# automatically remove it from the config. remove-from-config: "&a[Post Office] &aPost box successfully removed from the config." -unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." -user-banned: "&a[Post Office] &4You aren't able to interact with this post box." - +# Warning shown when closing an unclaimed post box. Good as a reminder for an admin/mod +# that they may be leaving items in the wrong post box +unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." +# Error shown to a user when they have been banned from using the post office plugin. +# They aren't able to open a post box and will see this error. +user-banned: "&a[Post Office] &4You aren't able to interact with this post box." # Confirmation message shown when a post box has been created # You can use %username% to show the players name diff --git a/src/main/resources/config/config.yml b/src/main/resources/config/config.yml index ddcdf32..1d44ea3 100644 --- a/src/main/resources/config/config.yml +++ b/src/main/resources/config/config.yml @@ -38,6 +38,45 @@ create-error: "&a[Post Office] &4You can't create a Post Box." # Error shown when a player tries to break a Post Box break-error: "&a[Post Office] &4You can't break this Post Box." +# Error when running a command and not looking at a configured post box. +# This is a generic error, shown in a lot of different scenarios. +look-at-post-box: "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel." + +# Error when the post box isn't registered in the config. Used in instanced like when trying to remove +# a post box, looking up postbox info etc. +not-registered: "&a[Post Office] &4This isn't a registered post office box." + +# Message shown when a post box is successfully removed with the remove command +post-box-removed: "&a[Post Office] &aPost box removed successfully." + +# Warning shown in cases where we haven't found a barrel/sign combo +# resulting in an invalid setup +sign-on-barrel: "&a[Post Office] &4The sign must be attached to a barrel." + +# Message when a post box has been successfully registered in the config +successful-registration: "&a[Post Office] &aPost box registered successfully." + +# Message shown when a post box has already been claimed to another player +already-claimed: "&a[Post Office] &4This post box has already been claimed." + +# Message shown when a post box is successfully claimed with the claim command +successfully-claimed: "&a[Post Office] &aYou have successfully claimed this post box." + +# Error when a player is trying to modify a post box sign without the correct permission +modify-sign: "&a[Post Office] &4You cannot modify a post box sign." + +# Message when a post box has been broken but was still in the config. The plugin will +# automatically remove it from the config. +remove-from-config: "&a[Post Office] &aPost box successfully removed from the config." + +# Warning shown when closing an unclaimed post box. Good as a reminder for an admin/mod +# that they may be leaving items in the wrong post box +unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." + +# Error shown to a user when they have been banned from using the post office plugin. +# They aren't able to open a post box and will see this error. +user-banned: "&a[Post Office] &4You aren't able to interact with this post box." + # Confirmation message shown when a post box has been created # You can use %username% to show the players name postbox-created: "&a[Post Office] &2 Box successfully created for %username%" From 6b7943faf226950e11eef704be19446e4c61ead5 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 12:03:08 +0930 Subject: [PATCH 34/45] Adding extra language keys to config --- src/main/java/io/shantek/functions/Commands.java | 4 ++-- src/main/java/io/shantek/functions/Language.java | 2 ++ src/main/java/io/shantek/functions/PluginConfig.java | 6 ++++-- src/main/resources/config.yml | 6 ++++++ src/main/resources/config/config.yml | 6 ++++++ 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index efc47b8..2f2eee0 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -138,7 +138,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { } else if (state != null && state.equals("registered")) { player.sendMessage(ChatColor.GREEN + "This post box is currently registered but not claimed."); } else { - player.sendMessage(ChatColor.RED + "This isn't a valid postbox."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.invalidPostbox)); } return true; @@ -174,7 +174,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { return true; } if (currentState != null && currentState.equals("registered")) { - player.sendMessage(ChatColor.RED + "This post box is already registered."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.alreadyRegistered)); return true; } diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index df9bfb4..e71903f 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -11,6 +11,7 @@ public Language(PostOffice postOffice) { public String lookAtPostBox = "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel."; public String notRegistered = "&a[Post Office] &4This isn't a registered post office box."; + public String alreadyRegistered = "&a[Post Office] &4This post box is already registered."; public String postBoxRemoved = "&a[Post Office] &aPost box removed successfully."; public String signOnBarrel = "&a[Post Office] &4The sign must be attached to a barrel."; public String successfulRegistration = "&a[Post Office] &aPost box registered successfully."; @@ -20,6 +21,7 @@ public Language(PostOffice postOffice) { public String removeFromConfig = "&a[Post Office] &aPost box successfully removed from the config."; public String unclaimedPostbox = "&a[Post Office] &4This post box is unclaimed."; public String userBanned = "&a[Post Office] &4You aren't able to interact with this post box."; + public String invalidPostbox = "&a[Post Office] &4This isn't a valid post box."; public String sentMessage = "&a[Post Office] &aMail sent to %receiver%."; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index b038dd3..4317233 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -73,6 +73,7 @@ public void reloadConfigFile() { postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); postOffice.signNotification = getBoolean(config, "sign-notification", true); + postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); postOffice.language.notRegistered = getString(config, "not-registered", postOffice.language.notRegistered); postOffice.language.postBoxRemoved = getString(config, "post-box-removed", postOffice.language.postBoxRemoved); @@ -84,6 +85,7 @@ public void reloadConfigFile() { postOffice.language.removeFromConfig = getString(config, "remove-from-config", postOffice.language.removeFromConfig); postOffice.language.unclaimedPostbox = getString(config, "unclaimed-postbox", postOffice.language.unclaimedPostbox); postOffice.language.userBanned = getString(config, "user-banned", postOffice.language.userBanned); + postOffice.language.alreadyRegistered = getString(config, "already-registered", postOffice.language.alreadyRegistered); } } catch (Exception e) { @@ -100,7 +102,7 @@ private boolean checkForMissingKeys(FileConfiguration config) { "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned"); + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox"); // Check for missing keys for (String key : keysToCheck) { @@ -121,7 +123,7 @@ private Map saveMissingKeyValues(FileConfiguration config) { "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned"); + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox"); // Save existing values of missing keys diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 1d44ea3..586c56c 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -59,6 +59,12 @@ successful-registration: "&a[Post Office] &aPost box registered successfully." # Message shown when a post box has already been claimed to another player already-claimed: "&a[Post Office] &4This post box has already been claimed." +# Error shown when running the info command and not looking at a valid postbox +invalid-postbox: "&a[Post Office] &4This isn't a valid post box." + +# Warning shown to the admin/mod when trying to register a new post box if it's already registered +already-registered: "&a[Post Office] &4This post box is already registered." + # Message shown when a post box is successfully claimed with the claim command successfully-claimed: "&a[Post Office] &aYou have successfully claimed this post box." diff --git a/src/main/resources/config/config.yml b/src/main/resources/config/config.yml index 1d44ea3..586c56c 100644 --- a/src/main/resources/config/config.yml +++ b/src/main/resources/config/config.yml @@ -59,6 +59,12 @@ successful-registration: "&a[Post Office] &aPost box registered successfully." # Message shown when a post box has already been claimed to another player already-claimed: "&a[Post Office] &4This post box has already been claimed." +# Error shown when running the info command and not looking at a valid postbox +invalid-postbox: "&a[Post Office] &4This isn't a valid post box." + +# Warning shown to the admin/mod when trying to register a new post box if it's already registered +already-registered: "&a[Post Office] &4This post box is already registered." + # Message shown when a post box is successfully claimed with the claim command successfully-claimed: "&a[Post Office] &aYou have successfully claimed this post box." From adedf40cf5748d275d1d227a2a7dca725c43fdc6 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 12:10:10 +0930 Subject: [PATCH 35/45] Adding extra language keys to config --- src/main/java/io/shantek/functions/Commands.java | 2 +- src/main/java/io/shantek/functions/Language.java | 3 +-- src/main/java/io/shantek/functions/PluginConfig.java | 8 ++++++-- src/main/resources/config.yml | 3 +++ 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 2f2eee0..bbfdd86 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -136,7 +136,7 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { if (owner != null && !owner.equals("none")) { player.sendMessage(ChatColor.GREEN + "This post box is owned by: " + ChatColor.YELLOW + owner); } else if (state != null && state.equals("registered")) { - player.sendMessage(ChatColor.GREEN + "This post box is currently registered but not claimed."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.registeredNotClaimed)); } else { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.invalidPostbox)); } diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index e71903f..0094cb3 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -22,8 +22,7 @@ public Language(PostOffice postOffice) { public String unclaimedPostbox = "&a[Post Office] &4This post box is unclaimed."; public String userBanned = "&a[Post Office] &4You aren't able to interact with this post box."; public String invalidPostbox = "&a[Post Office] &4This isn't a valid post box."; - - + public String registeredNotClaimed = "&a[Post Office] &eThis post box is currently registered, but not claimed."; public String sentMessage = "&a[Post Office] &aMail sent to %receiver%."; public String receivedMessage = "&a[Post Office] &eYou received mail from %sender%!"; public String gotMailMessage = "&a[Post Office] &fYou got mail!"; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 4317233..5257b96 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -73,6 +73,7 @@ public void reloadConfigFile() { postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); postOffice.signNotification = getBoolean(config, "sign-notification", true); + postOffice.language.registeredNotClaimed = getString(config, "registered-not-claimed", postOffice.language.registeredNotClaimed); postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); postOffice.language.notRegistered = getString(config, "not-registered", postOffice.language.notRegistered); @@ -102,7 +103,8 @@ private boolean checkForMissingKeys(FileConfiguration config) { "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox"); + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox", + "registered-not-claimed"); // Check for missing keys for (String key : keysToCheck) { @@ -123,7 +125,9 @@ private Map saveMissingKeyValues(FileConfiguration config) { "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox"); + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox", + "registered-not-claimed" + ); // Save existing values of missing keys diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 586c56c..ada93da 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -12,6 +12,9 @@ sent-message: "&a[Post Office] &aMail sent to %receiver%." # Message sent to the receiver if they are online received-message: "&a[Post Office] &eYou received mail from %sender%!" +# Message shown when a post box is registered, but not claimed - when running the info command +registered-not-claimed: "&a[Post Office] &eThis post box is currently registered, but not claimed." + # Message sent to the receiver next time they log on to the server got-mail-message: "&a[Post Office] &fYou got mail!" From e44dd30e06aac682d691a060ce1d0c4bd9ad253e Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 14:35:43 +0930 Subject: [PATCH 36/45] Moved all lang to a lang file --- .../io/shantek/functions/PluginConfig.java | 56 +++++++++--- src/main/resources/barrels.yml | 1 + src/main/resources/config.yml | 88 +------------------ .../resources/{config/config.yml => lang.yml} | 26 +----- 4 files changed, 46 insertions(+), 125 deletions(-) rename src/main/resources/{config/config.yml => lang.yml} (78%) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 5257b96..a462d65 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -40,7 +40,7 @@ public void reloadConfigFile() { FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check for missing keys - @SuppressWarnings("unused") boolean keysMissing = checkForMissingKeys(config); + boolean keysMissing = checkForMissingKeys(config); // Save existing values of missing keys Map missingKeyValues = saveMissingKeyValues(config); @@ -48,12 +48,49 @@ public void reloadConfigFile() { // Create a fresh config file saveDefaultConfig("config.yml", configFile); - // Load the new config + // Load and update the config config = YamlConfiguration.loadConfiguration(configFile); + updateConfigWithMissingKeyValues(config, missingKeyValues); + + // Boolean settings/config + postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); + postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); + postOffice.consoleLogs = getBoolean(config, "console-logs", true); + postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); + postOffice.signNotification = getBoolean(config, "sign-notification", true); + } + } catch (Exception e) { + postOffice.getLogger().log(Level.SEVERE, "An error occurred while reloading the config file", e); + } + + try { + postOffice.getLogger().info("Reloading lang file."); // Print to the console + + File langFile = new File(postOffice.getDataFolder(), "lang.yml"); + + // Check if the config file exists + if (!langFile.exists()) { + postOffice.getLogger().info("Lang file not found. Creating a new one."); + + // Create a new config file based on a template from resources + saveDefaultConfig("lang.yml", langFile); + } else { + FileConfiguration config = YamlConfiguration.loadConfiguration(langFile); + + // Check for missing keys + boolean keysMissing = checkForMissingKeys(config); - // Update the new config with missing key values + // Save existing values of missing keys + Map missingKeyValues = saveMissingKeyValues(config); + + // Create a fresh config file + saveDefaultConfig("config.yml", langFile); + + // Load and update the config + config = YamlConfiguration.loadConfiguration(langFile); updateConfigWithMissingKeyValues(config, missingKeyValues); + // Language strings postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); postOffice.language.removeItemError = getString(config, "remove-item-error", postOffice.language.removeItemError); @@ -66,13 +103,6 @@ public void reloadConfigFile() { postOffice.language.postboxCreated = getString(config, "postbox-created", postOffice.language.postboxCreated); postOffice.language.pluginUpToDate = getString(config, "plugin-up-to-date", postOffice.language.pluginUpToDate); postOffice.language.dropItemError = getString(config, "drop-item-error", postOffice.language.pluginUpToDate); - - postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); - postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); - postOffice.consoleLogs = getBoolean(config, "console-logs", true); - postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); - postOffice.signNotification = getBoolean(config, "sign-notification", true); - postOffice.language.registeredNotClaimed = getString(config, "registered-not-claimed", postOffice.language.registeredNotClaimed); postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); @@ -87,10 +117,10 @@ public void reloadConfigFile() { postOffice.language.unclaimedPostbox = getString(config, "unclaimed-postbox", postOffice.language.unclaimedPostbox); postOffice.language.userBanned = getString(config, "user-banned", postOffice.language.userBanned); postOffice.language.alreadyRegistered = getString(config, "already-registered", postOffice.language.alreadyRegistered); - } + } } catch (Exception e) { - postOffice.getLogger().log(Level.SEVERE, "An error occurred while reloading the config file", e); + postOffice.getLogger().log(Level.SEVERE, "An error occurred while reloading the lang file", e); } } @@ -151,7 +181,7 @@ private void updateConfigWithMissingKeyValues(FileConfiguration config, Map Date: Fri, 20 Sep 2024 17:48:18 +0930 Subject: [PATCH 37/45] Fixed issues with lang config --- .../io/shantek/functions/PluginConfig.java | 73 ++++++++++++++----- 1 file changed, 55 insertions(+), 18 deletions(-) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index a462d65..c4c5b9e 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -40,10 +40,10 @@ public void reloadConfigFile() { FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check for missing keys - boolean keysMissing = checkForMissingKeys(config); + boolean keysMissing = checkForMissingConfigKeys(config); // Save existing values of missing keys - Map missingKeyValues = saveMissingKeyValues(config); + Map missingKeyValues = saveMissingConfigKey(config); // Create a fresh config file saveDefaultConfig("config.yml", configFile); @@ -78,10 +78,10 @@ public void reloadConfigFile() { FileConfiguration config = YamlConfiguration.loadConfiguration(langFile); // Check for missing keys - boolean keysMissing = checkForMissingKeys(config); + boolean keysMissing = checkForMissingLangKeys(config); // Save existing values of missing keys - Map missingKeyValues = saveMissingKeyValues(config); + Map missingKeyValues = saveMissingLangKey(config); // Create a fresh config file saveDefaultConfig("config.yml", langFile); @@ -124,17 +124,13 @@ public void reloadConfigFile() { } } - private boolean checkForMissingKeys(FileConfiguration config) { + private boolean checkForMissingConfigKeys(FileConfiguration config) { boolean keysMissing = false; // List of keys to check List keysToCheck = Arrays.asList( - "custom-barrel-name", "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", - "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", - "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox", - "registered-not-claimed"); + "custom-barrel-name", "sign-notification", "got-mail-delay", "update-notification", "postbox-protection", "console-logs" + ); // Check for missing keys for (String key : keysToCheck) { @@ -146,19 +142,60 @@ private boolean checkForMissingKeys(FileConfiguration config) { return keysMissing; } - private Map saveMissingKeyValues(FileConfiguration config) { + private boolean checkForMissingLangKeys(FileConfiguration config) { + boolean keysMissing = false; + + // List of keys to check + List keysToCheck = Arrays.asList( + "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", + "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", + "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", + "already-registered", "invalid-postbox" + ); + + + // Check for missing keys + for (String key : keysToCheck) { + if (!config.contains(key)) { + postOffice.getLogger().warning("Key '" + key + "' not found in the configuration file, reverting to the default."); + keysMissing = true; + } + } + return keysMissing; + } + + private Map saveMissingLangKey(FileConfiguration config) { Map missingKeyValues = new HashMap<>(); // List of keys to check List keysToCheck = Arrays.asList( - "custom-barrel-name", "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", - "sent-message", "received-message", "got-mail-message", "update-notification", "postbox-protection", - "create-error", "break-error", "console-logs", "postbox-created", "plugin-up-to-date", "got-mail-delay", "sign-notification", - "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", "already-registered", "invalid-postbox", - "registered-not-claimed" + "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", + "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", + "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", + "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", + "already-registered", "invalid-postbox" ); + // Save existing values of missing keys + for (String key : keysToCheck) { + if (config.contains(key)) { + Object value = config.get(key); + missingKeyValues.put(key, value); + } + } + return missingKeyValues; + } + + private Map saveMissingConfigKey(FileConfiguration config) { + Map missingKeyValues = new HashMap<>(); + + // List of keys to check + List keysToCheck = Arrays.asList( + "custom-barrel-name", "sign-notification", "got-mail-delay", "update-notification", "postbox-protection", "console-logs" + ); // Save existing values of missing keys for (String key : keysToCheck) { From 58bfedfac64716e33588101bfc79f7f306f314e8 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 18:01:20 +0930 Subject: [PATCH 38/45] Starting to simplify the lang file. Further work to come. --- src/main/java/io/shantek/functions/Helpers.java | 5 ++++- src/main/java/io/shantek/functions/Language.java | 1 - src/main/java/io/shantek/functions/PluginConfig.java | 9 ++++----- src/main/java/io/shantek/listeners/InventoryClick.java | 2 +- src/main/resources/lang.yml | 10 +++++----- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 9936dd2..7485876 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -338,7 +338,7 @@ private void loadBarrelsIntoCache() { FileConfiguration barrelsConfig = getBarrelsConfig(); if (barrelsConfig.contains("barrels")) { Set keys = Objects.requireNonNull(barrelsConfig.getConfigurationSection("barrels")).getKeys(false); - postOffice.getLogger().info("Loading barrels into cache. Found keys: " + keys); + //postOffice.getLogger().info("Loading barrels into cache. Found keys: " + keys); for (String key : keys) { String path = "barrels." + key; @@ -360,8 +360,11 @@ private void loadBarrelsIntoCache() { BarrelData barrelData = new BarrelData(ownerUUID, state, signLocation); barrelsCache.put(key, barrelData); // Add to cache + /* postOffice.getLogger().info("Added barrel to cache at location: " + key + ", Owner: " + (ownerUUID != null ? ownerUUID : "none") + ", State: " + state + ", Sign: " + signLocation); + + */ } } else { postOffice.getLogger().warning("No barrels found in barrels.yml during cache load."); diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index 0094cb3..b92f4ba 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -27,7 +27,6 @@ public Language(PostOffice postOffice) { public String receivedMessage = "&a[Post Office] &eYou received mail from %sender%!"; public String gotMailMessage = "&a[Post Office] &fYou got mail!"; public String noPermission = "&a[Post Office] &4You don't have permission to do that."; - public String removeItemError = "&a[Post Office] &4You don't have permission to remove items."; public String hotBarError = "&a[Post Office] &4No hot bar usage while in a Post Box!"; public String breakError = "&a[Post Office] &4You can't break a Post Box."; public String createError = "&a[Post Office] &4You can't create a Post Box."; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index c4c5b9e..2f7750b 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -32,7 +32,7 @@ public void reloadConfigFile() { // Check if the config file exists if (!configFile.exists()) { - postOffice.getLogger().info("Config file not found. Creating a new one..."); + postOffice.getLogger().info("No config file found. Generating a new one."); // Create a new config file based on a template from resources saveDefaultConfig("config.yml", configFile); @@ -70,7 +70,7 @@ public void reloadConfigFile() { // Check if the config file exists if (!langFile.exists()) { - postOffice.getLogger().info("Lang file not found. Creating a new one."); + postOffice.getLogger().info("No lang file not found. Generating a new one."); // Create a new config file based on a template from resources saveDefaultConfig("lang.yml", langFile); @@ -93,7 +93,6 @@ public void reloadConfigFile() { // Language strings postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); - postOffice.language.removeItemError = getString(config, "remove-item-error", postOffice.language.removeItemError); postOffice.language.hotBarError = getString(config, "hotbar-error", postOffice.language.hotBarError); postOffice.language.sentMessage = getString(config, "sent-message", postOffice.language.sentMessage); postOffice.language.receivedMessage = getString(config, "received-message", postOffice.language.receivedMessage); @@ -147,7 +146,7 @@ private boolean checkForMissingLangKeys(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "no-permission", "offhand-error", "hotbar-error", "drop-item-error", "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", @@ -171,7 +170,7 @@ private Map saveMissingLangKey(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "no-permission", "remove-item-error", "offhand-error", "hotbar-error", "drop-item-error", + "no-permission", "offhand-error", "hotbar-error", "drop-item-error", "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index db1ee56..966e4be 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -77,7 +77,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (postOffice.consoleLogs) { postOffice.getLogger().info("Player " + player.getName() + " tried to interact without permission."); } - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.removeItemError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); event.setCancelled(true); return; } diff --git a/src/main/resources/lang.yml b/src/main/resources/lang.yml index 23ae6fa..6898c8d 100644 --- a/src/main/resources/lang.yml +++ b/src/main/resources/lang.yml @@ -1,20 +1,20 @@ -# Message sent to the sender when closing the Post Box +# Confirmation message shown to the sender when leaving mail in another post box. +# %receiver% will be replaced with the person sending the mail sent-message: "&a[Post Office] &aMail sent to %receiver%." # Message sent to the receiver if they are online +# %receiver% will be replaced with the name of the person receiving the mail +# %sender% will be replaced with the name of the person sending the mail received-message: "&a[Post Office] &eYou received mail from %sender%!" -# Message sent to the receiver next time they log on to the server +# Message sent to the player next time they log on to the server, if they have mail got-mail-message: "&a[Post Office] &fYou got mail!" # Generic no permission error message when a player is attempting to do an action # that they shouldn't have permission to do no-permission: "&a[Post Office] &4You don't have permission to do that." -# Error shown when a player attempts to remove items without permission -remove-item-error: "&a[Post Office] &4You don't have permission to remove items." - # Error shown when trying to use their offhand while in a Post Box offhand-error: "&a[Post Office] &4No offhand usage while in a Post Box!" From 8531b1ce53b9225b7365f9f49e93ad229ea99d62 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 21:06:45 +0930 Subject: [PATCH 39/45] Additional customization added to the lang file --- .../java/io/shantek/functions/Commands.java | 33 +++++-- .../java/io/shantek/functions/Language.java | 30 +++---- .../io/shantek/functions/PluginConfig.java | 89 +++++++++++++------ .../shantek/listeners/BarrelProtection.java | 4 +- .../io/shantek/listeners/InventoryClick.java | 6 +- src/main/resources/lang.yml | 62 +++++++------ 6 files changed, 141 insertions(+), 83 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index bbfdd86..d1625f1 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -134,9 +134,12 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // If there's an owner, print it. Otherwise, print the state. if (owner != null && !owner.equals("none")) { - player.sendMessage(ChatColor.GREEN + "This post box is owned by: " + ChatColor.YELLOW + owner); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.postBoxOwner + .replace("%owner%", owner) + )); } else if (state != null && state.equals("registered")) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.registeredNotClaimed)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.unclaimedPostbox)); } else { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.invalidPostbox)); } @@ -170,7 +173,10 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Check if the post box is already registered or claimed if (currentOwner != null && !currentOwner.equals("none")) { - player.sendMessage(ChatColor.RED + "This post box is already claimed by: " + ChatColor.YELLOW + currentOwner); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.postBoxOwner + .replace("%owner%", currentOwner) + )); return true; } if (currentState != null && currentState.equals("registered")) { @@ -240,7 +246,10 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { OfflinePlayer targetPlayer = Bukkit.getOfflinePlayer(targetPlayerName); if (!targetPlayer.hasPlayedBefore()) { - player.sendMessage(ChatColor.RED + "The player " + targetPlayerName + " has not played on this server."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.notPlayedBefore + .replace("%player%", targetPlayer.toString()) + )); return true; } @@ -249,7 +258,10 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Check if the player already has a post box if (postOffice.helpers.doesPlayerHavePostBox(targetPlayerUUID)) { String existingPostBoxLocation = postOffice.helpers.getPlayerPostBoxLocation(targetPlayerUUID); // Get world and coordinates - player.sendMessage(ChatColor.RED + targetPlayerName + " already has a post box at: " + ChatColor.YELLOW + existingPostBoxLocation); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.alreadyHasPostBox + .replace("%player%", targetPlayerName) + .replace("%location%", existingPostBoxLocation))); return true; } @@ -270,7 +282,9 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { sign.update(); } - player.sendMessage(ChatColor.GREEN + "The post box has been claimed for " + targetPlayerName + "."); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.claimedFor + .replace("%owner%", targetPlayerName))); postOffice.helpers.saveCacheToFile(); // Save the cache to disk return true; @@ -316,7 +330,12 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Check if the player already has a post box if (postOffice.helpers.doesPlayerHavePostBox(playerUUID)) { String existingPostBoxLocation = postOffice.helpers.getPlayerPostBoxLocation(playerUUID); // Get world and coordinates - player.sendMessage(ChatColor.RED + "You already have a post box at: " + ChatColor.YELLOW + existingPostBoxLocation); + + player.sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.alreadyHasPostBox + .replace("%player%", player.getName()) + .replace("%location%", existingPostBoxLocation))); + return true; } diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index b92f4ba..50d70f3 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -9,30 +9,30 @@ public Language(PostOffice postOffice) { this.postOffice = postOffice; } - public String lookAtPostBox = "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel."; + public String sentMessage = "&a[Post Office] &aMail sent to %receiver%."; + public String receivedMessage = "&a[Post Office] &eYou received mail from %sender%!"; + public String gotMailMessage = "&a[Post Office] &fYou got mail!"; + public String noPermission = "&a[Post Office] &4You don't have permission to do that."; + public String denyAction = "&a[Post Office] &4You can't do that here!"; public String notRegistered = "&a[Post Office] &4This isn't a registered post office box."; - public String alreadyRegistered = "&a[Post Office] &4This post box is already registered."; public String postBoxRemoved = "&a[Post Office] &aPost box removed successfully."; - public String signOnBarrel = "&a[Post Office] &4The sign must be attached to a barrel."; public String successfulRegistration = "&a[Post Office] &aPost box registered successfully."; + public String alreadyRegistered = "&a[Post Office] &4This post box is already registered."; + public String postboxCreated = "&a[Post Office] &4 Box successfully created for %username%"; + public String removeFromConfig = "&a[Post Office] &aPost box successfully removed from the config."; + public String lookAtPostBox = "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel."; + public String signOnBarrel = "&a[Post Office] &4The sign must be attached to a barrel."; public String alreadyClaimed = "&a[Post Office] &4This post box has already been claimed."; + public String invalidPostbox = "&a[Post Office] &4This isn't a valid post box."; public String successfullyClaimed = "&a[Post Office] &aYou have successfully registered this post box."; public String modifySign = "&a[Post Office] &4You cannot modify a post box sign."; - public String removeFromConfig = "&a[Post Office] &aPost box successfully removed from the config."; public String unclaimedPostbox = "&a[Post Office] &4This post box is unclaimed."; public String userBanned = "&a[Post Office] &4You aren't able to interact with this post box."; - public String invalidPostbox = "&a[Post Office] &4This isn't a valid post box."; - public String registeredNotClaimed = "&a[Post Office] &eThis post box is currently registered, but not claimed."; - public String sentMessage = "&a[Post Office] &aMail sent to %receiver%."; - public String receivedMessage = "&a[Post Office] &eYou received mail from %sender%!"; - public String gotMailMessage = "&a[Post Office] &fYou got mail!"; - public String noPermission = "&a[Post Office] &4You don't have permission to do that."; - public String hotBarError = "&a[Post Office] &4No hot bar usage while in a Post Box!"; - public String breakError = "&a[Post Office] &4You can't break a Post Box."; - public String createError = "&a[Post Office] &4You can't create a Post Box."; - public String postboxCreated = "&a[Post Office] &4 Box successfully created for %username%"; + public String postBoxOwner = "&a[Post Office] &aThis post box is owned by %owner%"; + public String claimedFor = "&a[Post Office] &aThis post box has been claimed for %owner%"; + public String alreadyHasPostBox = "&a[Post Office] &4%player% already has a post box at: %location%"; + public String notPlayedBefore = "&a[Post Office] &4The player %player% has not played on this server."; public String pluginUpToDate = "Your plugin is up-to-date."; - public String dropItemError = "&a[Post Office] &4 You can't drop items while in a postbox."; public UpdateChecker updateChecker; public PluginConfig pluginConfig; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 2f7750b..0a5eb67 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -53,6 +53,7 @@ public void reloadConfigFile() { updateConfigWithMissingKeyValues(config, missingKeyValues); // Boolean settings/config + postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); postOffice.consoleLogs = getBoolean(config, "console-logs", true); @@ -84,38 +85,38 @@ public void reloadConfigFile() { Map missingKeyValues = saveMissingLangKey(config); // Create a fresh config file - saveDefaultConfig("config.yml", langFile); + saveDefaultConfig("lang.yml", langFile); // Load and update the config config = YamlConfiguration.loadConfiguration(langFile); updateConfigWithMissingKeyValues(config, missingKeyValues); // Language strings - postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); - postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); - postOffice.language.hotBarError = getString(config, "hotbar-error", postOffice.language.hotBarError); postOffice.language.sentMessage = getString(config, "sent-message", postOffice.language.sentMessage); postOffice.language.receivedMessage = getString(config, "received-message", postOffice.language.receivedMessage); postOffice.language.gotMailMessage = getString(config, "got-mail-message", postOffice.language.gotMailMessage); - postOffice.language.createError = getString(config, "create-error", postOffice.language.createError); - postOffice.language.breakError = getString(config, "break-error", postOffice.language.breakError); - postOffice.language.postboxCreated = getString(config, "postbox-created", postOffice.language.postboxCreated); - postOffice.language.pluginUpToDate = getString(config, "plugin-up-to-date", postOffice.language.pluginUpToDate); - postOffice.language.dropItemError = getString(config, "drop-item-error", postOffice.language.pluginUpToDate); - postOffice.language.registeredNotClaimed = getString(config, "registered-not-claimed", postOffice.language.registeredNotClaimed); - postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); - postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); + postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); + postOffice.language.denyAction = getString(config, "deny-action", postOffice.language.denyAction); postOffice.language.notRegistered = getString(config, "not-registered", postOffice.language.notRegistered); postOffice.language.postBoxRemoved = getString(config, "post-box-removed", postOffice.language.postBoxRemoved); - postOffice.language.signOnBarrel = getString(config, "sign-on-barrel", postOffice.language.signOnBarrel); postOffice.language.successfulRegistration = getString(config, "successful-registration", postOffice.language.successfulRegistration); + postOffice.language.alreadyRegistered = getString(config, "already-registered", postOffice.language.alreadyRegistered); + postOffice.language.postboxCreated = getString(config, "postbox-created", postOffice.language.postboxCreated); + postOffice.language.removeFromConfig = getString(config, "remove-from-config", postOffice.language.removeFromConfig); + postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); + postOffice.language.signOnBarrel = getString(config, "sign-on-barrel", postOffice.language.signOnBarrel); postOffice.language.alreadyClaimed = getString(config, "already-claimed", postOffice.language.alreadyClaimed); + postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); postOffice.language.successfullyClaimed = getString(config, "successfully-claimed", postOffice.language.successfullyClaimed); postOffice.language.modifySign = getString(config, "modify-sign", postOffice.language.modifySign); - postOffice.language.removeFromConfig = getString(config, "remove-from-config", postOffice.language.removeFromConfig); postOffice.language.unclaimedPostbox = getString(config, "unclaimed-postbox", postOffice.language.unclaimedPostbox); postOffice.language.userBanned = getString(config, "user-banned", postOffice.language.userBanned); - postOffice.language.alreadyRegistered = getString(config, "already-registered", postOffice.language.alreadyRegistered); + postOffice.language.postBoxOwner = getString(config, "post-box-owner", postOffice.language.postBoxOwner); + postOffice.language.claimedFor = getString(config, "claimed-for", postOffice.language.claimedFor); + postOffice.language.alreadyHasPostBox = getString(config, "already-has-postbox", postOffice.language.alreadyHasPostBox); + postOffice.language.notPlayedBefore = getString(config, "not-played-before", postOffice.language.notPlayedBefore); + + postOffice.language.pluginUpToDate = getString(config, "plugin-up-to-date", postOffice.language.pluginUpToDate); } } catch (Exception e) { @@ -146,12 +147,29 @@ private boolean checkForMissingLangKeys(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "no-permission", "offhand-error", "hotbar-error", "drop-item-error", - "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", - "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", - "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", - "already-registered", "invalid-postbox" + "sent-message", + "received-message", + "got-mail-message", + "no-permission", "deny-action", + "not-registered", + "post-box-removed", + "successful-registration", + "already-registered", + "postbox-created", + "remove-from-config", + "look-at-post-box", + "sign-on-barrel", + "already-claimed", + "invalid-postbox", + "successfully-claimed", + "modify-sign", + "unclaimed-postbox", + "user-banned", + "post-box-owner", + "claimed-for", + "already-has-postbox", + "not-played-before", + "plugin-up-to-date" ); @@ -170,12 +188,29 @@ private Map saveMissingLangKey(FileConfiguration config) { // List of keys to check List keysToCheck = Arrays.asList( - "no-permission", "offhand-error", "hotbar-error", "drop-item-error", - "plugin-up-to-date", "sent-message", "received-message", "got-mail-message", "create-error", - "break-error", "postbox-created", "registered-not-claimed", "look-at-post-box", "not-registered", - "post-box-removed", "sign-on-barrel", "successful-registration", "already-claimed", - "successfully-claimed", "modify-sign", "remove-from-config", "unclaimed-postbox", "user-banned", - "already-registered", "invalid-postbox" + "sent-message", + "received-message", + "got-mail-message", + "no-permission", "deny-action", + "not-registered", + "post-box-removed", + "successful-registration", + "already-registered", + "postbox-created", + "remove-from-config", + "look-at-post-box", + "sign-on-barrel", + "already-claimed", + "invalid-postbox", + "successfully-claimed", + "modify-sign", + "unclaimed-postbox", + "user-banned", + "post-box-owner", + "claimed-for", + "already-has-postbox", + "not-played-before", + "plugin-up-to-date" ); // Save existing values of missing keys diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index 9461fdd..63aa66f 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -90,7 +90,7 @@ public void onBlockBreak(BlockBreakEvent event) { } else { // Prevent the player from breaking the post box if they don't have permission - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.breakError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); event.setCancelled(true); } } @@ -109,7 +109,7 @@ public void onBlockPlace(BlockPlaceEvent event) { if (placedBlock.getState() instanceof Sign && postOffice.helpers.hasBarrelNearby(placedBlock)) { if (!player.isOp() && !player.hasPermission("shantek.postoffice.create")) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.createError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); placedBlock.breakNaturally(); } } diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index 966e4be..ab90cf1 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -95,7 +95,7 @@ public void onInventoryClick(InventoryClickEvent event) { if (event.getClick() == ClickType.NUMBER_KEY) { ItemStack hotbarItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); if (hotbarItem != null) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); event.setCancelled(true); return; } @@ -103,14 +103,14 @@ public void onInventoryClick(InventoryClickEvent event) { // Prevent swapping items from a barrel while having another item in hand if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR || event.getAction() == InventoryAction.HOTBAR_SWAP) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.hotBarError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); event.setCancelled(true); return; } // Prevent the player from dropping items out of the postbox if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.dropItemError)); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); event.setCancelled(true); return; } diff --git a/src/main/resources/lang.yml b/src/main/resources/lang.yml index 6898c8d..469eab7 100644 --- a/src/main/resources/lang.yml +++ b/src/main/resources/lang.yml @@ -16,20 +16,7 @@ got-mail-message: "&a[Post Office] &fYou got mail!" no-permission: "&a[Post Office] &4You don't have permission to do that." # Error shown when trying to use their offhand while in a Post Box -offhand-error: "&a[Post Office] &4No offhand usage while in a Post Box!" - -# Error shown when trying to swap items to their hotbar -hotbar-error: "&a[Post Office] &4No hot bar usage while in a Post Box!" - -# Error shown when the player tries to create a Post Box -create-error: "&a[Post Office] &4You can't create a Post Box." - -# Error shown when a player tries to break a Post Box -break-error: "&a[Post Office] &4You can't break this Post Box." - -# Error when running a command and not looking at a configured post box. -# This is a generic error, shown in a lot of different scenarios. -look-at-post-box: "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel." +deny-action: "&a[Post Office] &4You can't do that here!" # Error when the post box isn't registered in the config. Used in instanced like when trying to remove # a post box, looking up postbox info etc. @@ -38,32 +25,40 @@ not-registered: "&a[Post Office] &4This isn't a registered post office box." # Message shown when a post box is successfully removed with the remove command post-box-removed: "&a[Post Office] &aPost box removed successfully." +# Message when a post box has been successfully registered in the config +successful-registration: "&a[Post Office] &aPost box registered successfully." + +# Warning shown to the admin/mod when trying to register a new post box if it's already registered +already-registered: "&a[Post Office] &4This post box is already registered." + +# Confirmation message shown when a post box has been created +# You can use %username% to show the players name +postbox-created: "&a[Post Office] &2 Box successfully created for %username%" + +# Message when a post box has been broken but was still in the config. The plugin will +# automatically remove it from the config. +remove-from-config: "&a[Post Office] &aPost box successfully removed from the config." + +# Error when running a command and not looking at a configured post box. +# This is a generic error, shown in a lot of different scenarios. +look-at-post-box: "&a[Post Office] &4You must be looking at a barrel or a sign attached to a barrel." + # Warning shown in cases where we haven't found a barrel/sign combo # resulting in an invalid setup sign-on-barrel: "&a[Post Office] &4The sign must be attached to a barrel." -# Message when a post box has been successfully registered in the config -successful-registration: "&a[Post Office] &aPost box registered successfully." - # Message shown when a post box has already been claimed to another player already-claimed: "&a[Post Office] &4This post box has already been claimed." # Error shown when running the info command and not looking at a valid postbox invalid-postbox: "&a[Post Office] &4This isn't a valid post box." -# Warning shown to the admin/mod when trying to register a new post box if it's already registered -already-registered: "&a[Post Office] &4This post box is already registered." - # Message shown when a post box is successfully claimed with the claim command successfully-claimed: "&a[Post Office] &aYou have successfully claimed this post box." # Error when a player is trying to modify a post box sign without the correct permission modify-sign: "&a[Post Office] &4You cannot modify a post box sign." -# Message when a post box has been broken but was still in the config. The plugin will -# automatically remove it from the config. -remove-from-config: "&a[Post Office] &aPost box successfully removed from the config." - # Warning shown when closing an unclaimed post box. Good as a reminder for an admin/mod # that they may be leaving items in the wrong post box unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." @@ -72,12 +67,21 @@ unclaimed-postbox: "&a[Post Office] &4This post box is unclaimed." # They aren't able to open a post box and will see this error. user-banned: "&a[Post Office] &4You aren't able to interact with this post box." -# Confirmation message shown when a post box has been created -# You can use %username% to show the players name -postbox-created: "&a[Post Office] &2 Box successfully created for %username%" +# Message shown when looking running the info command and looking at a post box +# %owner% is replaced with the name of the player who owns the post box +post-box-owner: "&a[Post Office] &aThis post box is owned by %owner%" + +# %owner% is replaced with the name of the owner of the post box +claimed-for: "&a[Post Office] &aThis post box has been claimed for %owner%" + +# Warning shown when the player tries to register a box and already has one registered +# %player% is replaced with the name of the player who is trying to claim a box +# %location% is replaced with the location of the box they already own +already-has-postbox: "&a[Post Office] &4%player% already has a post box at: %location%" -# Error shown to the player if they try dropping an item while in a post box -drop-item-error: "&a[Post Office] &4 You can't drop items while in a postbox." +# A warning shown when the name being registered doesn't exist on the server +# %player% is replaced with the name that is being used to register a box +not-played-before: "&a[Post Office] &4The player %player% has not played on this server." # Message shown in the console to inform the server owner the plugin is up to date plugin-up-to-date: "Your plugin is up to date." \ No newline at end of file From 5b697740c5eb95e7d1707a63c664bb78751fdace Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 21:58:34 +0930 Subject: [PATCH 40/45] Re-wrote config handling/reloading --- .../io/shantek/functions/PluginConfig.java | 384 +++++------------- 1 file changed, 110 insertions(+), 274 deletions(-) diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 0a5eb67..82db524 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -1,17 +1,16 @@ package io.shantek.functions; import io.shantek.PostOffice; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.HashMap; -import java.util.logging.Level; -import java.nio.file.*; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.util.*; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; +import java.util.logging.Level; public class PluginConfig { @@ -25,334 +24,173 @@ public PluginConfig(PostOffice postOffice) { private File barrelsConfigFile = null; public void reloadConfigFile() { - try { - postOffice.getLogger().info("Reloading config file."); // Print to the console - - File configFile = new File(postOffice.getDataFolder(), "config.yml"); - - // Check if the config file exists - if (!configFile.exists()) { - postOffice.getLogger().info("No config file found. Generating a new one."); - - // Create a new config file based on a template from resources - saveDefaultConfig("config.yml", configFile); - } else { - FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); + // Handle config.yml + handleFile("config.yml", this::loadConfigFile); - // Check for missing keys - boolean keysMissing = checkForMissingConfigKeys(config); - - // Save existing values of missing keys - Map missingKeyValues = saveMissingConfigKey(config); - - // Create a fresh config file - saveDefaultConfig("config.yml", configFile); - - // Load and update the config - config = YamlConfiguration.loadConfiguration(configFile); - updateConfigWithMissingKeyValues(config, missingKeyValues); + // Handle lang.yml + handleFile("lang.yml", this::loadLangFile); + } - // Boolean settings/config - postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); - postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); - postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); - postOffice.consoleLogs = getBoolean(config, "console-logs", true); - postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); - postOffice.signNotification = getBoolean(config, "sign-notification", true); - } - } catch (Exception e) { - postOffice.getLogger().log(Level.SEVERE, "An error occurred while reloading the config file", e); + private void handleFile(String fileName, Runnable loadAction) { + File file = new File(postOffice.getDataFolder(), fileName); + if (!file.exists()) { + postOffice.getLogger().info(fileName + " not found. Creating a new one..."); + saveDefaultConfig(fileName, file); // Create default file if not exists + } else { + postOffice.getLogger().info(fileName + " found. Reloading and checking for missing keys..."); + loadAction.run(); } + } - try { - postOffice.getLogger().info("Reloading lang file."); // Print to the console - - File langFile = new File(postOffice.getDataFolder(), "lang.yml"); - - // Check if the config file exists - if (!langFile.exists()) { - postOffice.getLogger().info("No lang file not found. Generating a new one."); - - // Create a new config file based on a template from resources - saveDefaultConfig("lang.yml", langFile); - } else { - FileConfiguration config = YamlConfiguration.loadConfiguration(langFile); - - // Check for missing keys - boolean keysMissing = checkForMissingLangKeys(config); - - // Save existing values of missing keys - Map missingKeyValues = saveMissingLangKey(config); - - // Create a fresh config file - saveDefaultConfig("lang.yml", langFile); - - // Load and update the config - config = YamlConfiguration.loadConfiguration(langFile); - updateConfigWithMissingKeyValues(config, missingKeyValues); - - // Language strings - postOffice.language.sentMessage = getString(config, "sent-message", postOffice.language.sentMessage); - postOffice.language.receivedMessage = getString(config, "received-message", postOffice.language.receivedMessage); - postOffice.language.gotMailMessage = getString(config, "got-mail-message", postOffice.language.gotMailMessage); - postOffice.language.noPermission = getString(config, "no-permission", postOffice.language.noPermission); - postOffice.language.denyAction = getString(config, "deny-action", postOffice.language.denyAction); - postOffice.language.notRegistered = getString(config, "not-registered", postOffice.language.notRegistered); - postOffice.language.postBoxRemoved = getString(config, "post-box-removed", postOffice.language.postBoxRemoved); - postOffice.language.successfulRegistration = getString(config, "successful-registration", postOffice.language.successfulRegistration); - postOffice.language.alreadyRegistered = getString(config, "already-registered", postOffice.language.alreadyRegistered); - postOffice.language.postboxCreated = getString(config, "postbox-created", postOffice.language.postboxCreated); - postOffice.language.removeFromConfig = getString(config, "remove-from-config", postOffice.language.removeFromConfig); - postOffice.language.lookAtPostBox = getString(config, "look-at-post-box", postOffice.language.lookAtPostBox); - postOffice.language.signOnBarrel = getString(config, "sign-on-barrel", postOffice.language.signOnBarrel); - postOffice.language.alreadyClaimed = getString(config, "already-claimed", postOffice.language.alreadyClaimed); - postOffice.language.invalidPostbox = getString(config, "invalid-postbox", postOffice.language.invalidPostbox); - postOffice.language.successfullyClaimed = getString(config, "successfully-claimed", postOffice.language.successfullyClaimed); - postOffice.language.modifySign = getString(config, "modify-sign", postOffice.language.modifySign); - postOffice.language.unclaimedPostbox = getString(config, "unclaimed-postbox", postOffice.language.unclaimedPostbox); - postOffice.language.userBanned = getString(config, "user-banned", postOffice.language.userBanned); - postOffice.language.postBoxOwner = getString(config, "post-box-owner", postOffice.language.postBoxOwner); - postOffice.language.claimedFor = getString(config, "claimed-for", postOffice.language.claimedFor); - postOffice.language.alreadyHasPostBox = getString(config, "already-has-postbox", postOffice.language.alreadyHasPostBox); - postOffice.language.notPlayedBefore = getString(config, "not-played-before", postOffice.language.notPlayedBefore); - - postOffice.language.pluginUpToDate = getString(config, "plugin-up-to-date", postOffice.language.pluginUpToDate); + private void loadConfigFile() { + File configFile = new File(postOffice.getDataFolder(), "config.yml"); + FileConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (checkForMissingConfigKeys(config)) { + postOffice.getLogger().info("Updating config with missing keys..."); + updateConfigWithMissingKeyValues(config, saveMissingConfigKey(config), configFile); + } + postOffice.customBarrelName = getString(config, "custom-barrel-name", "pobox"); + postOffice.postBoxProtection = getBoolean(config, "postbox-protection", true); + postOffice.updateNotificationEnabled = getBoolean(config, "update-notification", true); + postOffice.consoleLogs = getBoolean(config, "console-logs", false); + postOffice.gotMailDelay = getBoolean(config, "got-mail-delay", true); + postOffice.signNotification = getBoolean(config, "sign-notification", true); + } - } - } catch (Exception e) { - postOffice.getLogger().log(Level.SEVERE, "An error occurred while reloading the lang file", e); - } + private void loadLangFile() { + File langFile = new File(postOffice.getDataFolder(), "lang.yml"); + FileConfiguration langConfig = YamlConfiguration.loadConfiguration(langFile); + if (checkForMissingLangKeys(langConfig)) { + postOffice.getLogger().info("Updating lang with missing keys..."); + updateConfigWithMissingKeyValues(langConfig, saveMissingLangKey(langConfig), langFile); + } + postOffice.language.sentMessage = getString(langConfig, "sent-message", postOffice.language.sentMessage); + postOffice.language.receivedMessage = getString(langConfig, "received-message", postOffice.language.receivedMessage); + postOffice.language.gotMailMessage = getString(langConfig, "got-mail-message", postOffice.language.gotMailMessage); + postOffice.language.noPermission = getString(langConfig, "no-permission", postOffice.language.noPermission); + postOffice.language.denyAction = getString(langConfig, "deny-action", postOffice.language.denyAction); + postOffice.language.notRegistered = getString(langConfig, "not-registered", postOffice.language.notRegistered); + postOffice.language.postBoxRemoved = getString(langConfig, "post-box-removed", postOffice.language.postBoxRemoved); + postOffice.language.successfulRegistration = getString(langConfig, "successful-registration", postOffice.language.successfulRegistration); + postOffice.language.alreadyRegistered = getString(langConfig, "already-registered", postOffice.language.alreadyRegistered); + postOffice.language.postboxCreated = getString(langConfig, "postbox-created", postOffice.language.postboxCreated); + postOffice.language.removeFromConfig = getString(langConfig, "remove-from-config", postOffice.language.removeFromConfig); + postOffice.language.lookAtPostBox = getString(langConfig, "look-at-post-box", postOffice.language.lookAtPostBox); + postOffice.language.signOnBarrel = getString(langConfig, "sign-on-barrel", postOffice.language.signOnBarrel); + postOffice.language.alreadyClaimed = getString(langConfig, "already-claimed", postOffice.language.alreadyClaimed); + postOffice.language.invalidPostbox = getString(langConfig, "invalid-postbox", postOffice.language.invalidPostbox); + postOffice.language.successfullyClaimed = getString(langConfig, "successfully-claimed", postOffice.language.successfullyClaimed); + postOffice.language.modifySign = getString(langConfig, "modify-sign", postOffice.language.modifySign); + postOffice.language.unclaimedPostbox = getString(langConfig, "unclaimed-postbox", postOffice.language.unclaimedPostbox); + postOffice.language.userBanned = getString(langConfig, "user-banned", postOffice.language.userBanned); + postOffice.language.postBoxOwner = getString(langConfig, "post-box-owner", postOffice.language.postBoxOwner); + postOffice.language.claimedFor = getString(langConfig, "claimed-for", postOffice.language.claimedFor); + postOffice.language.alreadyHasPostBox = getString(langConfig, "already-has-postbox", postOffice.language.alreadyHasPostBox); + postOffice.language.notPlayedBefore = getString(langConfig, "not-played-before", postOffice.language.notPlayedBefore); + postOffice.language.pluginUpToDate = getString(langConfig, "plugin-up-to-date", postOffice.language.pluginUpToDate); } private boolean checkForMissingConfigKeys(FileConfiguration config) { - boolean keysMissing = false; - - // List of keys to check - List keysToCheck = Arrays.asList( + return checkForMissingKeys(config, Arrays.asList( "custom-barrel-name", "sign-notification", "got-mail-delay", "update-notification", "postbox-protection", "console-logs" - ); - - // Check for missing keys - for (String key : keysToCheck) { - if (!config.contains(key)) { - postOffice.getLogger().warning("Key '" + key + "' not found in the configuration file, reverting to the default."); - keysMissing = true; - } - } - return keysMissing; + )); } private boolean checkForMissingLangKeys(FileConfiguration config) { - boolean keysMissing = false; - - // List of keys to check - List keysToCheck = Arrays.asList( - "sent-message", - "received-message", - "got-mail-message", - "no-permission", "deny-action", - "not-registered", - "post-box-removed", - "successful-registration", - "already-registered", - "postbox-created", - "remove-from-config", - "look-at-post-box", - "sign-on-barrel", - "already-claimed", - "invalid-postbox", - "successfully-claimed", - "modify-sign", - "unclaimed-postbox", - "user-banned", - "post-box-owner", - "claimed-for", - "already-has-postbox", - "not-played-before", - "plugin-up-to-date" - ); - + return checkForMissingKeys(config, Arrays.asList( + "sent-message", "received-message", "got-mail-message", "no-permission", "deny-action", + "not-registered", "post-box-removed", "successful-registration", "already-registered", + "postbox-created", "remove-from-config", "look-at-post-box", "sign-on-barrel", + "already-claimed", "invalid-postbox", "successfully-claimed", "modify-sign", + "unclaimed-postbox", "user-banned", "post-box-owner", "claimed-for", + "already-has-postbox", "not-played-before", "plugin-up-to-date" + )); + } - // Check for missing keys + private boolean checkForMissingKeys(FileConfiguration config, List keysToCheck) { + boolean keysMissing = false; for (String key : keysToCheck) { if (!config.contains(key)) { - postOffice.getLogger().warning("Key '" + key + "' not found in the configuration file, reverting to the default."); + postOffice.getLogger().warning("Key '" + key + "' not found in the file, reverting to the default."); keysMissing = true; } } return keysMissing; } - private Map saveMissingLangKey(FileConfiguration config) { - Map missingKeyValues = new HashMap<>(); - - // List of keys to check - List keysToCheck = Arrays.asList( - "sent-message", - "received-message", - "got-mail-message", - "no-permission", "deny-action", - "not-registered", - "post-box-removed", - "successful-registration", - "already-registered", - "postbox-created", - "remove-from-config", - "look-at-post-box", - "sign-on-barrel", - "already-claimed", - "invalid-postbox", - "successfully-claimed", - "modify-sign", - "unclaimed-postbox", - "user-banned", - "post-box-owner", - "claimed-for", - "already-has-postbox", - "not-played-before", - "plugin-up-to-date" - ); + private Map saveMissingConfigKey(FileConfiguration config) { + return saveMissingKeys(config, Arrays.asList( + "custom-barrel-name", "sign-notification", "got-mail-delay", "update-notification", "postbox-protection", "console-logs" + )); + } - // Save existing values of missing keys - for (String key : keysToCheck) { - if (config.contains(key)) { - Object value = config.get(key); - missingKeyValues.put(key, value); - } - } - return missingKeyValues; + private Map saveMissingLangKey(FileConfiguration config) { + return saveMissingKeys(config, Arrays.asList( + "sent-message", "received-message", "got-mail-message", "no-permission", "deny-action", + "not-registered", "post-box-removed", "successful-registration", "already-registered", + "postbox-created", "remove-from-config", "look-at-post-box", "sign-on-barrel", + "already-claimed", "invalid-postbox", "successfully-claimed", "modify-sign", + "unclaimed-postbox", "user-banned", "post-box-owner", "claimed-for", + "already-has-postbox", "not-played-before", "plugin-up-to-date" + )); } - private Map saveMissingConfigKey(FileConfiguration config) { + private Map saveMissingKeys(FileConfiguration config, List keysToCheck) { Map missingKeyValues = new HashMap<>(); - - // List of keys to check - List keysToCheck = Arrays.asList( - "custom-barrel-name", "sign-notification", "got-mail-delay", "update-notification", "postbox-protection", "console-logs" - ); - - // Save existing values of missing keys for (String key : keysToCheck) { if (config.contains(key)) { - Object value = config.get(key); - missingKeyValues.put(key, value); + missingKeyValues.put(key, config.get(key)); } } return missingKeyValues; } - private void updateConfigWithMissingKeyValues(FileConfiguration config, Map missingKeyValues) { - // Update the new config with missing key values + private void updateConfigWithMissingKeyValues(FileConfiguration config, Map missingKeyValues, File destination) { for (Map.Entry entry : missingKeyValues.entrySet()) { config.set(entry.getKey(), entry.getValue()); } - - // Save the updated config - saveConfigSilently(config); + saveConfigSilently(config, destination); // Pass the correct file to save to } private void saveDefaultConfig(String resourceName, File destination) { try (InputStream resourceStream = getClass().getResourceAsStream("/" + resourceName)) { if (resourceStream != null) { Files.copy(resourceStream, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); - //getLogger().info("Default config file created successfully."); } else { - postOffice.getLogger().warning("Failed to create default config file. Resource not found."); + postOffice.getLogger().warning("Failed to create default " + resourceName + ". Resource not found."); } } catch (IOException e) { - postOffice.getLogger().log(Level.SEVERE, "Error creating default config file", e); + postOffice.getLogger().log(Level.SEVERE, "Error creating default file: " + resourceName, e); } } private String getString(FileConfiguration config, String key, String defaultValue) { - if (config.contains(key) && config.isString(key)) { - String originalValue = config.getString(key); - assert originalValue != null; - String updatedValue = originalValue.replaceAll("(?m)^\\s+|\\s+$", "") // Remove leading/trailing spaces, tabs, and indentation - .replaceAll("\\s+", " "); // Collapse multiple spaces into a single space - - // Log removal to the console if changes were made - if (!originalValue.equals(updatedValue)) { - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Extra spaces removed from key '" + key + "'"); - } - } - - - // Check for a string split across two lines - if (!originalValue.equals(updatedValue) && originalValue.contains("\n")) { - updatedValue = originalValue.replace("\n", ""); // Remove newline characters - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Indentation removed from key '" + key + "'"); - } - } - - - - // Save the updated value back to the config - config.set(key, updatedValue); - saveConfigSilently(config); // Custom method to save the configuration without logging exceptions - - return updatedValue; - } else { - // Log a warning if the key is not found or is of unexpected type - postOffice.getLogger().warning("Key '" + key + "' not found in the configuration file, reverting to the default."); - - // Set the default value in the configuration - config.set(key, defaultValue); - - // Save the configuration with the default value - saveConfigSilently(config); // Custom method to save the configuration without logging exceptions - - return defaultValue; - } + return config.getString(key, defaultValue); } private boolean getBoolean(FileConfiguration config, String key, boolean defaultValue) { - if (config.contains(key) && config.isBoolean(key)) { - boolean originalValue = config.getBoolean(key); - - // Save the updated value back to the config - config.set(key, originalValue); - saveConfigSilently(config); // Custom method to save the configuration without logging exceptions - - return originalValue; - } else { - // Log a warning if the key is not found or is of unexpected type - postOffice.getLogger().warning("Key '" + key + "' not found in the configuration file, reverting to the default."); - - // Set the default value in the configuration - config.set(key, defaultValue); - - // Save the configuration with the default value - saveConfigSilently(config); // Custom method to save the configuration without logging exceptions - - return defaultValue; - } + return config.getBoolean(key, defaultValue); } - private void saveConfigSilently(FileConfiguration config) { + private void saveConfigSilently(FileConfiguration config, File destination) { try { - config.save(new File(postOffice.getDataFolder(), "config.yml")); + config.save(destination); } catch (IOException e) { - // Log the exception or handle it as needed (e.g., printStackTrace()) - postOffice.getLogger().log(Level.SEVERE, "An error occurred while updating the config file", e); + postOffice.getLogger().log(Level.SEVERE, "An error occurred while saving the file " + destination.getName(), e); } } + // Reload and manage barrels.yml public void reloadBarrelsConfig() { if (barrelsConfigFile == null) { barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); } barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); - - // Check if the file exists, and if not, create it if (!barrelsConfigFile.exists()) { postOffice.saveResource("barrels.yml", false); } } - // Get the barrels.yml configuration public FileConfiguration getBarrelsConfig() { if (barrelsConfig == null) { reloadBarrelsConfig(); @@ -360,15 +198,13 @@ public FileConfiguration getBarrelsConfig() { return barrelsConfig; } - // Save changes to barrels.yml public void saveBarrelsConfig() { - if (barrelsConfig == null || barrelsConfigFile == null) { - return; - } - try { - barrelsConfig.save(barrelsConfigFile); - } catch (IOException e) { - postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + if (barrelsConfig != null && barrelsConfigFile != null) { + try { + barrelsConfig.save(barrelsConfigFile); + } catch (IOException e) { + postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); + } } } } From 2aef85bb614e90bfbcfe9233e0a107d3ba1bf254 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 22:21:40 +0930 Subject: [PATCH 41/45] Fixed bug preventing players placing items in a post box --- .../io/shantek/listeners/InventoryClick.java | 192 ++++++++++-------- 1 file changed, 106 insertions(+), 86 deletions(-) diff --git a/src/main/java/io/shantek/listeners/InventoryClick.java b/src/main/java/io/shantek/listeners/InventoryClick.java index ab90cf1..a25434e 100644 --- a/src/main/java/io/shantek/listeners/InventoryClick.java +++ b/src/main/java/io/shantek/listeners/InventoryClick.java @@ -1,8 +1,8 @@ package io.shantek.listeners; import io.shantek.PostOffice; -import io.shantek.functions.BarrelData; import org.bukkit.ChatColor; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.*; import org.bukkit.entity.Player; @@ -17,11 +17,10 @@ import org.bukkit.inventory.ItemStack; import java.util.Objects; -import java.util.UUID; public class InventoryClick implements Listener { - private final PostOffice postOffice; + public PostOffice postOffice; public InventoryClick(PostOffice postOffice) { this.postOffice = postOffice; @@ -33,99 +32,120 @@ public void onInventoryClick(InventoryClickEvent event) { Inventory inventory = event.getInventory(); Inventory clickedInventory = event.getClickedInventory(); - // If the clicked inventory isn't a barrel, ignore it + // If they aren't opening a barrel, ignore it if (clickedInventory == null || inventory.getType() != InventoryType.BARREL) { return; } - Block clickedBlock = Objects.requireNonNull(inventory.getLocation()).getBlock(); - if (clickedBlock.getType() != Material.BARREL) { - return; - } - - // Get the location string for the barrel - String barrelLocationString = postOffice.helpers.getBlockLocationString(clickedBlock); - - // Log barrel location - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Player is interacting with a barrel at location: " + barrelLocationString); - } - - // Fetch the barrel data from the cache - BarrelData barrelData = postOffice.helpers.barrelsCache.get(barrelLocationString); // Use barrelsCache directly - - // Check if barrel data is null (not registered) - if (barrelData == null) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.notRegistered)); - return; - } - - // Log the owner and the player interacting - UUID ownerUUID = barrelData.getOwnerUUID(); - - // Determine if the player is the owner or has permission - boolean isOwner = ownerUUID != null && ownerUUID.equals(player.getUniqueId()); - boolean hasPermissionToRemove = player.hasPermission("shantek.postoffice.removeitems"); - - // Log the result of the ownership and permission checks - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Barrel owner: " + isOwner + ". Remove permission: " + hasPermissionToRemove); - } - - // Prevent non-owners without permission from interacting with the post box - if (!isOwner && !hasPermissionToRemove) { - if (postOffice.consoleLogs) { - postOffice.getLogger().info("Player " + player.getName() + " tried to interact without permission."); - } - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); - event.setCancelled(true); - return; - } - - // Prevent double-clicking items in player's own inventory to remove items + // Prevent the player from double-clicking items in their own inventory to remove items if (event.getClick() == ClickType.DOUBLE_CLICK) { if (clickedInventory == player.getInventory() || clickedInventory.getType() == InventoryType.PLAYER) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); - event.setCancelled(true); - return; - } - } - - // Prevent item swapping using hotbar - if (event.getClick() == ClickType.NUMBER_KEY) { - ItemStack hotbarItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); - if (hotbarItem != null) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); - event.setCancelled(true); - return; + Inventory topInventory = player.getOpenInventory().getTopInventory(); + if (topInventory != null && topInventory.getType() == InventoryType.BARREL) { + Block clickedBlock = Objects.requireNonNull(topInventory.getLocation()).getBlock(); + if (clickedBlock.getType() == Material.BARREL) { + BlockState blockState = clickedBlock.getState(); + + if (blockState instanceof Barrel) { + Barrel barrel = (Barrel) blockState; + if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { + event.setCancelled(true); + return; + } + } + } + } } } - // Prevent swapping items from a barrel while having another item in hand - if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR || event.getAction() == InventoryAction.HOTBAR_SWAP) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); - event.setCancelled(true); - return; - } - - // Prevent the player from dropping items out of the postbox - if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); - event.setCancelled(true); - return; - } - - // Check if the player is adding items to an existing stack in the barrel - ItemStack[] contents = inventory.getContents(); - for (ItemStack item : contents) { - if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { - // If the player is not the owner and trying to add to an existing stack, cancel the event - if (!isOwner && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.noPermission)); - event.setCancelled(true); - return; + Block clickedBlock = Objects.requireNonNull(clickedInventory.getLocation()).getBlock(); + if (clickedBlock.getType() == Material.BARREL) { + BlockState blockState = clickedBlock.getState(); + + if (blockState instanceof Barrel) { + Barrel barrel = (Barrel) blockState; + + if (barrel.getCustomName() != null && barrel.getCustomName().equalsIgnoreCase(postOffice.customBarrelName)) { + + String ownerName = ""; + + for (BlockFace blockFace : BlockFace.values()) { + Block relativeBlock = clickedBlock.getRelative(blockFace); + + if (relativeBlock.getType().name().toUpperCase().contains("SIGN")) { + Sign sign = (Sign) relativeBlock.getState(); + Location signLoc = relativeBlock.getLocation().subtract(blockFace.getDirection()); + + if (sign.getLine(1).equalsIgnoreCase(player.getName()) && signLoc.equals(clickedBlock.getLocation())) { + ownerName = sign.getLine(1); + break; + } + } + } + + boolean isNotOwner = !ownerName.equalsIgnoreCase(player.getName()); + + // Prevent non-owners from taking items out of the postbox + if (!player.isOp() && isNotOwner && !player.hasPermission("shantek.postoffice.removeitems")) { + if (event.getAction().name().contains("PICKUP") || event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + } + + // Allow placing items into the postbox + if (event.getAction() == InventoryAction.PLACE_ALL || event.getAction() == InventoryAction.PLACE_ONE || + event.getAction() == InventoryAction.PLACE_SOME || event.getAction() == InventoryAction.SWAP_WITH_CURSOR) { + return; + } + + // Prevent item swapping using hotbar for unauthorized players + if (isNotOwner && !player.hasPermission("shantek.postoffice.removeitems")) { + if (event.getClick() == ClickType.NUMBER_KEY) { + ItemStack hotbarItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); + if (hotbarItem != null) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + } + + // Prevent players from swapping items from a barrel while having another item in hand + if (event.getAction() == InventoryAction.SWAP_WITH_CURSOR) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + + if (event.getAction() == InventoryAction.HOTBAR_SWAP) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + + // Prevent the player from dropping items out of the postbox + if (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + } + + // Check if item is already in the barrel + ItemStack[] contents = inventory.getContents(); + for (ItemStack item : contents) { + if (item != null && event.getCurrentItem() != null && item.isSimilar(event.getCurrentItem())) { + // If the player is not the owner and trying to add to an existing stack, cancel the event + if (isNotOwner && !player.hasPermission("shantek.postoffice.removeitems") && event.getAction() == InventoryAction.PLACE_ALL && item.getAmount() < item.getMaxStackSize()) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.denyAction)); + return; + } + break; + } + } } - break; } } } From 50e7fade57f818cfdf03d2a9efedb5610384a3d3 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 22:29:02 +0930 Subject: [PATCH 42/45] Project cleanup --- src/main/java/io/shantek/PostOffice.java | 1 - .../java/io/shantek/functions/Helpers.java | 2 -- .../io/shantek/functions/PluginConfig.java | 27 ------------------- .../shantek/listeners/BarrelProtection.java | 4 --- .../io/shantek/listeners/InventoryClose.java | 1 - .../io/shantek/listeners/InventoryOpen.java | 1 - 6 files changed, 36 deletions(-) diff --git a/src/main/java/io/shantek/PostOffice.java b/src/main/java/io/shantek/PostOffice.java index 3867e35..4456fbe 100644 --- a/src/main/java/io/shantek/PostOffice.java +++ b/src/main/java/io/shantek/PostOffice.java @@ -117,5 +117,4 @@ public void printInfoMessage(String message) { getLogger().info(message); // Print to the console } - } \ No newline at end of file diff --git a/src/main/java/io/shantek/functions/Helpers.java b/src/main/java/io/shantek/functions/Helpers.java index 7485876..8366991 100644 --- a/src/main/java/io/shantek/functions/Helpers.java +++ b/src/main/java/io/shantek/functions/Helpers.java @@ -135,8 +135,6 @@ public String getPlayerName(UUID uuid) { return offlinePlayer.getName(); // This may return null if the player's name is not available } - - public Block getSignForBarrel(Block barrelBlock) { String barrelLocationString = getBlockLocationString(barrelBlock); diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 82db524..0b953c1 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -180,31 +180,4 @@ private void saveConfigSilently(FileConfiguration config, File destination) { } } - // Reload and manage barrels.yml - public void reloadBarrelsConfig() { - if (barrelsConfigFile == null) { - barrelsConfigFile = new File(postOffice.getDataFolder(), "barrels.yml"); - } - barrelsConfig = YamlConfiguration.loadConfiguration(barrelsConfigFile); - if (!barrelsConfigFile.exists()) { - postOffice.saveResource("barrels.yml", false); - } - } - - public FileConfiguration getBarrelsConfig() { - if (barrelsConfig == null) { - reloadBarrelsConfig(); - } - return barrelsConfig; - } - - public void saveBarrelsConfig() { - if (barrelsConfig != null && barrelsConfigFile != null) { - try { - barrelsConfig.save(barrelsConfigFile); - } catch (IOException e) { - postOffice.getLogger().severe("Could not save barrels.yml: " + e.getMessage()); - } - } - } } diff --git a/src/main/java/io/shantek/listeners/BarrelProtection.java b/src/main/java/io/shantek/listeners/BarrelProtection.java index 63aa66f..4de2800 100644 --- a/src/main/java/io/shantek/listeners/BarrelProtection.java +++ b/src/main/java/io/shantek/listeners/BarrelProtection.java @@ -51,7 +51,6 @@ public void onSignChange(SignChangeEvent event) { } } - @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (!postOffice.postBoxProtection) { @@ -96,8 +95,6 @@ public void onBlockBreak(BlockBreakEvent event) { } } - - @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (!postOffice.postBoxProtection) { @@ -133,7 +130,6 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { } } - @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (!postOffice.postBoxProtection) { diff --git a/src/main/java/io/shantek/listeners/InventoryClose.java b/src/main/java/io/shantek/listeners/InventoryClose.java index 45d639b..f8ea36e 100644 --- a/src/main/java/io/shantek/listeners/InventoryClose.java +++ b/src/main/java/io/shantek/listeners/InventoryClose.java @@ -102,7 +102,6 @@ public void onInventoryClose(InventoryCloseEvent event) { } } - } diff --git a/src/main/java/io/shantek/listeners/InventoryOpen.java b/src/main/java/io/shantek/listeners/InventoryOpen.java index 818dadf..4966f55 100644 --- a/src/main/java/io/shantek/listeners/InventoryOpen.java +++ b/src/main/java/io/shantek/listeners/InventoryOpen.java @@ -2,7 +2,6 @@ import io.shantek.PostOffice; import org.bukkit.ChatColor; -import org.bukkit.Material; import org.bukkit.block.Barrel; import org.bukkit.block.Block; import org.bukkit.block.BlockState; From 0e87918769d96c034503a0c01f3b5d23107a735e Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 22:32:51 +0930 Subject: [PATCH 43/45] Added no permission error to register command --- src/main/java/io/shantek/functions/Commands.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index d1625f1..1c8dd41 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -203,6 +203,11 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.successfulRegistration)); return true; + } else { + // Player doesn't have permission to use the command + sender.sendMessage(ChatColor.RED + "You don't have access to this command!"); + return false; + } } else { sender.sendMessage(ChatColor.RED + "This command can only be used by players."); From 94c2a75f9a370d2318e6e8b6aef09b59ba14a018 Mon Sep 17 00:00:00 2001 From: Kris Date: Fri, 20 Sep 2024 22:33:54 +0930 Subject: [PATCH 44/45] Added no permission error to claim commands --- src/main/java/io/shantek/functions/Commands.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index 1c8dd41..bd4b104 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -294,6 +294,11 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { postOffice.helpers.saveCacheToFile(); // Save the cache to disk return true; } + else { + // Player doesn't have permission to use the command + sender.sendMessage(ChatColor.RED + "You don't have access to this command!"); + return false; + } } else if (args[0].equalsIgnoreCase("claim")) { if (sender instanceof Player) { Player player = (Player) sender; @@ -358,7 +363,9 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { postOffice.helpers.saveCacheToFile(); // Save the cache to disk return true; } else { - sender.sendMessage(ChatColor.RED + "You don't have permission to claim your own post box."); + // Player doesn't have permission to use the command + sender.sendMessage(ChatColor.RED + "You don't have access to this command!"); + return false; } } else { sender.sendMessage(ChatColor.RED + "This command can only be used by players."); From 6139db00616826fdc3c7f6aa70419305e9620a57 Mon Sep 17 00:00:00 2001 From: Kris Date: Sat, 21 Sep 2024 10:59:45 +0930 Subject: [PATCH 45/45] Added a confirmation sent to the owner when claiming on behalf of another player. --- src/main/java/io/shantek/functions/Commands.java | 7 +++++++ src/main/java/io/shantek/functions/Language.java | 1 + src/main/java/io/shantek/functions/PluginConfig.java | 5 +++-- src/main/resources/lang.yml | 4 ++++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/shantek/functions/Commands.java b/src/main/java/io/shantek/functions/Commands.java index bd4b104..d953b43 100644 --- a/src/main/java/io/shantek/functions/Commands.java +++ b/src/main/java/io/shantek/functions/Commands.java @@ -10,6 +10,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.Objects; import java.util.UUID; public class Commands implements CommandExecutor { @@ -287,10 +288,16 @@ else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { sign.update(); } + // Confirm to the person running the command that it worked player.sendMessage(ChatColor.translateAlternateColorCodes('&', postOffice.language.claimedFor .replace("%owner%", targetPlayerName))); + // Let the owner know they now have a post box, if they're online + if (targetPlayer.isOnline()) { + Objects.requireNonNull(targetPlayer.getPlayer()).sendMessage(ChatColor.translateAlternateColorCodes('&', + postOffice.language.claimedForOtherPlayer)); + } postOffice.helpers.saveCacheToFile(); // Save the cache to disk return true; } diff --git a/src/main/java/io/shantek/functions/Language.java b/src/main/java/io/shantek/functions/Language.java index 50d70f3..23dc57c 100644 --- a/src/main/java/io/shantek/functions/Language.java +++ b/src/main/java/io/shantek/functions/Language.java @@ -32,6 +32,7 @@ public Language(PostOffice postOffice) { public String claimedFor = "&a[Post Office] &aThis post box has been claimed for %owner%"; public String alreadyHasPostBox = "&a[Post Office] &4%player% already has a post box at: %location%"; public String notPlayedBefore = "&a[Post Office] &4The player %player% has not played on this server."; + public String claimedForOtherPlayer = "&a[Post Office] &aA post box has been created for you."; public String pluginUpToDate = "Your plugin is up-to-date."; public UpdateChecker updateChecker; diff --git a/src/main/java/io/shantek/functions/PluginConfig.java b/src/main/java/io/shantek/functions/PluginConfig.java index 0b953c1..44129bc 100644 --- a/src/main/java/io/shantek/functions/PluginConfig.java +++ b/src/main/java/io/shantek/functions/PluginConfig.java @@ -87,6 +87,7 @@ private void loadLangFile() { postOffice.language.claimedFor = getString(langConfig, "claimed-for", postOffice.language.claimedFor); postOffice.language.alreadyHasPostBox = getString(langConfig, "already-has-postbox", postOffice.language.alreadyHasPostBox); postOffice.language.notPlayedBefore = getString(langConfig, "not-played-before", postOffice.language.notPlayedBefore); + postOffice.language.claimedForOtherPlayer = getString(langConfig, "claimed-for-other-player", postOffice.language.claimedForOtherPlayer); postOffice.language.pluginUpToDate = getString(langConfig, "plugin-up-to-date", postOffice.language.pluginUpToDate); } @@ -103,7 +104,7 @@ private boolean checkForMissingLangKeys(FileConfiguration config) { "postbox-created", "remove-from-config", "look-at-post-box", "sign-on-barrel", "already-claimed", "invalid-postbox", "successfully-claimed", "modify-sign", "unclaimed-postbox", "user-banned", "post-box-owner", "claimed-for", - "already-has-postbox", "not-played-before", "plugin-up-to-date" + "already-has-postbox", "not-played-before", "claimed-for-other-player", "plugin-up-to-date" )); } @@ -131,7 +132,7 @@ private Map saveMissingLangKey(FileConfiguration config) { "postbox-created", "remove-from-config", "look-at-post-box", "sign-on-barrel", "already-claimed", "invalid-postbox", "successfully-claimed", "modify-sign", "unclaimed-postbox", "user-banned", "post-box-owner", "claimed-for", - "already-has-postbox", "not-played-before", "plugin-up-to-date" + "already-has-postbox", "not-played-before", "claimed-for-other-player", "plugin-up-to-date" )); } diff --git a/src/main/resources/lang.yml b/src/main/resources/lang.yml index 469eab7..0f5fb6f 100644 --- a/src/main/resources/lang.yml +++ b/src/main/resources/lang.yml @@ -83,5 +83,9 @@ already-has-postbox: "&a[Post Office] &4%player% already has a post box at: %loc # %player% is replaced with the name that is being used to register a box not-played-before: "&a[Post Office] &4The player %player% has not played on this server." +# Message shown to a player when a post box has been set up for them. Displayed when using the +# claim of other players command. Sent to the player if they are online at the time. +claimed-for-other-player: "&a[Post Office] &aA post box has been created for you." + # Message shown in the console to inform the server owner the plugin is up to date plugin-up-to-date: "Your plugin is up to date." \ No newline at end of file