From e5f31385d53b79defc5016559e5dd3c882227e39 Mon Sep 17 00:00:00 2001 From: Stijn Bannink Date: Sun, 20 Aug 2023 20:20:23 +0200 Subject: [PATCH 1/2] Started with API overhaul, still WIP --- .../sbdevelopment/v10lift/V10LiftPlugin.java | 6 + .../sbdevelopment/v10lift/api/V10LiftAPI.java | 861 +----------------- .../v10lift/api/lists/LiftQueue.java | 45 + .../v10lift/api/objects/Floor.java | 2 + .../v10lift/api/objects/Lift.java | 700 +++++++++++++- .../v10lift/api/runnables/DoorCloser.java | 11 +- .../v10lift/managers/DataManager.java | 22 - 7 files changed, 785 insertions(+), 862 deletions(-) create mode 100644 src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java diff --git a/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java b/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java index 48a6321..298c71e 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java +++ b/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java @@ -5,6 +5,7 @@ import org.bstats.bukkit.Metrics; import org.bstats.charts.SingleLineChart; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; +import tech.sbdevelopment.v10lift.api.V10LiftAPI; import tech.sbdevelopment.v10lift.commands.V10LiftCommand; import tech.sbdevelopment.v10lift.commands.V10LiftTabCompleter; import tech.sbdevelopment.v10lift.listeners.BlockBreakListener; @@ -23,6 +24,8 @@ import java.util.Collections; public class V10LiftPlugin extends JavaPlugin { @Getter private static V10LiftPlugin instance; + @Getter + private static V10LiftAPI api; private static YamlFile config; private static DBManager dbManager; @Getter @@ -36,6 +39,9 @@ public class V10LiftPlugin extends JavaPlugin { public void onEnable() { instance = this; + //Load the API + api = new V10LiftAPI(); + //Load the config config = new YamlFile("config"); config.loadDefaults(); diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java b/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java index b09ecd4..da1c8f2 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java @@ -1,24 +1,16 @@ package tech.sbdevelopment.v10lift.api; -import com.cryptomorin.xseries.XMaterial; -import org.bukkit.*; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import tech.sbdevelopment.v10lift.V10LiftPlugin; -import tech.sbdevelopment.v10lift.api.objects.*; -import tech.sbdevelopment.v10lift.api.runnables.DoorCloser; -import tech.sbdevelopment.v10lift.api.runnables.MoveLift; +import tech.sbdevelopment.v10lift.api.objects.Lift; +import tech.sbdevelopment.v10lift.api.objects.LiftSign; import tech.sbdevelopment.v10lift.managers.DataManager; -import tech.sbdevelopment.v10lift.managers.ForbiddenBlockManager; -import tech.sbdevelopment.v10lift.sbutils.LocationSerializer; -import tech.sbdevelopment.v10lift.utils.ConfigUtil; -import tech.sbdevelopment.v10lift.utils.BlockStateUtil; -import tech.sbdevelopment.v10lift.utils.DoorUtil; import javax.annotation.Nonnull; import java.util.*; @@ -27,41 +19,8 @@ import java.util.*; * The Main API class, for all the API methods */ public class V10LiftAPI { - private static V10LiftAPI instance; - - private V10LiftAPI() { - } - - public static V10LiftAPI getInstance() { - if (instance == null) instance = new V10LiftAPI(); - return instance; - } - - /* Private API methods */ - private void sortFloors(@Nonnull Lift lift) { - ArrayList> as = new ArrayList<>(lift.getFloors().entrySet()); - as.sort(Comparator.comparingInt(o -> o.getValue().getY())); - Iterator> iter = as.iterator(); - lift.getFloors().clear(); - Map.Entry e; - while (iter.hasNext()) { - e = iter.next(); - lift.getFloors().put(e.getKey(), e.getValue()); - } - } - - private void startLift(String liftName) { - if (!DataManager.containsMovingTask(liftName)) { - Lift lift = DataManager.getLift(liftName); - DataManager.addMovingTask(liftName, Bukkit.getScheduler().scheduleSyncRepeatingTask(V10LiftPlugin.getInstance(), new MoveLift(liftName, lift.getSpeed()), lift.getSpeed(), lift.getSpeed())); - } - } - - /* API methods */ - - /* - @todo Fix creating lifts in adventure not working - */ + @Getter + private static final List lifts = new ArrayList<>(); /** * Create a new Lift @@ -70,10 +29,10 @@ public class V10LiftAPI { * @param liftName The name of the lift * @return true if created, false if null or already exists */ - public boolean createLift(Player p, String liftName) { - if (p == null || liftName == null || DataManager.containsLift(liftName)) return false; + public boolean createLift(@Nonnull Player p, @Nonnull String liftName) { + if (isLift(liftName)) return false; - DataManager.addLift(liftName, new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic"))); + lifts.add(new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic"))); return true; } @@ -83,8 +42,9 @@ public class V10LiftAPI { * @param liftName The name of the lift * @return true if removed, false if null or doesn't exists */ - public boolean removeLift(String liftName) { - if (liftName == null || !DataManager.containsLift(liftName)) return false; + public boolean deleteLift(@Nonnull String liftName) { + Optional liftOpt = getLift(liftName); + if (liftOpt.isEmpty()) return false; Iterator> iter = DataManager.getEditors().entrySet().iterator(); HashSet activeEdits = new HashSet<>(); @@ -112,27 +72,27 @@ public class V10LiftAPI { DataManager.removeMovingTask(liftName); } - DataManager.removeLift(liftName); + lifts.remove(liftOpt.get()); V10LiftPlugin.getDBManager().remove(liftName); return true; } + public boolean isLift(@Nonnull String name) { + return lifts.stream().anyMatch(lift -> lift.getName().equalsIgnoreCase(name)); + } + + public Optional getLift(@Nonnull String name) { + return lifts.stream().filter(lift -> lift.getName().equalsIgnoreCase(name)).findFirst(); + } + /** * Get the name of a lift by a location (checking for cab blocks) * * @param loc The location you want to check for * @return The liftname */ - public String getLiftByLocation(Location loc) { - for (Map.Entry entry : DataManager.getLifts().entrySet()) { - for (LiftBlock block : entry.getValue().getBlocks()) { - //Check for world, x and z - if (block.getWorld().equals(Objects.requireNonNull(loc.getWorld(), "World is null at getLiftByLocation").getName()) && block.getX() == loc.getBlockX() && block.getZ() == loc.getBlockZ()) { - return entry.getKey(); - } - } - } - return null; + public Optional getLift(@Nonnull Location loc) { + return lifts.stream().filter(lift -> lift.getBlocks().stream().anyMatch(block -> block.getWorld().equals(loc.getWorld().getName()) && block.getX() == loc.getBlockX() && block.getZ() == loc.getBlockZ())).findFirst(); } /** @@ -141,13 +101,12 @@ public class V10LiftAPI { * @param liftName The name of the lift * @param newName The new name of the lift */ - public void renameLift(String liftName, String newName) { - if (liftName == null || newName == null || !DataManager.containsLift(liftName)) return; + public boolean renameLift(@Nonnull String liftName, @Nonnull String newName) { + Optional liftOpt = getLift(liftName); + if (liftOpt.isEmpty() || isLift(newName)) return false; - Lift lift = DataManager.getLift(liftName); - DataManager.removeLift(liftName); - DataManager.addLift(newName, lift); - for (LiftSign ls : lift.getSigns()) { + liftOpt.get().setName(newName); + for (LiftSign ls : liftOpt.get().getSigns()) { Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at renameLift").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); BlockState bs = block.getState(); if (!(bs instanceof Sign)) continue; @@ -155,557 +114,9 @@ public class V10LiftAPI { si.setLine(1, newName); si.update(); } - } - - /** - * Add a block to a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param liftName The name of the lift - * @param block The block - * @return 0 if added, -1 if null or doesn't exists, -2 if forbidden, -3 if already added - */ - public int addBlockToLift(String liftName, Block block) { - if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1; - Lift lift = DataManager.getLift(liftName); - return addBlockToLift(lift.getBlocks(), block); - } - - /** - * Add a block to a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param blocks The blockset - * @param block The block - * @return 0 if added, -1 if null or doesn't exists, -2 if forbidden, -3 if already added - */ - public int addBlockToLift(Set blocks, @Nonnull Block block) { - return addBlockToLift(blocks, new LiftBlock(block)); - } - - /** - * Add a block to a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param blocks The blockset - * @param block The LiftBlock - * @return 0 if added, -2 if forbidden, -3 if already added - */ - public int addBlockToLift(@Nonnull Set blocks, @Nonnull LiftBlock block) { - if (ForbiddenBlockManager.isForbidden(block.getMat())) return -2; - if (blocks.contains(block)) return -3; - blocks.add(block); - return 0; - } - - /** - * Remove a block from a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param liftName The name of the lift - * @param block The block - * @return 0 if removed, -1 if null or doesn't exists, -2 if not added - */ - public int removeBlockFromLift(String liftName, Block block) { - if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1; - Lift lift = DataManager.getLift(liftName); - LiftBlock lb = new LiftBlock(block); - if (!lift.getBlocks().contains(lb)) return -2; - lift.getBlocks().remove(lb); - return 0; - } - - /** - * Switch a block at a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param liftName The name of the lift - * @param block The block - * @return 0 if added, 1 if removed, -1 if null or doesn't exists, -2 if not added - */ - public int switchBlockAtLift(String liftName, Block block) { - if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1; - return switchBlockAtLift(DataManager.getLift(liftName).getBlocks(), block); - } - - /** - * Switch a block at a lift - * Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after! - * - * @param blocks The blockset - * @param block The block - * @return 0 if added, 1 if removed, -1 if null or doesn't exists, -2 if not added - */ - public int switchBlockAtLift(TreeSet blocks, Block block) { - if (blocks == null || block == null) return -1; - if (ForbiddenBlockManager.isForbidden(block.getType())) return -2; - LiftBlock lb = new LiftBlock(block); - if (blocks.contains(lb)) { - blocks.remove(lb); - return 1; - } - blocks.add(lb); - return 0; - } - - /** - * Sort the blocks of a lift. - * Use this after they have been modified. - * - * @param liftName The name of the lift - */ - public void sortLiftBlocks(String liftName) { - if (liftName != null && DataManager.containsLift(liftName)) { - Lift lift = DataManager.getLift(liftName); - if (lift.getWorldName() == null) lift.setWorldName(lift.getBlocks().first().getWorld()); - World world = Bukkit.getWorld(lift.getWorldName()); - if (world == null) return; - lift.setY(world.getMaxHeight()); - for (LiftBlock lb : lift.getBlocks()) { - if (lb.getY() < lift.getY()) { - lift.setY(lb.getY()); - lift.setWorldName(lb.getWorld()); - } - } - } - } - - /** - * Open the door - * - * @param liftName The name of the lift - * @return true/false - */ - public boolean openDoor(String liftName) { - if (liftName == null || !DataManager.containsLift(liftName)) return false; - - Lift lift = DataManager.getLift(liftName); - - if (lift.getQueue() != null) return false; - - Floor f = null; - for (Floor fl : lift.getFloors().values()) { - if (fl.getY() == lift.getY() && fl.getWorld().equals(lift.getWorldName())) { - f = fl; - break; - } - } - - if (f == null) return false; - - if (lift.getDoorOpen() != null && !closeDoor(liftName)) return false; - - for (LiftBlock lb : f.getDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - block.setType(Material.AIR); - } - - for (LiftBlock lb : f.getRealDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - DoorUtil.openDoor(block); - } - - lift.setDoorOpen(f); - - if (lift.isRealistic()) lift.setDoorCloser(new DoorCloser(liftName)); return true; } - /** - * Open the door - * - * @param lift The lift - * @param liftName The name of the lift - * @param f The floor - * @return true/false - */ - public boolean openDoor(Lift lift, String liftName, Floor f) { - if (lift == null || liftName == null || f == null) return false; - if (lift.getDoorOpen() != null && !closeDoor(liftName)) return false; - - for (LiftBlock lb : f.getDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - block.setType(Material.AIR); - } - - for (LiftBlock lb : f.getRealDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - DoorUtil.openDoor(block); - } - - lift.setDoorOpen(f); - - if (lift.isRealistic()) lift.setDoorCloser(new DoorCloser(liftName)); - return true; - } - - /** - * Close a lift door - * - * @param liftName The name of the lift - * @return true if door was closed, false if else. - */ - public boolean closeDoor(String liftName) { - if (liftName == null || !DataManager.containsLift(liftName)) return false; - - Lift lift = DataManager.getLift(liftName); - - boolean blocked = false; - if (lift.getDoorOpen() == null) { - return true; - } - - if (lift.isRealistic()) { - for (LiftBlock lb : lift.getDoorOpen().getDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - for (Entity ent : block.getChunk().getEntities()) { - Location loc = ent.getLocation(); - if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) { - blocked = true; - break; - } - } - if (blocked) break; - } - - for (LiftBlock lb : lift.getDoorOpen().getRealDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - for (Entity ent : block.getChunk().getEntities()) { - Location loc = ent.getLocation(); - - if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) { - blocked = true; - break; - } - } - if (blocked) break; - } - } - - if (!blocked) { - for (LiftBlock lb : lift.getDoorOpen().getDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - BlockState state = block.getState(); - state.setType(lb.getMat()); - state.update(true); - } - - for (LiftBlock lb : lift.getDoorOpen().getRealDoorBlocks()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); - DoorUtil.closeDoor(block); - } - - lift.setDoorOpen(null); - if (lift.getDoorCloser() != null) lift.getDoorCloser().stop(); - } - - return !blocked; - } - - /** - * To check if a lift has an open door. - * - * @param liftName The name of the lift - * @return true if open, false if else - */ - public boolean hasDoorOpen(String liftName) { - return (liftName != null && DataManager.containsLift(liftName)) && DataManager.getLift(liftName).getDoorOpen() != null; - } - - /** - * Adds a new floor to a lift - * - * @param liftName The name of the lift - * @param floorName The name of the floor - * @param floor The floor object - * @return 0 if added, -1 if null or doesn't exists, -2 if height is to high, -3 if floor already exists - */ - public int addFloor(String liftName, String floorName, Floor floor) { - if (liftName == null || floorName == null || floor == null || !DataManager.containsLift(liftName) || floor.getWorld() == null) - return -1; - if (floor.getY() > Objects.requireNonNull(Bukkit.getServer().getWorld(floor.getWorld()), "World is null at addNewFloor!").getMaxHeight()) - return -2; - if (floorName.length() > 13) floorName = floorName.substring(0, 13).trim(); - Lift lift = DataManager.getLift(liftName); - if (lift.getFloors().containsKey(floorName) || lift.getFloors().containsValue(floor)) return -3; - - lift.getFloors().put(floorName, floor); - sortFloors(lift); - return 0; - } - - /** - * Removes a floor from a lift - * - * @param liftName The name of the lift - * @param floorName The name of the floor - * @return true if removed, false if null or doesn't exists - */ - public boolean removeFloor(String liftName, String floorName) { - if (liftName == null || floorName == null || !DataManager.containsLift(liftName)) return false; - Lift lift = DataManager.getLift(liftName); - if (!lift.getFloors().containsKey(floorName)) return false; - - lift.getFloors().remove(floorName); - lift.getInputs().removeIf(liftBlock -> liftBlock.getFloor().equals(floorName)); - return true; - } - - /** - * Rename a floor from a lift - * - * @param liftName The name of the lift - * @param oldName The old name of the floor - * @param newName The new name of the floor - * @return 0 if renamed, -1 if null or doesn't exists, -2 if floor doesn't exists, -3 if floor already exists - */ - public int renameFloor(String liftName, String oldName, String newName) { - if (liftName == null || oldName == null || newName == null || !DataManager.containsLift(liftName)) return -1; - Lift lift = DataManager.getLift(liftName); - if (!lift.getFloors().containsKey(oldName)) return -2; - if (newName.length() > 13) newName = newName.substring(0, 13).trim(); - if (lift.getFloors().containsKey(newName)) return -3; - - Floor f = lift.getFloors().get(oldName); - lift.getFloors().remove(oldName); - lift.getFloors().put(newName, f); - sortFloors(lift); - Iterator liter = lift.getInputs().iterator(); - LiftInput lb; - ArrayList newBlocks = new ArrayList<>(); - while (liter.hasNext()) { - lb = liter.next(); - if (lb.getFloor().equals(oldName)) { - liter.remove(); - newBlocks.add(new LiftInput(lb.getWorld(), lb.getX(), lb.getY(), lb.getZ(), newName)); - } - } - newBlocks.forEach(nlb -> lift.getInputs().add(nlb)); - return 0; - } - - /** - * Check if a lift is defective - * - * @param liftName The name of the lift - * @return true/false - */ - public boolean isDefective(String liftName) { - if (liftName == null || !DataManager.containsLift(liftName)) return false; - return DataManager.getLift(liftName).isDefective(); - } - - /** - * Set a lift to (not) defective - * - * @param liftName The name of the lift - * @param state true/false - * @return 0 if set, -1 if null or doesn't exists, -2 if same state, -3 if no signs, -4 if wrong sign - */ - public int setDefective(String liftName, boolean state) { - if (liftName == null || !DataManager.containsLift(liftName)) return -1; - Lift lift = DataManager.getLift(liftName); - boolean oldState = lift.isDefective(); - if (oldState == state) return -2; - lift.setDefective(state); - if (state) { - //SET DEFECTIVE - //Update sign - for (LiftSign ls : lift.getSigns()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); - BlockState bs = block.getState(); - if (!(bs instanceof Sign)) { - Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation())); - return -4; - } - - Sign s = (Sign) bs; - ls.setOldText(s.getLine(3)); - s.setLine(3, ConfigUtil.getConfigText("DefectText")); - s.update(); - } - - //Update all cab signs - for (LiftBlock lb : lift.getBlocks()) { - BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); - if (!(bs instanceof Sign)) continue; - - Sign s = (Sign) bs; - lift.setSignText(s.getLine(3)); - s.setLine(3, ConfigUtil.getConfigText("DefectText")); - s.update(); - } - } else { - - //Update sign - for (LiftSign ls : lift.getSigns()) { - Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); - BlockState bs = block.getState(); - if (!(bs instanceof Sign)) { - Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation())); - return -4; - } - - Sign s = (Sign) bs; - s.setLine(3, ls.getOldText()); - ls.setOldText(null); - s.update(); - } - - //Update all cab signs - for (LiftBlock lb : lift.getBlocks()) { - BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); - if (!(bs instanceof Sign)) continue; - - Sign s = (Sign) bs; - s.setLine(3, lift.getSignText()); - s.update(); - } - lift.setSignText(null); - } - return 0; - } - - /** - * Get the userWhitelist of a lift - * - * @param liftName The name of the lift - * @param floorName The name of the floor - * @return list with UUIDs of the players - */ - public HashSet getUserWhitelist(String liftName, String floorName) { - HashSet ret = new HashSet<>(); - if (liftName != null && floorName != null && DataManager.containsLift(liftName)) { - Lift lift = DataManager.getLift(liftName); - if (lift.getFloors().containsKey(floorName)) { - ret = lift.getFloors().get(floorName).getUserWhitelist(); - } - } - return ret; - } - - /** - * Get the groupWhitelist of a lift - * - * @param liftName The name of the lift - * @param floorName The name of the floor - * @return list with groupnames - */ - public HashSet getGroupWhitelist(String liftName, String floorName) { - HashSet ret = new HashSet<>(); - if (liftName != null && floorName != null && DataManager.containsLift(liftName)) { - Lift lift = DataManager.getLift(liftName); - if (lift.getFloors().containsKey(floorName)) { - ret = lift.getFloors().get(floorName).getGroupWhitelist(); - } - } - return ret; - } - - /** - * Check if a lift is offline - * - * @param liftName The name of the lift - * @return true/false - */ - public boolean isOffline(String liftName) { - if (liftName == null || !DataManager.containsLift(liftName)) return false; - return DataManager.getLift(liftName).isOffline(); - } - - /** - * Set a lift to (not) offline - * - * @param liftName The name of the lift - * @param state true/false - * @return 0 if set, -1 if null or doesn't exists, -2 if same state - */ - public int setOffline(String liftName, boolean state) { - if (liftName == null || !DataManager.containsLift(liftName)) return -1; - Lift lift = DataManager.getLift(liftName); - boolean oldState = lift.isOffline(); - if (oldState == state) return -2; - lift.setOffline(state); - Iterator liter = lift.getSigns().iterator(); - BlockState bs; - Sign sign; - if (state) { - for (LiftBlock lb : lift.getBlocks()) { - bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); - if (!(bs instanceof Sign)) continue; - sign = (Sign) bs; - if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue; - sign.setLine(3, ConfigUtil.getConfigText("DisabledText")); - sign.update(); - } - - while (liter.hasNext()) { - LiftSign ls = liter.next(); - bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState(); - if (!(bs instanceof Sign)) { - Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation())); - liter.remove(); - continue; - } - sign = (Sign) bs; - ls.setOldText(sign.getLine(3)); - sign.setLine(3, ConfigUtil.getConfigText("DisabledText")); - sign.update(); - } - } else { - for (LiftBlock lb : lift.getBlocks()) { - bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); - if (!(bs instanceof Sign)) continue; - sign = (Sign) bs; - if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue; - sign.setLine(3, ""); - sign.update(); - } - - while (liter.hasNext()) { - LiftSign ls = liter.next(); - bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState(); - if (!(bs instanceof Sign)) { - Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation())); - liter.remove(); - continue; - } - sign = (Sign) bs; - sign.setLine(3, ls.getOldText()); - sign.update(); - ls.setOldText(null); - } - } - return 0; - } - - /** - * Check if a lift contains the block as rope - * - * @param liftName The name of the lift - * @param block The block - * @return true/false - */ - public boolean containsRope(String liftName, Block block) { - if (liftName == null || block == null || !DataManager.containsLift(liftName)) return false; - - Lift lift = DataManager.getLift(liftName); - if (lift.getRopes().isEmpty()) return false; - - String world = block.getWorld().getName(); - int x = block.getX(); - int y = block.getY(); - int z = block.getZ(); - - for (LiftRope rope : lift.getRopes()) { - if (x != rope.getX() || z != rope.getZ()) continue; - if (y >= rope.getMinY() && y <= rope.getMaxY()) { - return true; - } - } - return false; - } - /** * Check if a block is a rope * @@ -713,218 +124,6 @@ public class V10LiftAPI { * @return true/false */ public boolean isRope(Block b) { - for (String lift : DataManager.getLifts().keySet()) { - if (containsRope(lift, b)) return true; - } - return false; - } - - /** - * Send info about a lift to a player - * - * @param sender Where you want to send it to - * @param liftName The name of the lift - */ - public void sendLiftInfo(CommandSender sender, String liftName) { - sendLiftInfo(sender, liftName, DataManager.getLift(liftName)); - } - - /** - * Send info about a lift to a player - * - * @param ent Where you want to send it to - * @param liftName The name of the lift - * @param lift The lift - */ - public void sendLiftInfo(@Nonnull CommandSender ent, String liftName, @Nonnull Lift lift) { - - ent.sendMessage(ChatColor.GOLD + "Elevator: " + ChatColor.YELLOW + liftName); - ent.sendMessage(ChatColor.GOLD + "Settings:"); - ent.sendMessage(ChatColor.GREEN + " Speed: " + ChatColor.YELLOW + lift.getSpeed()); - ent.sendMessage(ChatColor.GREEN + " Realistic Mode: " + ChatColor.YELLOW + lift.isRealistic()); - ent.sendMessage(ChatColor.GREEN + " Malfunction: " + ChatColor.YELLOW + lift.isDefective()); - ent.sendMessage(ChatColor.GOLD + "Floors:"); - if (lift.getFloors().isEmpty()) { - ent.sendMessage(ChatColor.RED + "None."); - } else { - for (Map.Entry entry : lift.getFloors().entrySet()) { - ent.sendMessage(ChatColor.GREEN + " " + entry.getKey() + ":"); - Floor f = entry.getValue(); - ent.sendMessage(ChatColor.YELLOW + " World: " + ChatColor.GREEN + f.getWorld()); - ent.sendMessage(ChatColor.YELLOW + " Height: " + ChatColor.GREEN + f.getY()); - ent.sendMessage(ChatColor.YELLOW + " Whitelist:"); - if (f.getUserWhitelist().isEmpty() && f.getGroupWhitelist().isEmpty()) { - ent.sendMessage(ChatColor.GOLD + " None."); - } else { - ChatColor color = ChatColor.DARK_PURPLE; - Iterator iter = f.getUserWhitelist().iterator(); - Iterator iter2 = f.getGroupWhitelist().iterator(); - StringBuilder sb = new StringBuilder(); - sb.append(" ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName()); - while (iter.hasNext()) { - if (color == ChatColor.DARK_PURPLE) { - color = ChatColor.LIGHT_PURPLE; - } else { - color = ChatColor.DARK_PURPLE; - } - sb.append(ChatColor.AQUA).append(", ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName()); - } - while (iter2.hasNext()) { - if (color == ChatColor.DARK_PURPLE) { - color = ChatColor.LIGHT_PURPLE; - } else { - color = ChatColor.DARK_PURPLE; - } - sb.append(ChatColor.AQUA).append(", ").append(color).append("Group: ").append(iter2.next()); - } - ent.sendMessage(sb.toString()); - } - } - } - } - - /** - * Add a rope to a lift - * - * @param lift The name of the lift - * @param world The world - * @param x The x-pos - * @param minY The min y-pos - * @param maxY The max y-pos - * @param z The z-pos - * @return 0 if added, -1 if null or doesn't exists, -2 if not same mat, -3 if already a rope, -4 if forbidden material - */ - public int addRope(String lift, World world, int x, int minY, int maxY, int z) { - if (lift == null || !DataManager.containsLift(lift) || world == null) return -1; - - //minY = maxY, so reverse - if (minY > maxY) { - int tempY = minY; - minY = maxY; - maxY = tempY; - } - - Block block = world.getBlockAt(x, minY, z); - if (isRope(block)) return -3; - Material mat = block.getType(); - if (ForbiddenBlockManager.isForbidden(mat)) return -4; - - for (int i = minY + 1; i <= maxY; i++) { - block = world.getBlockAt(x, i, z); - if (isRope(block)) return -3; - if (block.getType() != mat) return -2; - } - - LiftRope rope = new LiftRope(block, minY, maxY); - DataManager.getLift(lift).getRopes().add(rope); - - return 0; - } - - /** - * Remove a rope from a lift - * - * @param lift The name of the lift - * @param block The block - * @return true/false - */ - public boolean removeRope(String lift, Block block) { - if (lift == null || block == null || !DataManager.containsLift(lift) || !containsRope(lift, block)) - return false; - - String world = block.getWorld().getName(); - int x = block.getX(); - int y = block.getY(); - int z = block.getZ(); - Iterator riter = DataManager.getLift(lift).getRopes().iterator(); - while (riter.hasNext()) { - LiftRope rope = riter.next(); - if (x != rope.getX() || z != rope.getZ()) continue; - if (world.equals(rope.getWorld())) { - if (y >= rope.getMinY() && y <= rope.getMaxY()) { - riter.remove(); - return true; - } - } - } - return false; - } - - /** - * Set the queue of a lift - * - * @param liftName The name of the lift - * @param queue The queue - * @return true/false - */ - public boolean setQueue(String liftName, LinkedHashMap queue) { - if (liftName == null || queue == null || !DataManager.containsLift(liftName)) return false; - - Lift lift = DataManager.getLift(liftName); - lift.setQueue(new LinkedHashMap<>()); - for (Map.Entry e : queue.entrySet()) { - addToQueue(liftName, e.getValue(), e.getKey()); - } - return true; - } - - /** - * Add a location to the queue - * - * @param lift The name of the lift - * @param y The y-pos - * @param world The world - * @return true/false - */ - public boolean addToQueue(String lift, int y, World world) { - return addToQueue(lift, y, world, null); - } - - /** - * Add a location to the queue - * - * @param lift The name of the lift - * @param y The y-pos - * @param world The world - * @param floorName The name of the flor - * @return true/false - */ - public boolean addToQueue(String lift, int y, @Nonnull World world, String floorName) { - return addToQueue(lift, new Floor(y, world.getName()), floorName); - } - - /** - * Add a location to the queue - * - * @param lift The name of the lift - * @param floor The {@link Floor} - * @param floorName The name of the flor - * @return true/false - */ - public boolean addToQueue(String lift, Floor floor, String floorName) { - if (lift == null || floor == null || !DataManager.containsLift(lift)) return false; - - Lift l = DataManager.getLift(lift); - if (l.getQueue() == null) { - l.setQueue(new LinkedHashMap<>()); - } - - if (!l.getQueue().containsValue(floor)) { - if (floorName == null) { - floorName = ChatColor.MAGIC + "-----"; - for (Map.Entry e : l.getFloors().entrySet()) { - if (e.getValue().equals(floor)) { - floorName = e.getKey(); - floor = e.getValue(); - break; - } - } - } - - l.getQueue().put(floorName, floor); - startLift(lift); - return true; - } - return false; + return getLifts().stream().anyMatch(lift -> lift.containsRope(b)); } } diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java b/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java new file mode 100644 index 0000000..3e91c43 --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java @@ -0,0 +1,45 @@ +package tech.sbdevelopment.v10lift.api.lists; + +import lombok.Setter; +import tech.sbdevelopment.v10lift.api.objects.Floor; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class LiftQueue { + private final LinkedHashMap queue = new LinkedHashMap<>(); + + @Setter + private LiftQueueListener listener; + + public interface LiftQueueListener { + void onQueueChange(); + } + + public void requestFloor(String floorName, Floor floor) { + if (!queue.containsKey(floorName)) { + queue.put(floorName, floor); + + if (listener != null) { + listener.onQueueChange(); + } + } + } + + public boolean hasRequests() { + return !queue.isEmpty(); + } + + public String getNextFloor(String currentFloor, boolean movingUp) { + if (!hasRequests()) return null; + + String nextFloor = currentFloor; + for (Map.Entry entry : queue.entrySet()) { + if ((movingUp && entry.getValue().getY() > entry.getValue().getY()) || (!movingUp && entry.getValue().getY() < entry.getValue().getY())) { + nextFloor = entry.getKey(); + } + } + + return nextFloor; + } +} diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Floor.java b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Floor.java index 38ad25c..cb55a41 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Floor.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Floor.java @@ -5,6 +5,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashSet; import java.util.UUID; @@ -17,6 +18,7 @@ import java.util.UUID; @NoArgsConstructor @ToString public class Floor { + @Nonnull private String world; private int y; private ArrayList doorBlocks = new ArrayList<>(); diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java index e1d3874..e7e6963 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java @@ -4,8 +4,21 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import tech.sbdevelopment.v10lift.V10LiftPlugin; +import tech.sbdevelopment.v10lift.api.lists.LiftQueue; import tech.sbdevelopment.v10lift.api.runnables.DoorCloser; +import tech.sbdevelopment.v10lift.managers.ForbiddenBlockManager; +import tech.sbdevelopment.v10lift.sbutils.LocationSerializer; +import tech.sbdevelopment.v10lift.utils.ConfigUtil; +import tech.sbdevelopment.v10lift.utils.DoorUtil; +import javax.annotation.Nonnull; import java.util.*; /** @@ -15,6 +28,8 @@ import java.util.*; @NoArgsConstructor @ToString public class Lift { + @Setter + private String name; @Setter private String worldName; @Setter @@ -25,18 +40,15 @@ public class Lift { private final HashSet signs = new HashSet<>(); private final HashSet inputs = new HashSet<>(); private final HashSet offlineInputs = new HashSet<>(); - @Setter - private LinkedHashMap queue = null; + private final LiftQueue queue = new LiftQueue(); private final HashSet ropes = new HashSet<>(); @Setter private int speed; @Setter private boolean realistic; - @Setter private boolean offline = false; @Setter private boolean sound = true; - @Setter private boolean defective = false; @Setter private String signText = null; @@ -74,4 +86,684 @@ public class Lift { this.speed = speed; this.realistic = realistic; } + + /** + * Add a block to a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param block The block + * @return 0 if added, -2 if forbidden, -3 if already added + */ + public int addBlock(@Nonnull Block block) { + return addBlock(getBlocks(), block); + } + + /** + * Add a block to a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param blocks The blockset + * @param block The block + * @return 0 if added, -2 if forbidden, -3 if already added + */ + public int addBlock(@Nonnull Set blocks, @Nonnull Block block) { + return addBlock(blocks, new LiftBlock(block)); + } + + /** + * Add a block to a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param blocks The blockset + * @param block The LiftBlock + * @return 0 if added, -2 if forbidden, -3 if already added + */ + public int addBlock(@Nonnull Set blocks, @Nonnull LiftBlock block) { + if (ForbiddenBlockManager.isForbidden(block.getMat())) return -2; + if (blocks.contains(block)) return -3; + blocks.add(block); + return 0; + } + + /** + * Remove a block from a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param block The block + * @return true if removed, false if doesn't exists + */ + public boolean removeBlock(@Nonnull Block block) { + LiftBlock lb = new LiftBlock(block); + if (!getBlocks().contains(lb)) return false; + getBlocks().remove(lb); + return true; + } + + /** + * Switch a block at a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param block The block + * @return 0 if added, 1 if removed, -2 if not added + */ + public int switchBlock(@Nonnull Block block) { + return switchBlock(getBlocks(), block); + } + + /** + * Switch a block at a lift + * Use {@link Lift#sortLiftBlocks()} after! + * + * @param blocks The blockset + * @param block The block + * @return 0 if added, 1 if removed, -2 if not added + */ + public int switchBlock(@Nonnull TreeSet blocks, @Nonnull Block block) { + if (ForbiddenBlockManager.isForbidden(block.getType())) return -2; + LiftBlock lb = new LiftBlock(block); + if (blocks.contains(lb)) { + blocks.remove(lb); + return 1; + } + blocks.add(lb); + return 0; + } + + /** + * Sort the blocks of a lift. + * Use this after they have been modified. + */ + public void sortLiftBlocks() { + if (getWorldName() == null) setWorldName(getBlocks().first().getWorld()); + World world = Bukkit.getWorld(getWorldName()); + if (world == null) return; + setY(world.getMaxHeight()); + for (LiftBlock lb : getBlocks()) { + if (lb.getY() < getY()) { + setY(lb.getY()); + setWorldName(lb.getWorld()); + } + } + } + + /** + * Open the door + * + * @return true/false + */ + public boolean openDoor() { + if (getQueue() != null) return false; + + Floor f = null; + for (Floor fl : getFloors().values()) { + if (fl.getY() == getY() && fl.getWorld().equals(getWorldName())) { + f = fl; + break; + } + } + + if (f == null) return false; + + if (getDoorOpen() != null && !closeDoor()) return false; + + for (LiftBlock lb : f.getDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + block.setType(Material.AIR); + } + + for (LiftBlock lb : f.getRealDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + DoorUtil.openDoor(block); + } + + setDoorOpen(f); + + if (isRealistic()) setDoorCloser(new DoorCloser(this)); + return true; + } + + /** + * Open the door + * + * @param f The floor + * @return true/false + */ + public boolean openDoor(@Nonnull Floor f) { + if (getDoorOpen() != null && !closeDoor()) return false; + + for (LiftBlock lb : f.getDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + block.setType(Material.AIR); + } + + for (LiftBlock lb : f.getRealDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + DoorUtil.openDoor(block); + } + + setDoorOpen(f); + + if (isRealistic()) setDoorCloser(new DoorCloser(this)); + return true; + } + + /** + * Close a lift door + * + * @return true if door was closed, false if else. + */ + public boolean closeDoor() { + boolean blocked = false; + if (getDoorOpen() == null) { + return true; + } + + if (isRealistic()) { + for (LiftBlock lb : getDoorOpen().getDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + for (Entity ent : block.getChunk().getEntities()) { + Location loc = ent.getLocation(); + if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) { + blocked = true; + break; + } + } + if (blocked) break; + } + + for (LiftBlock lb : getDoorOpen().getRealDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + for (Entity ent : block.getChunk().getEntities()) { + Location loc = ent.getLocation(); + + if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) { + blocked = true; + break; + } + } + if (blocked) break; + } + } + + if (!blocked) { + for (LiftBlock lb : getDoorOpen().getDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + BlockState state = block.getState(); + state.setType(lb.getMat()); + state.update(true); + } + + for (LiftBlock lb : getDoorOpen().getRealDoorBlocks()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ()); + DoorUtil.closeDoor(block); + } + + setDoorOpen(null); + if (getDoorCloser() != null) getDoorCloser().stop(); + } + + return !blocked; + } + + /** + * To check if a lift has an open door. + * + * @return true if open, false if else + */ + public boolean hasDoorOpen() { + return getDoorOpen() != null; + } + + private void sortFloors() { + ArrayList> as = new ArrayList<>(getFloors().entrySet()); + as.sort(Comparator.comparingInt(o -> o.getValue().getY())); + Iterator> iter = as.iterator(); + getFloors().clear(); + Map.Entry e; + while (iter.hasNext()) { + e = iter.next(); + getFloors().put(e.getKey(), e.getValue()); + } + } + + /** + * Adds a new floor to a lift + * + * @param floorName The name of the floor + * @param floor The floor object + * @return 0 if added, -1 if world doesn't exist, -2 if height is too high, -3 if floor already exists + */ + public int addFloor(@Nonnull String floorName, @Nonnull Floor floor) { + if (Bukkit.getWorld(floor.getWorld()) == null) return -1; + if (floor.getY() > Bukkit.getServer().getWorld(floor.getWorld()).getMaxHeight()) + return -2; + if (floorName.length() > 13) floorName = floorName.substring(0, 13).trim(); + if (getFloors().containsKey(floorName) || getFloors().containsValue(floor)) return -3; + + getFloors().put(floorName, floor); + sortFloors(); + return 0; + } + + /** + * Removes a floor from a lift + * + * @param floorName The name of the floor + * @return true if removed, false if null or doesn't exists + */ + public boolean removeFloor(@Nonnull String floorName) { + if (!getFloors().containsKey(floorName)) return false; + + getFloors().remove(floorName); + getInputs().removeIf(liftBlock -> liftBlock.getFloor().equals(floorName)); + return true; + } + + /** + * Rename a floor from a lift + * + * @param oldName The old name of the floor + * @param newName The new name of the floor + * @return 0 if renamed, -2 if floor doesn't exists, -3 if floor already exists + */ + public int renameFloor(@Nonnull String oldName, @Nonnull String newName) { + if (!getFloors().containsKey(oldName)) return -2; + if (newName.length() > 13) newName = newName.substring(0, 13).trim(); + if (getFloors().containsKey(newName)) return -3; + + Floor f = getFloors().get(oldName); + getFloors().remove(oldName); + getFloors().put(newName, f); + sortFloors(); + Iterator liter = getInputs().iterator(); + LiftInput lb; + ArrayList newBlocks = new ArrayList<>(); + while (liter.hasNext()) { + lb = liter.next(); + if (lb.getFloor().equals(oldName)) { + liter.remove(); + newBlocks.add(new LiftInput(lb.getWorld(), lb.getX(), lb.getY(), lb.getZ(), newName)); + } + } + newBlocks.forEach(nlb -> getInputs().add(nlb)); + return 0; + } + + /** + * Set a lift to (not) defective + * + * @param state true/false + * @return 0 if set, -2 if same state, -3 if no signs, -4 if wrong sign + */ + public int setDefective(boolean state) { + if (defective == state) return -2; + defective = state; + + if (state) { + //SET DEFECTIVE + //Update sign + for (LiftSign ls : getSigns()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); + BlockState bs = block.getState(); + if (!(bs instanceof Sign)) { + Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation())); + return -4; + } + + Sign s = (Sign) bs; + ls.setOldText(s.getLine(3)); + s.setLine(3, ConfigUtil.getConfigText("DefectText")); + s.update(); + } + + //Update all cab signs + for (LiftBlock lb : getBlocks()) { + BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); + if (!(bs instanceof Sign)) continue; + + Sign s = (Sign) bs; + setSignText(s.getLine(3)); + s.setLine(3, ConfigUtil.getConfigText("DefectText")); + s.update(); + } + } else { + + //Update sign + for (LiftSign ls : getSigns()) { + Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); + BlockState bs = block.getState(); + if (!(bs instanceof Sign)) { + Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation())); + return -4; + } + + Sign s = (Sign) bs; + s.setLine(3, ls.getOldText()); + ls.setOldText(null); + s.update(); + } + + //Update all cab signs + for (LiftBlock lb : getBlocks()) { + BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); + if (!(bs instanceof Sign)) continue; + + Sign s = (Sign) bs; + s.setLine(3, getSignText()); + s.update(); + } + setSignText(null); + } + return 0; + } + + /** + * Get the userWhitelist of a lift + * + * @param floorName The name of the floor + * @return set with UUIDs of the players + */ + public HashSet getUserWhitelist(@Nonnull String floorName) { + HashSet ret = new HashSet<>(); + if (getFloors().containsKey(floorName)) { + ret = getFloors().get(floorName).getUserWhitelist(); + } + return ret; + } + + /** + * Get the groupWhitelist of a lift + * + * @param floorName The name of the floor + * @return set with groupnames + */ + public HashSet getGroupWhitelist(@Nonnull String floorName) { + HashSet ret = new HashSet<>(); + if (getFloors().containsKey(floorName)) { + ret = getFloors().get(floorName).getGroupWhitelist(); + } + return ret; + } + + /** + * Set a lift to (not) offline + * + * @param state true/false + * @return 0 if set, -2 if same state + */ + public int setOffline(boolean state) { + if (offline == state) return -2; + offline = state; + Iterator liter = getSigns().iterator(); + BlockState bs; + Sign sign; + if (state) { + for (LiftBlock lb : getBlocks()) { + bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); + if (!(bs instanceof Sign)) continue; + sign = (Sign) bs; + if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue; + sign.setLine(3, ConfigUtil.getConfigText("DisabledText")); + sign.update(); + } + + while (liter.hasNext()) { + LiftSign ls = liter.next(); + bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState(); + if (!(bs instanceof Sign)) { + Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation())); + liter.remove(); + continue; + } + sign = (Sign) bs; + ls.setOldText(sign.getLine(3)); + sign.setLine(3, ConfigUtil.getConfigText("DisabledText")); + sign.update(); + } + } else { + for (LiftBlock lb : getBlocks()) { + bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState(); + if (!(bs instanceof Sign)) continue; + sign = (Sign) bs; + if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue; + sign.setLine(3, ""); + sign.update(); + } + + while (liter.hasNext()) { + LiftSign ls = liter.next(); + bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState(); + if (!(bs instanceof Sign)) { + Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation())); + liter.remove(); + continue; + } + sign = (Sign) bs; + sign.setLine(3, ls.getOldText()); + sign.update(); + ls.setOldText(null); + } + } + return 0; + } + + /** + * Check if a lift contains the block as rope + * + * @param block The block + * @return true/false + */ + public boolean containsRope(@Nonnull Block block) { + if (getRopes().isEmpty()) return false; + + int x = block.getX(); + int y = block.getY(); + int z = block.getZ(); + for (LiftRope rope : getRopes()) { + if (x != rope.getX() || z != rope.getZ()) continue; + if (y >= rope.getMinY() && y <= rope.getMaxY()) { + return true; + } + } + return false; + } + + /** + * Send info about a lift to a player + * + * @param ent Where you want to send it to + */ + public void sendInfo(@Nonnull CommandSender ent) { + ent.sendMessage(ChatColor.GOLD + "Elevator: " + ChatColor.YELLOW + name); + ent.sendMessage(ChatColor.GOLD + "Settings:"); + ent.sendMessage(ChatColor.GREEN + " Speed: " + ChatColor.YELLOW + getSpeed()); + ent.sendMessage(ChatColor.GREEN + " Realistic Mode: " + ChatColor.YELLOW + isRealistic()); + ent.sendMessage(ChatColor.GREEN + " Malfunction: " + ChatColor.YELLOW + isDefective()); + ent.sendMessage(ChatColor.GOLD + "Floors:"); + if (getFloors().isEmpty()) { + ent.sendMessage(ChatColor.RED + "None."); + } else { + for (Map.Entry entry : getFloors().entrySet()) { + ent.sendMessage(ChatColor.GREEN + " " + entry.getKey() + ":"); + Floor f = entry.getValue(); + ent.sendMessage(ChatColor.YELLOW + " World: " + ChatColor.GREEN + f.getWorld()); + ent.sendMessage(ChatColor.YELLOW + " Height: " + ChatColor.GREEN + f.getY()); + ent.sendMessage(ChatColor.YELLOW + " Whitelist:"); + if (f.getUserWhitelist().isEmpty() && f.getGroupWhitelist().isEmpty()) { + ent.sendMessage(ChatColor.GOLD + " None."); + } else { + ChatColor color = ChatColor.DARK_PURPLE; + Iterator iter = f.getUserWhitelist().iterator(); + Iterator iter2 = f.getGroupWhitelist().iterator(); + StringBuilder sb = new StringBuilder(); + sb.append(" ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName()); + while (iter.hasNext()) { + if (color == ChatColor.DARK_PURPLE) { + color = ChatColor.LIGHT_PURPLE; + } else { + color = ChatColor.DARK_PURPLE; + } + sb.append(ChatColor.AQUA).append(", ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName()); + } + while (iter2.hasNext()) { + if (color == ChatColor.DARK_PURPLE) { + color = ChatColor.LIGHT_PURPLE; + } else { + color = ChatColor.DARK_PURPLE; + } + sb.append(ChatColor.AQUA).append(", ").append(color).append("Group: ").append(iter2.next()); + } + ent.sendMessage(sb.toString()); + } + } + } + } + + /** + * Add a rope to a lift + * + * @param world The world + * @param x The x-pos + * @param minY The min y-pos + * @param maxY The max y-pos + * @param z The z-pos + * @return 0 if added, -2 if not same mat, -3 if already a rope, -4 if forbidden material + */ + public int addRope(@Nonnull World world, int x, int minY, int maxY, int z) { + //minY = maxY, so reverse + if (minY > maxY) { + int tempY = minY; + minY = maxY; + maxY = tempY; + } + + Block block = world.getBlockAt(x, minY, z); + if (V10LiftPlugin.getApi().isRope(block)) return -3; + Material mat = block.getType(); + if (ForbiddenBlockManager.isForbidden(mat)) return -4; + + for (int i = minY + 1; i <= maxY; i++) { + block = world.getBlockAt(x, i, z); + if (V10LiftPlugin.getApi().isRope(block)) return -3; + if (block.getType() != mat) return -2; + } + + LiftRope rope = new LiftRope(block, minY, maxY); + getRopes().add(rope); + + return 0; + } + + /** + * Remove a rope from a lift + * + * @param block The block + * @return true/false + */ + public boolean removeRope(@Nonnull Block block) { + if (!containsRope(block)) + return false; + + String world = block.getWorld().getName(); + int x = block.getX(); + int y = block.getY(); + int z = block.getZ(); + Iterator riter = getRopes().iterator(); + while (riter.hasNext()) { + LiftRope rope = riter.next(); + if (x != rope.getX() || z != rope.getZ()) continue; + if (world.equals(rope.getWorld())) { + if (y >= rope.getMinY() && y <= rope.getMaxY()) { + riter.remove(); + return true; + } + } + } + return false; + } + +// /** +// * Set the queue of a lift +// * +// * @param liftName The name of the lift +// * @param queue The queue +// * @return true/false +// */ +// public boolean setQueue(String liftName, LinkedHashMap queue) { +// if (liftName == null || queue == null || !DataManager.containsLift(liftName)) return false; +// +// Lift lift = DataManager.getLift(liftName); +// lift.setQueue(new LinkedHashMap<>()); +// for (Map.Entry e : queue.entrySet()) { +// addToQueue(liftName, e.getValue(), e.getKey()); +// } +// return true; +// } +// +// /** +// * Add a location to the queue +// * +// * @param lift The name of the lift +// * @param y The y-pos +// * @param world The world +// * @return true/false +// */ +// public boolean addToQueue(String lift, int y, World world) { +// return addToQueue(lift, y, world, null); +// } +// +// /** +// * Add a location to the queue +// * +// * @param lift The name of the lift +// * @param y The y-pos +// * @param world The world +// * @param floorName The name of the flor +// * @return true/false +// */ +// public boolean addToQueue(String lift, int y, @Nonnull World world, String floorName) { +// return addToQueue(lift, new Floor(y, world.getName()), floorName); +// } +// +// /** +// * Add a location to the queue +// * +// * @param lift The name of the lift +// * @param floor The {@link Floor} +// * @param floorName The name of the flor +// * @return true/false +// */ +// public boolean addToQueue(String lift, Floor floor, String floorName) { +// if (lift == null || floor == null || !DataManager.containsLift(lift)) return false; +// +// Lift l = DataManager.getLift(lift); +// if (l.getQueue() == null) { +// l.setQueue(new LinkedHashMap<>()); +// } +// +// if (!l.getQueue().containsValue(floor)) { +// if (floorName == null) { +// floorName = ChatColor.MAGIC + "-----"; +// for (Map.Entry e : l.getFloors().entrySet()) { +// if (e.getValue().equals(floor)) { +// floorName = e.getKey(); +// floor = e.getValue(); +// break; +// } +// } +// } +// +// l.getQueue().put(floorName, floor); +// startLift(lift); +// return true; +// } +// return false; +// } +// +// private void start(String liftName) { +// if (!DataManager.containsMovingTask(liftName)) { +// Lift lift = DataManager.getLift(liftName); +// DataManager.addMovingTask(liftName, Bukkit.getScheduler().scheduleSyncRepeatingTask(V10LiftPlugin.getInstance(), new MoveLift(liftName, lift.getSpeed()), lift.getSpeed(), lift.getSpeed())); +// } +// } } diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/runnables/DoorCloser.java b/src/main/java/tech/sbdevelopment/v10lift/api/runnables/DoorCloser.java index b07440b..0e31e07 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/runnables/DoorCloser.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/runnables/DoorCloser.java @@ -3,17 +3,18 @@ package tech.sbdevelopment.v10lift.api.runnables; import org.bukkit.Bukkit; import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.api.V10LiftAPI; +import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.managers.DataManager; /** * The DoorCloser runnable, used for checking if the door can be closed. */ public class DoorCloser implements Runnable { - private final String liftName; + private final Lift lift; private final int taskID; - public DoorCloser(String liftName) { - this.liftName = liftName; + public DoorCloser(Lift lift) { + this.lift = lift; final long doorCloseTime = V10LiftPlugin.getSConfig().getFile().getLong("DoorCloseTime"); this.taskID = Bukkit.getScheduler().runTaskTimer(V10LiftPlugin.getInstance(), this, doorCloseTime, doorCloseTime).getTaskId(); @@ -21,11 +22,11 @@ public class DoorCloser implements Runnable { @Override public void run() { - if (V10LiftAPI.getInstance().closeDoor(liftName)) stop(); + if (lift.closeDoor()) stop(); } public void stop() { Bukkit.getScheduler().cancelTask(taskID); - if (DataManager.containsLift(liftName)) DataManager.getLift(liftName).setDoorCloser(null); + lift.setDoorCloser(null); } } diff --git a/src/main/java/tech/sbdevelopment/v10lift/managers/DataManager.java b/src/main/java/tech/sbdevelopment/v10lift/managers/DataManager.java index 46b212d..717475b 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/managers/DataManager.java +++ b/src/main/java/tech/sbdevelopment/v10lift/managers/DataManager.java @@ -7,8 +7,6 @@ import tech.sbdevelopment.v10lift.api.objects.LiftBlock; import java.util.*; public class DataManager { - /* A manager for general HashMaps */ - @Getter private static final Map lifts = new LinkedHashMap<>(); private static final Map> builds = new LinkedHashMap<>(); @Getter private static final Map editors = new LinkedHashMap<>(); private static final Map inputEdits = new LinkedHashMap<>(); @@ -22,26 +20,6 @@ public class DataManager { private static final List whoisReq = new ArrayList<>(); private static final Map movingTasks = new HashMap<>(); - /* HashMap methods */ - - // // - public static void addLift(String liftName, Lift lift) { - lifts.put(liftName, lift); - } - - public static void removeLift(String liftName) { - lifts.remove(liftName); - } - - public static boolean containsLift(String liftName) { - return lifts.containsKey(liftName); - } - - public static Lift getLift(String liftName) { - return lifts.get(liftName); - } - - // // public static boolean containsPlayer(UUID player) { return builds.containsKey(player); } From fdd34cbe31d3ac66e2802cbc36679bcd38ae2d15 Mon Sep 17 00:00:00 2001 From: SBDeveloper Date: Fri, 23 Aug 2024 14:12:19 +0200 Subject: [PATCH 2/2] Migrated to storm --- pom.xml | 18 + .../sbdevelopment/v10lift/V10LiftPlugin.java | 75 +-- .../sbdevelopment/v10lift/api/V10LiftAPI.java | 42 +- .../v10lift/api/lists/LiftQueue.java | 9 + .../v10lift/api/objects/Lift.java | 26 +- .../v10lift/api/runnables/MoveLift.java | 27 +- .../v10lift/commands/V10LiftCommand.java | 525 ++++-------------- .../v10lift/commands/V10LiftTabCompleter.java | 98 ---- .../v10lift/listeners/BlockBreakListener.java | 10 +- .../listeners/EntityDamageListener.java | 4 +- .../v10lift/listeners/SignChangeListener.java | 9 +- .../sbdevelopment/v10lift/locale/Locale.java | 66 +++ .../sbdevelopment/v10lift/locale/Message.java | 144 +++++ .../v10lift/locale/package-info.java | 4 + .../v10lift/managers/ACFHandler.java | 61 ++ .../v10lift/managers/DBManager.java | 133 +---- .../v10lift/sbutils/ConfigUpdater.java | 335 ----------- .../v10lift/sbutils/SQLiteDB.java | 89 --- .../v10lift/sbutils/StormSQLiteDB.java | 72 +++ .../v10lift/sbutils/UpdateManager.java | 154 ++--- .../v10lift/utils/ConfigUtil.java | 8 +- src/main/resources/config.yml | 3 + src/main/resources/locale/lang_en.yml | 147 +++++ src/main/resources/messages.yml | 175 ------ src/main/resources/plugin.yml | 25 +- 25 files changed, 850 insertions(+), 1409 deletions(-) delete mode 100644 src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftTabCompleter.java create mode 100644 src/main/java/tech/sbdevelopment/v10lift/locale/Locale.java create mode 100644 src/main/java/tech/sbdevelopment/v10lift/locale/Message.java create mode 100644 src/main/java/tech/sbdevelopment/v10lift/locale/package-info.java create mode 100644 src/main/java/tech/sbdevelopment/v10lift/managers/ACFHandler.java delete mode 100644 src/main/java/tech/sbdevelopment/v10lift/sbutils/ConfigUpdater.java delete mode 100644 src/main/java/tech/sbdevelopment/v10lift/sbutils/SQLiteDB.java create mode 100644 src/main/java/tech/sbdevelopment/v10lift/sbutils/StormSQLiteDB.java create mode 100644 src/main/resources/locale/lang_en.yml delete mode 100644 src/main/resources/messages.yml diff --git a/pom.xml b/pom.xml index c25b8e4..fef31ac 100644 --- a/pom.xml +++ b/pom.xml @@ -150,6 +150,10 @@ enginehub-maven https://maven.enginehub.org/repo/ + + aikar + https://repo.aikar.co/content/groups/aikar/ + @@ -208,5 +212,19 @@ 7.2.9 provided + + + + com.github.jensjeflensje + storm + 4e84a5205f + + + + + co.aikar + acf-paper + 0.5.1-SNAPSHOT + \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java b/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java index 298c71e..9d00aa6 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java +++ b/src/main/java/tech/sbdevelopment/v10lift/V10LiftPlugin.java @@ -6,20 +6,17 @@ import org.bstats.charts.SingleLineChart; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import tech.sbdevelopment.v10lift.api.V10LiftAPI; -import tech.sbdevelopment.v10lift.commands.V10LiftCommand; -import tech.sbdevelopment.v10lift.commands.V10LiftTabCompleter; import tech.sbdevelopment.v10lift.listeners.BlockBreakListener; import tech.sbdevelopment.v10lift.listeners.EntityDamageListener; import tech.sbdevelopment.v10lift.listeners.PlayerInteractListener; import tech.sbdevelopment.v10lift.listeners.SignChangeListener; import tech.sbdevelopment.v10lift.managers.*; -import tech.sbdevelopment.v10lift.sbutils.ConfigUpdater; import tech.sbdevelopment.v10lift.sbutils.UpdateManager; import tech.sbdevelopment.v10lift.sbutils.YamlFile; import java.io.IOException; import java.sql.SQLException; -import java.util.Collections; +import java.util.logging.Level; public class V10LiftPlugin extends JavaPlugin { @Getter @@ -39,21 +36,20 @@ public class V10LiftPlugin extends JavaPlugin { public void onEnable() { instance = this; + getLogger().info("-------------------------------"); + getLogger().info("V10Lift v" + getDescription().getVersion()); + getLogger().info("Made by SBDeveloper"); + getLogger().info(" "); + //Load the API + getLogger().info("Loading API..."); api = new V10LiftAPI(); //Load the config + getLogger().info("Loading configs..."); config = new YamlFile("config"); config.loadDefaults(); - //And update config - try { - ConfigUpdater.update(this, "config.yml", config.getJavaFile(), Collections.emptyList()); - } catch (IOException e) { - Bukkit.getLogger().warning("[V10Lift] Couldn't update the config.yml. Please check the stacktrace below."); - e.printStackTrace(); - } - //Load the messages messages = new YamlFile("messages"); messages.loadDefaults(); @@ -65,88 +61,101 @@ public class V10LiftPlugin extends JavaPlugin { ForbiddenBlockManager.init(); //Load the database - dbManager = new DBManager("data"); + getLogger().info("Loading lifts from storage..."); + dbManager = new DBManager(this, "data"); try { dbManager.load(); - } catch (SQLException e) { - Bukkit.getLogger().warning("[V10Lift] Couldn't connect to the SQLite database. Please check the stacktrace below."); - e.printStackTrace(); + } catch (Exception e) { + getLogger().log(Level.SEVERE, "Couldn't load lifts from data storage.", e); } //Load vault if found if (VaultManager.setupPermissions()) { - Bukkit.getLogger().info("[V10Lift] Loading Vault hook for group whitelist support."); + getLogger().info("Loading Vault hook for group whitelist support."); vault = true; } //Load worldedit if found if (Bukkit.getPluginManager().getPlugin("WorldEdit") != null) { - Bukkit.getLogger().info("[V10Lift] Loading WorldEdit hook for selection support."); + getLogger().info("Loading WorldEdit hook for selection support."); worldEdit = true; } //Load the command - getCommand("v10lift").setExecutor(new V10LiftCommand()); - getCommand("v10lift").setTabCompleter(new V10LiftTabCompleter()); + getLogger().info("Registering commands..."); + try { + ACFHandler.init(this); + } catch (IOException e) { + getLogger().log(Level.SEVERE, "Couldn't load commands.", e); + } //Register the listeners + getLogger().info("Registering events..."); Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(), this); Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this); Bukkit.getPluginManager().registerEvents(new SignChangeListener(), this); Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this); //Load metrics - Bukkit.getLogger().info("[V10Lift] Loading metrics. Can be disabled in the global bStats config."); + getLogger().info("Loading metrics. Can be disabled in the global bStats config."); Metrics metrics = new Metrics(this, 6564); - metrics.addCustomChart(new SingleLineChart("lifts", () -> DataManager.getLifts().size())); + metrics.addCustomChart(new SingleLineChart("lifts", () -> api.getLifts().size())); //Load the update checker if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) { - UpdateManager updateManager = new UpdateManager(this, 72317); + UpdateManager updateManager = new UpdateManager(this, UpdateManager.CheckType.SPIGOT); updateManager.handleResponse((versionResponse, version) -> { switch (versionResponse) { case FOUND_NEW: - Bukkit.getLogger().warning("[V10Lift] There is a new version available! Current: " + this.getDescription().getVersion() + " New: " + version.get()); + getLogger().warning("There is a new version available! Current: " + this.getDescription().getVersion() + " New: " + version.get()); if (getSConfig().getFile().getBoolean("UpdateChecker.DownloadOnUpdate")) { - Bukkit.getLogger().info("[V10Lift] Trying to download the update. This could take some time..."); + getLogger().info("Trying to download the update. This could take some time..."); updateManager.handleDownloadResponse((downloadResponse, fileName) -> { switch (downloadResponse) { case DONE: - Bukkit.getLogger().info("[V10Lift] Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName); + getLogger().info("Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName); break; case ERROR: - Bukkit.getLogger().severe("[V10Lift] Something went wrong when trying downloading the latest version."); + getLogger().severe("Something went wrong when trying downloading the latest version."); break; case UNAVAILABLE: - Bukkit.getLogger().warning("[V10Lift] Unable to download the latest version."); + getLogger().warning("Unable to download the latest version."); break; } }).runUpdate(); } break; case LATEST: - Bukkit.getLogger().info("[V10Lift] You are running the latest version [" + this.getDescription().getVersion() + "]!"); + getLogger().info("You are running the latest version [" + this.getDescription().getVersion() + "]!"); break; case THIS_NEWER: - Bukkit.getLogger().info("[V10Lift] You are running a newer version [" + this.getDescription().getVersion() + "]! This is probably fine."); + getLogger().info("You are running a newer version [" + this.getDescription().getVersion() + "]! This is probably fine."); break; case UNAVAILABLE: - Bukkit.getLogger().severe("[V10Lift] Unable to perform an update check."); + getLogger().severe("Unable to perform an update check."); break; } }).check(); } - Bukkit.getLogger().info("[V10Lift] Plugin loaded successfully!"); + getLogger().info("Plugin loaded successfully!"); + getLogger().info("-------------------------------"); } @Override public void onDisable() { - dbManager.save(); + getLogger().info("Saving lifts..."); + try { + dbManager.save(); + } catch (SQLException e) { + //We can't do anything about it here, just inform the user + getLogger().log(Level.WARNING, "Couldn't save lifts to data storage.", e); + } dbManager.closeConnection(); + getLogger().info("Plugin disabled!"); instance = null; } diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java b/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java index da1c8f2..2cdc7a6 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/V10LiftAPI.java @@ -13,6 +13,8 @@ import tech.sbdevelopment.v10lift.api.objects.LiftSign; import tech.sbdevelopment.v10lift.managers.DataManager; import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.SQLException; import java.util.*; /** @@ -20,37 +22,36 @@ import java.util.*; */ public class V10LiftAPI { @Getter - private static final List lifts = new ArrayList<>(); + private final List lifts = new ArrayList<>(); /** * Create a new Lift * * @param p The player [owner] of the lift * @param liftName The name of the lift - * @return true if created, false if null or already exists + * @return The lift object, or null if already exists */ - public boolean createLift(@Nonnull Player p, @Nonnull String liftName) { - if (isLift(liftName)) return false; + @Nullable + public Lift createLift(@Nonnull Player p, @Nonnull String liftName) { + if (isLift(liftName)) return null; - lifts.add(new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic"))); - return true; + Lift lift = new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic")); + lifts.add(lift); + return lift; } /** * Remove a lift * - * @param liftName The name of the lift - * @return true if removed, false if null or doesn't exists + * @param lift The lift + * @return true if removed, false if failure (check console) */ - public boolean deleteLift(@Nonnull String liftName) { - Optional liftOpt = getLift(liftName); - if (liftOpt.isEmpty()) return false; - + public boolean deleteLift(Lift lift) { Iterator> iter = DataManager.getEditors().entrySet().iterator(); HashSet activeEdits = new HashSet<>(); while (iter.hasNext()) { Map.Entry entry = iter.next(); - if (entry.getValue().equals(liftName)) { + if (entry.getValue().equals(lift.getName())) { activeEdits.add(entry.getKey()); iter.remove(); } @@ -67,13 +68,18 @@ public class V10LiftAPI { DataManager.removeDoorEditPlayer(puuid); } - if (DataManager.containsMovingTask(liftName)) { - Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(liftName)); - DataManager.removeMovingTask(liftName); + if (DataManager.containsMovingTask(lift.getName())) { + Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); + DataManager.removeMovingTask(lift.getName()); } - lifts.remove(liftOpt.get()); - V10LiftPlugin.getDBManager().remove(liftName); + lifts.remove(lift); + try { + V10LiftPlugin.getDBManager().remove(lift); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } return true; } diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java b/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java index 3e91c43..a7edb2d 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/lists/LiftQueue.java @@ -3,6 +3,7 @@ package tech.sbdevelopment.v10lift.api.lists; import lombok.Setter; import tech.sbdevelopment.v10lift.api.objects.Floor; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; @@ -12,6 +13,10 @@ public class LiftQueue { @Setter private LiftQueueListener listener; + public void empty() { + queue.clear(); + } + public interface LiftQueueListener { void onQueueChange(); } @@ -26,6 +31,10 @@ public class LiftQueue { } } + public Iterator> iterator() { + return queue.entrySet().iterator(); + } + public boolean hasRequests() { return !queue.isEmpty(); } diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java index e7e6963..4dee5d4 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/objects/Lift.java @@ -1,5 +1,8 @@ package tech.sbdevelopment.v10lift.api.objects; +import com.craftmend.storm.api.StormModel; +import com.craftmend.storm.api.markers.Column; +import com.craftmend.storm.api.markers.Table; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -27,35 +30,56 @@ import java.util.*; @Getter @NoArgsConstructor @ToString -public class Lift { +@Table(name = "lifts") +public class Lift extends StormModel { + @Column @Setter private String name; + @Column @Setter private String worldName; + @Column @Setter private int y; + @Column private HashSet owners; + @Column private final TreeSet blocks = new TreeSet<>(); + @Column private final LinkedHashMap floors = new LinkedHashMap<>(); + @Column private final HashSet signs = new HashSet<>(); + @Column private final HashSet inputs = new HashSet<>(); + @Column private final HashSet offlineInputs = new HashSet<>(); + //transient private final LiftQueue queue = new LiftQueue(); + @Column private final HashSet ropes = new HashSet<>(); + @Column @Setter private int speed; + @Column @Setter private boolean realistic; + @Column private boolean offline = false; + @Column @Setter private boolean sound = true; + @Column private boolean defective = false; + @Column @Setter private String signText = null; + //transient @Setter private int counter = 0; + //transient @Setter private Floor doorOpen = null; + //transient @Setter private DoorCloser doorCloser = null; diff --git a/src/main/java/tech/sbdevelopment/v10lift/api/runnables/MoveLift.java b/src/main/java/tech/sbdevelopment/v10lift/api/runnables/MoveLift.java index 2f61a83..b466ff5 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/api/runnables/MoveLift.java +++ b/src/main/java/tech/sbdevelopment/v10lift/api/runnables/MoveLift.java @@ -1,6 +1,5 @@ package tech.sbdevelopment.v10lift.api.runnables; -import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; import org.bukkit.*; import org.bukkit.block.Block; @@ -11,14 +10,13 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import tech.sbdevelopment.v10lift.V10LiftPlugin; -import tech.sbdevelopment.v10lift.api.V10LiftAPI; import tech.sbdevelopment.v10lift.api.enums.LiftDirection; import tech.sbdevelopment.v10lift.api.objects.*; import tech.sbdevelopment.v10lift.managers.AntiCopyBlockManager; import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.sbutils.LocationSerializer; -import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.BlockStateUtil; +import tech.sbdevelopment.v10lift.utils.ConfigUtil; import java.lang.reflect.Method; import java.util.*; @@ -67,15 +65,16 @@ public class MoveLift implements Runnable { @Override public void run() { //Check if lift exists - Lift lift = DataManager.getLift(liftName); - if (lift == null) { + Optional liftOpt = V10LiftPlugin.getApi().getLift(liftName); + if (liftOpt.isEmpty()) { stop(); return; } + Lift lift = liftOpt.get(); - //If the queue is NOT empty and the lift is NOT offline - if (lift.getQueue().isEmpty() || lift.isOffline()) { - lift.setQueue(null); + //If the queue is NOT empty and the lift is offline + if (lift.getQueue().hasRequests() || lift.isOffline()) { + lift.getQueue().empty(); stop(); return; } @@ -122,12 +121,12 @@ public class MoveLift implements Runnable { if (changeOfDefect > 0.0D) { double chance = ThreadLocalRandom.current().nextDouble(100); if (chance < changeOfDefect) { - V10LiftAPI.getInstance().setDefective(liftName, true); + lift.setDefective(true); return; } } - Iterator> queueIterator = lift.getQueue().entrySet().iterator(); + Iterator> queueIterator = lift.getQueue().iterator(); Map.Entry floor = queueIterator.next(); String floorName = floor.getKey(); Floor floorTo = floor.getValue(); @@ -144,7 +143,7 @@ public class MoveLift implements Runnable { List antiCopyBlocks = new ArrayList<>(); if (direction == LiftDirection.UP || direction == LiftDirection.DOWN) { - if (!V10LiftAPI.getInstance().closeDoor(liftName)) return; + if (!lift.closeDoor()) return; if (direction == LiftDirection.UP) { //MOVE ROPES @@ -152,7 +151,7 @@ public class MoveLift implements Runnable { if (rope.getCurrently() > rope.getMaxY()) { Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!"); - V10LiftAPI.getInstance().setDefective(liftName, true); + lift.setDefective(true); queueIterator.remove(); return; } @@ -305,7 +304,7 @@ public class MoveLift implements Runnable { if (rope.getCurrently() < rope.getMinY()) { Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!"); - V10LiftAPI.getInstance().setDefective(liftName, true); + lift.setDefective(true); queueIterator.remove(); stopAfter = true; @@ -388,7 +387,7 @@ public class MoveLift implements Runnable { ls.setState((byte) 0); } - V10LiftAPI.getInstance().openDoor(lift, liftName, floorTo); + lift.openDoor(floorTo); if (lift.isRealistic()) lift.setCounter(ft); diff --git a/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftCommand.java b/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftCommand.java index 11e230c..972ca70 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftCommand.java +++ b/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftCommand.java @@ -1,15 +1,15 @@ package tech.sbdevelopment.v10lift.commands; +import co.aikar.commands.BaseCommand; +import co.aikar.commands.CommandHelp; +import co.aikar.commands.annotation.*; import com.cryptomorin.xseries.XMaterial; -import com.ibm.icu.impl.Pair; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Powerable; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -25,285 +25,102 @@ import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.WorldEditUtil; import javax.annotation.Nonnull; -import java.sql.SQLException; +import java.util.Optional; import java.util.*; -public class V10LiftCommand implements CommandExecutor { - - @Override - public boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command cmd, @Nonnull String label, @Nonnull String[] args) { - if (args.length == 0) { - //v10lift - return helpCommand(sender); - } else if (args[0].equalsIgnoreCase("info") && args.length == 1) { - //v10lift info - return infoCommand(sender); - } else if (args[0].equalsIgnoreCase("list") && args.length == 1) { - //v10lift list - if (sender.hasPermission("v10lift.list") || sender.hasPermission("v10lift.admin")) { - return listCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("create") && (args.length == 1 || args.length == 2)) { - //v10lift create || v10lift create - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return createCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("delete") && args.length == 2) { - //v10lift delete - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return deleteCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("edit") && (args.length == 1 || args.length == 2)) { - //v10lift edit - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return editCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("floor") && (args.length == 3 || args.length == 4)) { - //v10lift floor add || v10lift floor del || v10lift floor rename - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return floorCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("input") && (args.length == 2 || args.length == 3)) { - //v10lift input add || v10lift input del - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return inputCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("offline") && args.length == 2) { - //v10lift offline add || v10lift offline del - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return offlineCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("rename") && args.length == 2) { - //v10lift rename - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return renameCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("build") && args.length == 1) { - //v10lift build - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return buildCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("build") && args.length == 2 && args[1].equalsIgnoreCase("worldedit")) { - //v10lift build worldedit - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - if (!V10LiftPlugin.isWorldEditEnabled()) { - ConfigUtil.sendMessage(sender, "Build.WorldEditNotEnabled"); - return true; - } - - return buildWorldEditCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("rope") && args.length == 2) { - //v10lift rope add || v10lift rope del - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return ropeCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("door") && (args.length == 1 || args.length == 2)) { - //v10lift door || v10lift door - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return doorCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("whitelist") && (args.length == 3 || args.length == 4)) { - //v10lift whitelist add || v10lift whitelist del - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return whitelistCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("whois") && (args.length == 1 || args.length == 2)) { - //v10lift whois || v10lift whois - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return whoisCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("speed") && (args.length == 2 || args.length == 3)) { - //v10lift speed [Name] - if (args.length == 2 && !(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return speedCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("sound") && args.length == 1) { - //v10lift sound - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return soundCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("realistic") && args.length == 1) { - //v10lift realistic - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return realisticCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("abort") && args.length == 1) { - //v10lift abort - if (!(sender instanceof Player)) { - ConfigUtil.sendMessage(sender, "General.PlayerOnly"); - return true; - } - if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) { - return abortCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("reload") && args.length == 1) { - //v10lift reload - if (sender.hasPermission("v10lift.reload") || sender.hasPermission("v10lift.admin")) { - return reloadCommand(sender); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("repair") && args.length == 2) { - //v10lift repair - if (sender.hasPermission("v10lift.repair") || sender.hasPermission("v10lift.admin")) { - return repairCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("disable") && args.length == 2) { - //v10lift disable - if (sender.hasPermission("v10lift.disable") || sender.hasPermission("v10lift.admin")) { - return disableCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("setoffline") && args.length == 3) { - //v10lift setoffline - if (sender.hasPermission("v10lift.setoffline") || sender.hasPermission("v10lift.admin")) { - return setOfflineCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("start")) { - //v10lift start - if (sender.hasPermission("v10lift.start") || sender.hasPermission("v10lift.admin")) { - return startCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else if (args[0].equalsIgnoreCase("stop")) { - //v10lift stop - if (sender.hasPermission("v10lift.stop") || sender.hasPermission("v10lift.admin")) { - return stopCommand(sender, args); - } else { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - } - } else { - return helpCommand(sender); - } - return true; +@CommandAlias("v10lift|v10l") +@Description("The main command for V10Lift") +public class V10LiftCommand extends BaseCommand { + @HelpCommand + @CatchUnknown + @Default + public static void onHelp(CommandSender sender, CommandHelp help) { + help.showHelp(); } - private boolean listCommand(CommandSender sender) { + @Subcommand("info") + @Description("Get information about the plugin") + public void infoCommand(CommandSender sender) { + sender.sendMessage(ChatColor.DARK_GREEN + "V10Lift v" + V10LiftPlugin.getInstance().getDescription().getVersion()); + sender.sendMessage(ChatColor.GREEN + "Made by SBDeveloper"); + sender.sendMessage(ChatColor.GREEN + " "); + sender.sendMessage(ChatColor.GREEN + "Type /v10lift help for more information!"); + } + + @Subcommand("list") + @Description("List all lifts") + @CommandPermission("v10lift.list") + public void listCommand(CommandSender sender) { //Send list of all lifts - Map lifts = DataManager.getLifts(); + List lifts = V10LiftPlugin.getApi().getLifts(); if (lifts.isEmpty()) { ConfigUtil.sendMessage(sender, "List.NoLifts"); - return true; + return; } ConfigUtil.sendMessage(sender, "List.Header"); - for (String liftName : lifts.keySet()) { - ConfigUtil.sendMessage(sender, "List.Lift", Map.of("%Name%", liftName)); + for (Lift lift : lifts) { + ConfigUtil.sendMessage(sender, "List.Lift", Map.of("%Name%", lift.getName())); } - return true; + } + + @Subcommand("create") + @Description("Create a lift") + @CommandPermission("v10lift.admin") + @CommandCompletion("@nothing") + public void createCommand(Player p, @co.aikar.commands.annotation.Optional String name) { + if (DataManager.containsPlayer(p.getUniqueId())) { + //Already building!! + if (name == null) { + ConfigUtil.sendMessage(p, "General.IncorrectUsage", Collections.singletonMap("%Command%", "/v10lift create ")); + return; + } + + TreeSet blocks = DataManager.getPlayer(p.getUniqueId()); + if (blocks.isEmpty()) { + ConfigUtil.sendMessage(p, "Create.NoBlocks"); + return; + } + + Lift lift = V10LiftPlugin.getApi().createLift(p, name); + if (lift == null) { + ConfigUtil.sendMessage(p, "General.AlreadyExists"); + return; + } + + blocks.forEach(block -> lift.addBlock(lift.getBlocks(), block)); + lift.sortLiftBlocks(); + DataManager.removePlayer(p.getUniqueId()); + ConfigUtil.sendMessage(p, "Create.Created", Collections.singletonMap("%Name%", name)); + p.performCommand("v10lift edit " + name); + } else { + //Not building yet!! + DataManager.addPlayer(p.getUniqueId()); + ConfigUtil.sendMessage(p, "Create.AddBlocks"); + } + } + + @Subcommand("delete") + @Description("Delete a lift") + @CommandPermission("v10lift.admin") + @CommandCompletion("@lifts") + public void deleteCommand(Player p, Lift lift) { + if (!V10LiftPlugin.getApi().deleteLift(lift)) { + ConfigUtil.sendMessage(p, "Delete.NotRemoved", Collections.singletonMap("%Name%", lift.getName())); + return; + } + + ConfigUtil.sendMessage(p, "Delete.Removed", Collections.singletonMap("%Name%", lift.getName())); } private boolean setOfflineCommand(CommandSender sender, @Nonnull String[] args) { String liftName = args[1]; boolean newState = Boolean.parseBoolean(args[2]); - if (!DataManager.containsLift(liftName)) { + Optional liftOpt = V10LiftPlugin.getApi().getLift(liftName); + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } - - Lift lift = DataManager.getLift(liftName); + Lift lift = liftOpt.get(); lift.setOffline(newState); @@ -326,74 +143,73 @@ public class V10LiftCommand implements CommandExecutor { private boolean disableCommand(CommandSender sender, @Nonnull String[] args) { String liftName = args[1]; - if (!DataManager.containsLift(liftName)) { + Optional liftOpt = V10LiftPlugin.getApi().getLift(liftName); + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } - - Lift lift = DataManager.getLift(liftName); + Lift lift = liftOpt.get(); if (lift.isDefective()) { ConfigUtil.sendMessage(sender, "Disable.AlreadyDefective"); return true; } - V10LiftAPI.getInstance().setDefective(liftName, true); + lift.setDefective(true); ConfigUtil.sendMessage(sender, "Disable.Disabled"); return true; } private boolean stopCommand(CommandSender sender, @Nonnull String[] args) { - String liftName; + Optional liftOpt; if (args.length == 1 && sender instanceof Player) { //v10lift stop -> Get liftName from loc and floorName from sign Player p = (Player) sender; - liftName = V10LiftAPI.getInstance().getLiftByLocation(p.getLocation()); + liftOpt = V10LiftPlugin.getApi().getLift(p.getLocation()); } else if (args.length == 1) { ConfigUtil.sendMessage(sender, "Stop.NonPlayer"); return true; } else { - liftName = args[1]; + liftOpt = V10LiftPlugin.getApi().getLift(args[1]); } - if (liftName == null || !DataManager.containsLift(liftName)) { + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } + Lift lift = liftOpt.get(); - Lift lift = DataManager.getLift(liftName); - if (!lift.getQueue().isEmpty()) lift.getQueue().clear(); + if (lift.getQueue().hasRequests()) lift.getQueue().empty(); - if (!DataManager.containsMovingTask(liftName)) { - ConfigUtil.sendMessage(sender, "Stop.NoMovingTasks", Collections.singletonMap("%Name%", liftName)); + if (!DataManager.containsMovingTask(lift.getName())) { + ConfigUtil.sendMessage(sender, "Stop.NoMovingTasks", Collections.singletonMap("%Name%", lift.getName())); return true; } - Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(liftName)); - DataManager.removeMovingTask(liftName); - ConfigUtil.sendMessage(sender, "Stop.Stopped", Collections.singletonMap("%Name%", liftName)); + Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); + DataManager.removeMovingTask(lift.getName()); + ConfigUtil.sendMessage(sender, "Stop.Stopped", Collections.singletonMap("%Name%", lift.getName())); return true; } private boolean startCommand(CommandSender sender, @Nonnull String[] args) { - String liftName; + Optional liftOpt; if (args.length == 1 && sender instanceof Player) { - //v10lift start -> Get liftName from loc and floorName from sign + //v10lift stop -> Get liftName from loc and floorName from sign Player p = (Player) sender; - liftName = V10LiftAPI.getInstance().getLiftByLocation(p.getLocation()); + liftOpt = V10LiftPlugin.getApi().getLift(p.getLocation()); } else if (args.length == 1) { ConfigUtil.sendMessage(sender, "Start.NonPlayer"); return true; } else { - liftName = args[1]; + liftOpt = V10LiftPlugin.getApi().getLift(args[1]); } - if (liftName == null || !DataManager.containsLift(liftName)) { + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } - - Lift lift = DataManager.getLift(liftName); + Lift lift = liftOpt.get(); String floorName = null; if (args.length == 1 || args.length == 2) { @@ -418,20 +234,19 @@ public class V10LiftCommand implements CommandExecutor { } Floor f = lift.getFloors().get(floorName); - V10LiftAPI.getInstance().addToQueue(liftName, f, floorName); - ConfigUtil.sendMessage(sender, "Start.Started", Collections.singletonMap("%Name%", liftName)); + lift.getQueue().requestFloor(floorName, f); + ConfigUtil.sendMessage(sender, "Start.Started", Collections.singletonMap("%Name%", lift.getName())); return true; } private boolean reloadCommand(CommandSender sender) { - for (Map.Entry e : DataManager.getLifts().entrySet()) { - String lift = e.getKey(); - if (DataManager.containsMovingTask(lift)) { - Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift)); + for (Lift lift : V10LiftPlugin.getApi().getLifts()) { + if (DataManager.containsMovingTask(lift.getName())) { + Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); } - e.getValue().setQueue(null); - V10LiftAPI.getInstance().sortLiftBlocks(lift); + lift.getQueue().empty(); + lift.sortLiftBlocks(); } DataManager.clearMovingTasks(); @@ -439,7 +254,7 @@ public class V10LiftCommand implements CommandExecutor { try { V10LiftPlugin.getDBManager().save(); V10LiftPlugin.getDBManager().load(); - } catch (SQLException e) { + } catch (Exception e) { e.printStackTrace(); } @@ -486,7 +301,7 @@ public class V10LiftCommand implements CommandExecutor { if (DataManager.containsBuilderPlayer(p.getUniqueId())) { DataManager.removeBuilderPlayer(p.getUniqueId()); - V10LiftAPI.getInstance().sortLiftBlocks(DataManager.getEditPlayer(p.getUniqueId())); + V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get().sortLiftBlocks(); abort = true; } @@ -515,12 +330,12 @@ public class V10LiftCommand implements CommandExecutor { private boolean repairCommand(CommandSender sender, @Nonnull String[] args) { String liftName = args[1]; - if (!DataManager.containsLift(liftName)) { + Optional liftOpt = V10LiftPlugin.getApi().getLift(liftName); + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } - - Lift lift = DataManager.getLift(liftName); + Lift lift = liftOpt.get(); if (!lift.isDefective()) { ConfigUtil.sendMessage(sender, "Repair.NotDefective"); @@ -553,7 +368,7 @@ public class V10LiftCommand implements CommandExecutor { } } } - V10LiftAPI.getInstance().setDefective(liftName, false); + lift.setDefective(false); ConfigUtil.sendMessage(sender, "Repair.Repaired"); return true; } @@ -565,7 +380,7 @@ public class V10LiftCommand implements CommandExecutor { return true; } - Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); + Lift lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); lift.setRealistic(!lift.isRealistic()); if (lift.isRealistic()) { ConfigUtil.sendMessage(sender, "Realistic.TurnedOn"); @@ -582,7 +397,7 @@ public class V10LiftCommand implements CommandExecutor { return true; } - Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); + Lift lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); lift.setSound(!lift.isSound()); if (lift.isSound()) { ConfigUtil.sendMessage(sender, "Sound.TurnedOn"); @@ -595,11 +410,11 @@ public class V10LiftCommand implements CommandExecutor { private boolean speedCommand(CommandSender sender, @Nonnull String[] args) { Lift lift; if (args.length == 3) { - if (!DataManager.containsLift(args[2])) { + if (!V10LiftPlugin.getApi().isLift(args[2])) { ConfigUtil.sendMessage(sender, "General.DoesntExists"); return true; } - lift = DataManager.getLift(args[2]); + lift = V10LiftPlugin.getApi().getLift(args[2]).get(); } else { Player p = (Player) sender; if (!DataManager.containsEditPlayer(p.getUniqueId())) { @@ -607,7 +422,7 @@ public class V10LiftCommand implements CommandExecutor { return true; } - lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); + lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); } try { @@ -634,10 +449,10 @@ public class V10LiftCommand implements CommandExecutor { ConfigUtil.sendMessage(sender, "Whois.WithoutName"); } else { String liftName = args[1]; - if (!DataManager.containsLift(liftName)) { + if (!V10LiftPlugin.getApi().isLift(liftName)) { ConfigUtil.sendMessage(sender, "Whois.DoesntExists"); } else { - V10LiftAPI.getInstance().sendLiftInfo(sender, liftName); + V10LiftPlugin.getApi().getLift(liftName).get().sendInfo(sender); } } return true; @@ -1145,100 +960,4 @@ public class V10LiftCommand implements CommandExecutor { } return true; } - - private boolean deleteCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - Player p = (Player) sender; - if (!DataManager.containsLift(args[1])) { - ConfigUtil.sendMessage(sender, "General.DoesntExists"); - return true; - } - - Lift lift = DataManager.getLift(args[1]); - if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) { - ConfigUtil.sendMessage(sender, "General.NoPermission"); - return true; - } - - if (!V10LiftAPI.getInstance().removeLift(args[1])) { - ConfigUtil.sendMessage(sender, "Delete.NotRemoved", Collections.singletonMap("%Name%", args[1])); - return true; - } - - ConfigUtil.sendMessage(sender, "Delete.Removed", Collections.singletonMap("%Name%", args[1])); - return true; - } - - private boolean createCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - Player p = (Player) sender; - if (DataManager.containsPlayer(p.getUniqueId())) { - //Already building!! - if (args.length < 2) { - ConfigUtil.sendMessage(sender, "General.IncorrectUsage", Collections.singletonMap("%Command%", "/v10lift create ")); - return true; - } - - TreeSet blocks = DataManager.getPlayer(p.getUniqueId()); - if (blocks.isEmpty()) { - ConfigUtil.sendMessage(sender, "Create.NoBlocks"); - return true; - } - - if (!V10LiftAPI.getInstance().createLift(p, args[1])) { - ConfigUtil.sendMessage(sender, "General.AlreadyExists"); - return true; - } - - TreeSet blcks = DataManager.getLift(args[1]).getBlocks(); - - blocks.forEach(block -> V10LiftAPI.getInstance().addBlockToLift(blcks, block)); - V10LiftAPI.getInstance().sortLiftBlocks(args[1]); - DataManager.removePlayer(p.getUniqueId()); - ConfigUtil.sendMessage(p, "Create.Created", Collections.singletonMap("%Name%", args[1])); - p.performCommand("v10lift edit " + args[1]); - } else { - //Not building yet!! - DataManager.addPlayer(p.getUniqueId()); - ConfigUtil.sendMessage(p, "Create.AddBlocks"); - } - return true; - } - - private boolean infoCommand(@Nonnull CommandSender sender) { - sender.sendMessage("§1=================================="); - sender.sendMessage("§6V10Lift plugin made by §aSBDeveloper"); - sender.sendMessage("§6Version: " + V10LiftPlugin.getInstance().getDescription().getVersion()); - sender.sendMessage("§6Type /v10lift help for more information!"); - sender.sendMessage("§1=================================="); - return true; - } - - private boolean helpCommand(@Nonnull CommandSender sender) { - sender.sendMessage("§8V10Lift commands:"); - sender.sendMessage("§6/v10lift info§f: Gives you information about the plugin."); - sender.sendMessage("§6/v10lift help§f: Gives you this help page."); - sender.sendMessage("§6/v10lift reload§f: Reload the plugin."); - - sender.sendMessage("§6/v10lift create [Name]§f: Create a lift."); - sender.sendMessage("§6/v10lift delete §f: Delete a lift."); - sender.sendMessage("§6/v10lift rename §f: Rename a lift."); - sender.sendMessage("§6/v10lift abort§f: Abort your action."); - sender.sendMessage("§6/v10lift whois [Name]§f: See information about a lift."); - sender.sendMessage("§6/v10lift edit [Name]§f: Edit a lift."); - sender.sendMessage("§6/v10lift floor [New name]§f: Add/remove/rename a floor."); - sender.sendMessage("§6/v10lift input [Floorname]§f: Add/remove an input."); - sender.sendMessage("§6/v10lift offline §f: Add/remove an offline input."); - sender.sendMessage("§6/v10lift build§f: Add/remove blocks to/from a cab."); - sender.sendMessage("§6/v10lift rope §f: Add/remove a rope."); - sender.sendMessage("§6/v10lift door§f: Add doors to a lift."); - sender.sendMessage("§6/v10lift speed §f: Change the speed of a lift."); - sender.sendMessage("§6/v10lift realistic§f: Toggle realistic mode."); - sender.sendMessage("§6/v10lift repair§f: Repair a lift."); - sender.sendMessage("§6/v10lift whitelist [Floorname]§f: Add/remove someone of the whitelist. Use g: for a group."); - sender.sendMessage("§6/v10lift start [Name] [Floor]§f: Start a lift to a floor."); - sender.sendMessage("§6/v10lift stop [Name]§f: Stop a lift."); - sender.sendMessage("§6/v10lift disable §f: Disable a lift."); - sender.sendMessage("§6/v10lift repair §f: Repair a lift."); - return true; - } - } diff --git a/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftTabCompleter.java b/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftTabCompleter.java deleted file mode 100644 index baec7ad..0000000 --- a/src/main/java/tech/sbdevelopment/v10lift/commands/V10LiftTabCompleter.java +++ /dev/null @@ -1,98 +0,0 @@ -package tech.sbdevelopment.v10lift.commands; - -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import tech.sbdevelopment.v10lift.V10LiftPlugin; -import tech.sbdevelopment.v10lift.api.objects.Lift; -import tech.sbdevelopment.v10lift.managers.DataManager; -import tech.sbdevelopment.v10lift.managers.VaultManager; - -import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class V10LiftTabCompleter implements TabCompleter { - - private static final List COMMANDS = Arrays.asList("create", "delete", "rename", "abort", "whois", "edit", "floor", "input", "build", "rope", "door", "speed", "realistic", "repair", "disable", "whitelist", "reload", "help", "start", "stop", "offline", "list", "setoffline"); - private static final List SUBRENAME = Arrays.asList("add", "del", "rename"); - private static final List SUB = Arrays.asList("add", "del"); - private static final List BOOL = Arrays.asList("true", "false"); - - @Override - public List onTabComplete(@Nonnull CommandSender commandSender, @Nonnull Command cmd, @Nonnull String label, @Nonnull String[] args) { - if (label.equalsIgnoreCase("v10lift")) { - if (args.length == 1) { - return StringUtil.copyPartialMatches(args[0], COMMANDS, new ArrayList<>()); - } else if (args.length == 2) { - //Command based sub-commands - if (args[0].equalsIgnoreCase("delete") - || args[0].equalsIgnoreCase("edit") - || args[0].equalsIgnoreCase("whois") - || args[0].equalsIgnoreCase("repair") - || args[0].equalsIgnoreCase("disable") - || args[0].equalsIgnoreCase("start") - || args[0].equalsIgnoreCase("stop")) { - return StringUtil.copyPartialMatches(args[1], DataManager.getLifts().keySet(), new ArrayList<>()); - } else if (args[0].equalsIgnoreCase("floor")) { - return StringUtil.copyPartialMatches(args[1], SUBRENAME, new ArrayList<>()); - } else if (args[0].equalsIgnoreCase("input") - || args[0].equalsIgnoreCase("offline") - || args[0].equalsIgnoreCase("whitelist") - || args[0].equalsIgnoreCase("rope")) { - return StringUtil.copyPartialMatches(args[1], SUB, new ArrayList<>()); - } else if (args[0].equalsIgnoreCase("setoffline")) { - return StringUtil.copyPartialMatches(args[1], BOOL, new ArrayList<>()); - } else if (args[0].equalsIgnoreCase("build") && V10LiftPlugin.isWorldEditEnabled()) { - return StringUtil.copyPartialMatches(args[1], List.of("worldedit"), new ArrayList<>()); - } - } else if (args.length == 3) { - //Command based arguments - if (args[0].equalsIgnoreCase("floor") && (args[1].equalsIgnoreCase("del") || args[1].equalsIgnoreCase("rename"))) { - if (commandSender instanceof Player) { - Player p = (Player) commandSender; - if (DataManager.containsEditPlayer(p.getUniqueId())) { - Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); - return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>()); - } - } - } else if ((args[0].equalsIgnoreCase("input") - || args[0].equalsIgnoreCase("offline")) && args[1].equalsIgnoreCase("del")) { - if (commandSender instanceof Player) { - Player p = (Player) commandSender; - if (DataManager.containsEditPlayer(p.getUniqueId())) { - Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); - return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>()); - } - } - } else if (args[0].equalsIgnoreCase("whitelist")) { - ArrayList playerOrGroupNames = new ArrayList<>(); - for (Player p : Bukkit.getOnlinePlayers()) { - playerOrGroupNames.add(p.getName()); - } - if (V10LiftPlugin.isVaultEnabled()) { - playerOrGroupNames.addAll(VaultManager.getGroups()); - } - return StringUtil.copyPartialMatches(args[2], playerOrGroupNames, new ArrayList<>()); - } - } else if (args.length == 4) { - //Command based arguments - if (args[0].equalsIgnoreCase("whitelist")) { - if (commandSender instanceof Player) { - Player p = (Player) commandSender; - if (DataManager.containsEditPlayer(p.getUniqueId())) { - Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId())); - return StringUtil.copyPartialMatches(args[3], lift.getFloors().keySet(), new ArrayList<>()); - } - } - } - } - } - return null; - } - -} diff --git a/src/main/java/tech/sbdevelopment/v10lift/listeners/BlockBreakListener.java b/src/main/java/tech/sbdevelopment/v10lift/listeners/BlockBreakListener.java index c4c616a..5510d2a 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/listeners/BlockBreakListener.java +++ b/src/main/java/tech/sbdevelopment/v10lift/listeners/BlockBreakListener.java @@ -7,31 +7,27 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; -import tech.sbdevelopment.v10lift.api.V10LiftAPI; +import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.api.objects.Floor; import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.LiftBlock; -import tech.sbdevelopment.v10lift.api.objects.LiftInput; -import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.DoorUtil; -import java.util.Map; import java.util.Objects; public class BlockBreakListener implements Listener { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent e) { Block b = e.getBlock(); - if (V10LiftAPI.getInstance().isRope(b)) { + if (V10LiftPlugin.getApi().isRope(b)) { ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveRopeFirst"); e.setCancelled(true); return; } LiftBlock tlb = new LiftBlock(b); - for (Map.Entry entry : DataManager.getLifts().entrySet()) { - Lift lift = entry.getValue(); + for (Lift lift : V10LiftPlugin.getApi().getLifts()) { if (lift.getBlocks().contains(tlb)) { ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveLiftFirst"); e.setCancelled(true); diff --git a/src/main/java/tech/sbdevelopment/v10lift/listeners/EntityDamageListener.java b/src/main/java/tech/sbdevelopment/v10lift/listeners/EntityDamageListener.java index a1c09a2..47afd33 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/listeners/EntityDamageListener.java +++ b/src/main/java/tech/sbdevelopment/v10lift/listeners/EntityDamageListener.java @@ -7,6 +7,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; +import tech.sbdevelopment.v10lift.V10LiftPlugin; +import tech.sbdevelopment.v10lift.api.V10LiftAPI; import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.LiftBlock; import tech.sbdevelopment.v10lift.managers.DataManager; @@ -31,7 +33,7 @@ public class EntityDamageListener implements Listener { int y = loc.getBlockY(); int z = loc.getBlockZ(); - for (Lift lift : DataManager.getLifts().values()) { + for (Lift lift : V10LiftPlugin.getApi().getLifts()) { for (LiftBlock lb : lift.getBlocks()) { if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) { e.setCancelled(true); diff --git a/src/main/java/tech/sbdevelopment/v10lift/listeners/SignChangeListener.java b/src/main/java/tech/sbdevelopment/v10lift/listeners/SignChangeListener.java index fabda8a..7346736 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/listeners/SignChangeListener.java +++ b/src/main/java/tech/sbdevelopment/v10lift/listeners/SignChangeListener.java @@ -7,11 +7,13 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; +import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.LiftSign; -import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.utils.ConfigUtil; +import java.util.Optional; + public class SignChangeListener implements Listener { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -25,12 +27,13 @@ public class SignChangeListener implements Listener { return; } - if (!DataManager.containsLift(lines[1])) { + Optional liftOpt = V10LiftPlugin.getApi().getLift(lines[1]); + if (liftOpt.isEmpty()) { ConfigUtil.sendMessage(e.getPlayer(), "General.DoesntExists"); return; } + Lift lift = liftOpt.get(); - Lift lift = DataManager.getLift(lines[1]); if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) { ConfigUtil.sendMessage(e.getPlayer(), "General.NoPermission"); e.setCancelled(true); diff --git a/src/main/java/tech/sbdevelopment/v10lift/locale/Locale.java b/src/main/java/tech/sbdevelopment/v10lift/locale/Locale.java new file mode 100644 index 0000000..cacb249 --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/locale/Locale.java @@ -0,0 +1,66 @@ +package tech.sbdevelopment.v10lift.locale; + +import co.aikar.commands.MessageType; +import co.aikar.locales.MessageKey; +import net.md_5.bungee.api.ChatColor; +import tech.sbdevelopment.v10lift.managers.ACFHandler; + +import java.util.Map; + +public class Locale { + private Locale() { + } + + /** + * Get a translated message + * + * @param key the key to the message + * @return the translated message string + */ + public static String getMessage(Message key) { + return getMessage(key.getMessageKey()); + } + + /** + * Get a translated message + * + * @param msg the key to the message + * @return the translated message string + */ + public static String getMessage(MessageKey msg) { + String message = ACFHandler.getManager().formatMessage(null, MessageType.INFO, msg); + return ChatColor.translateAlternateColorCodes('&', message); + } + + /** + * Get a translated message + * + * @param key the key to the message + * @param args the arguments to the message + * @return the translated message string + */ + public static String getMessage(Message key, Map args) { + return getMessage(key.getMessageKey(), args); + } + + /** + * Get a translated message + * + * @param msg the key to the message + * @param args the arguments to the message + * @return the translated message string + */ + public static String getMessage(MessageKey msg, Map args) { + //Turn map into array (key, value, key, value, etc.) + String[] argsArray = new String[args.size() * 2]; + int i = 0; + for (Map.Entry entry : args.entrySet()) { + argsArray[i] = entry.getKey(); + argsArray[i + 1] = entry.getValue(); + i += 2; + } + + String message = ACFHandler.getManager().formatMessage(null, MessageType.INFO, msg, argsArray); + return ChatColor.translateAlternateColorCodes('&', message); + } +} \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/locale/Message.java b/src/main/java/tech/sbdevelopment/v10lift/locale/Message.java new file mode 100644 index 0000000..986081d --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/locale/Message.java @@ -0,0 +1,144 @@ +package tech.sbdevelopment.v10lift.locale; + +import co.aikar.locales.MessageKey; +import co.aikar.locales.MessageKeyProvider; + +public enum Message implements MessageKeyProvider { + GENERAL_NOPERMISSION, + GENERAL_PLAYERONLY, + GENERAL_INCORRECTUSAGE, + GENERAL_INTERNALERROR, + GENERAL_DOESNTEXISTS, + GENERAL_ALREADYEXISTS, + GENERAL_SWITCHONEDIT, + GENERAL_DETECTIONFAILED, + GENERAL_FLOORDOESNTEXISTS, + GENERAL_NOWHITELISTPERMISSION, + GENERAL_NOFLOORS, + GENERAL_REMOVELIFFTFIRST, + GENERAL_REMOVEROPEFIRST, + GENERAL_REMOVEDOORFIRST, + CREATE_ADDBLOCKS, + CREATE_NOBLOCKS, + CREATE_CREATED, + DELETE_NOTREMOVED, + DELETE_REMOVED, + RENAME_RENAMED, + EDIT_STILLINEDITMODE, + EDIT_TURNEDON, + EDIT_TURNEDOFF, + FLOOR_TOHIGH, + FLOOR_ALREADYEXISTS, + FLOOR_DOESNTEXISTS, + FLOOR_ADDED, + FLOOR_REMOVED, + FLOOR_RENAMED, + INPUT_STILLADJUSTING, + INPUT_NOTHINGTOREMOVE, + INPUT_ALREADYADDED, + INPUT_NOINPUT, + INPUT_RIGHTCLICK, + INPUT_CREATED, + INPUT_REMOVED, + OFFLINEINPUT_STILLADJUSTING, + OFFLINEINPUT_NOTHINGTOREMOVE, + OFFLINEINPUT_ALREADYADDED, + OFFLINEINPUT_NOINPUT, + OFFLINEINPUT_RIGHTCLICK, + OFFLINEINPUT_CREATED, + OFFLINEINPUT_REMOVED, + BUILD_DISABLED, + BUILD_ENABLED, + BUILD_BLOCKADDED, + BUILD_BLOCKREMOVED, + BUILD_BLACKLISTEDMATERIAL, + BUILD_NOSELECTION, + BUILD_UNSUPPORTEDSELECTION, + BUILD_BLOCKSADDED, + BUILD_BLOCKSFAILED, + BUILD_WORLDEDITNOTENABLED, + ROPE_STILLADJUSTING, + ROPE_ONLYUP, + ROPE_ONLYONEMATERIAL, + ROPE_ALREADYAROPE, + ROPE_NOTAROPE, + ROPE_BLACKLISTEDMATERIAL, + ROPE_ADD, + ROPE_DELETE, + ROPE_CLICKONEND, + ROPE_PARTREMOVED, + ROPE_CREATED, + ROPE_REMOVED, + DOOR_BLACKLISTEDMATERIAL, + DOOR_DISABLED, + DOOR_ENABLED, + DOOR_CREATED, + DOOR_REMOVED, + WHITELIST_GROUP_VAULTNOTFOUND, + WHITELIST_GROUP_NOTFOUND, + WHITELIST_GROUP_ALREADYCONTAINS, + WHITELIST_GROUP_DOESNTCONTAINS, + WHITELIST_GROUP_ADDED, + WHITELIST_GROUP_REMOVED, + WHITELIST_PLAYER_NOTFOUND, + WHITELIST_PLAYER_ALREADYCONTAINS, + WHITELIST_PLAYER_DOESNTCONTAINS, + WHITELIST_PLAYER_ADDED, + WHITELIST_PLAYER_REMOVED, + WHOIS_USEWITHOUTNAME, + WHOIS_NOTALIFT, + WHOIS_WITHOUTNAME, + SPEED_WRONGSPEED, + SPEED_CHANGED, + SOUND_TURNEDON, + SOUND_TURNEDOFF, + REALISTIC_TURNEDON, + REALISTIC_TURNEDOFF, + DISABLE_ALREADYDEFECTIVE, + DISABLE_DISABLED, + REPAIR_NOTDEFECTIVE, + REPAIR_ITEMSNEEDED, + REPAIR_REPAIRED, + ABORT_NOTHINGTOCANCEL, + ABORT_CANCELLED, + RELOAD_RELOADED, + START_NONPLAYER, + START_STARTED, + STOP_NONPLAYER, + STOP_NOMOVINGTASKS, + STOP_STOPPED, + LIFTSIGN_NONAME, + LIFTSIGN_CREATED, + LIFTSIGN_REMOVED, + LIST_NOLIFTS, + LIST_HEADER, + LIST_LIFT, + SETOFFLINE_DISABLED, + SETOFFLINE_ENABLED; + + private final MessageKey key; + + Message() { + this.key = MessageKey.of(convertConstantToLanguageKey("v10lift." + this.name())); + } + + @Override + public MessageKey getMessageKey() { + return this.key; + } + + private static String convertConstantToLanguageKey(String constant) { + StringBuilder languageKey = new StringBuilder(); + String[] words = constant.split("_"); + + for (int i = 0; i < words.length; i++) { + String word = words[i].toLowerCase(); + if (i > 0) { + languageKey.append("."); + } + languageKey.append(word); + } + + return languageKey.toString(); + } +} diff --git a/src/main/java/tech/sbdevelopment/v10lift/locale/package-info.java b/src/main/java/tech/sbdevelopment/v10lift/locale/package-info.java new file mode 100644 index 0000000..5134ce7 --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/locale/package-info.java @@ -0,0 +1,4 @@ +/** + * All the event listeners of V10Lift + */ +package tech.sbdevelopment.v10lift.locale; \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/managers/ACFHandler.java b/src/main/java/tech/sbdevelopment/v10lift/managers/ACFHandler.java new file mode 100644 index 0000000..36eeffc --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/managers/ACFHandler.java @@ -0,0 +1,61 @@ +package tech.sbdevelopment.v10lift.managers; + +import co.aikar.commands.PaperCommandManager; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.plugin.java.JavaPlugin; +import tech.sbdevelopment.v10lift.V10LiftPlugin; +import tech.sbdevelopment.v10lift.api.objects.Lift; +import tech.sbdevelopment.v10lift.commands.V10LiftCommand; +import tech.sbdevelopment.v10lift.sbutils.YamlFile; + +import java.io.File; +import java.io.IOException; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class ACFHandler { + private static final String[] defaultLanguages = new String[]{"en"}; + private static final Pattern pattern = Pattern.compile("^lang_([a-z]{2})\\.yml$"); + + private ACFHandler() { + } + + private static PaperCommandManager manager; + + public static void init(JavaPlugin plugin) throws IOException { + manager = new PaperCommandManager(plugin); + + manager.getCommandContexts().registerContext(Lift.class, c -> V10LiftPlugin.getApi().getLift(c.popFirstArg().toLowerCase()).orElse(null)); + + manager.getCommandCompletions().registerCompletion("lifts", c -> V10LiftPlugin.getApi().getLifts().stream().map(Lift::getName).collect(Collectors.toList())); + manager.registerCommand(new V10LiftCommand()); + manager.enableUnstableAPI("help"); + + manager.getLocales().setDefaultLocale(Locale.forLanguageTag(V10LiftPlugin.getSConfig().getFile().getString("Locale"))); + + File localeDir = new File(plugin.getDataFolder(), "locale"); + localeDir.mkdirs(); + + for (String lang : defaultLanguages) { + YamlFile file = new YamlFile("locale/lang_" + lang); + file.loadDefaults(); + } + + for (File file : localeDir.listFiles((dir, name) -> name.startsWith("lang_") && name.endsWith(".yml"))) { + Matcher matcher = pattern.matcher(file.getName()); + if (!matcher.matches()) continue; + + try { + manager.getLocales().loadYamlLanguageFile(file, Locale.forLanguageTag(matcher.group(1))); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Couldn't load the language file " + file.getName() + "!"); + } + } + } + + public static PaperCommandManager getManager() { + return manager; + } +} diff --git a/src/main/java/tech/sbdevelopment/v10lift/managers/DBManager.java b/src/main/java/tech/sbdevelopment/v10lift/managers/DBManager.java index bffdb67..86d2cbb 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/managers/DBManager.java +++ b/src/main/java/tech/sbdevelopment/v10lift/managers/DBManager.java @@ -1,147 +1,64 @@ package tech.sbdevelopment.v10lift.managers; -import com.google.gson.Gson; -import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.api.objects.Lift; -import tech.sbdevelopment.v10lift.sbutils.SQLiteDB; +import tech.sbdevelopment.v10lift.sbutils.StormSQLiteDB; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Map; +import java.util.Collection; /** * The DBManager manages the database */ public class DBManager { - private static final Gson gson = new Gson(); - - private static SQLiteDB data; - private static Connection con; + private final StormSQLiteDB data; /** * Construct the database manager * - * @param name The name of the sqlite database file + * @param plugin The plugin instance + * @param dbName The name of the sqlite database file */ - public DBManager(String name) { - data = new SQLiteDB(name); - + public DBManager(JavaPlugin plugin, String dbName) { try { - con = data.getConnection(); - - String query = "CREATE TABLE IF NOT EXISTS lifts (liftName varchar(255) NOT NULL, liftData blob NOT NULL, UNIQUE (liftName))"; - PreparedStatement statement = con.prepareStatement(query); - statement.execute(); + data = new StormSQLiteDB(plugin, dbName); } catch (SQLException e) { - e.printStackTrace(); + throw new RuntimeException("Couldn't connect to the database!", e); } } /** * Load the database from data * - * @throws SQLException If the SQL SELECT fails + * @throws Exception If the data couldn't be loaded */ - public void load() throws SQLException { - String query = "SELECT * FROM lifts"; - PreparedStatement statement = con.prepareStatement(query); - ResultSet liftSet = statement.executeQuery(); - while (liftSet.next()) { - //Loading a lift... - - /* - * @todo Fix migrating from 1.12.2- to 1.13+ - * - byte to Facing for signs - * - Facing opposite for ropes - * - New materials - */ - - byte[] blob = liftSet.getBytes("liftData"); - String json = new String(blob); - - Lift lift = gson.fromJson(json, Lift.class); - DataManager.addLift(liftSet.getString("liftName"), lift); - - Bukkit.getLogger().info("[V10Lift] Loading lift " + liftSet.getString("liftName") + " from data..."); - } + public void load() throws Exception { + Collection lifts = data.getStorm().buildQuery(Lift.class) + .execute() + .join(); + V10LiftPlugin.getApi().getLifts().addAll(lifts); } /** - * Remove a lift from data + * Save the data to the database * - * @param liftName The name of the lift + * @throws SQLException If the data couldn't be saved */ - public void remove(String liftName) { - if (!DataManager.containsLift(liftName)) { - Bukkit.getLogger().info("[V10Lift] Removing lift " + liftName + " to data..."); - - Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> { - try { - String query = "DELETE FROM lifts WHERE liftName = ?"; - PreparedStatement statement = con.prepareStatement(query); - statement.setString(1, liftName); - statement.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - }); + public void save() throws SQLException { + for (Lift lift : V10LiftPlugin.getApi().getLifts()) { + data.getStorm().save(lift); } } /** - * Save all lifts to data - */ - public void save() { - for (Map.Entry entry : DataManager.getLifts().entrySet()) { - saveLift(entry.getKey(), entry.getValue(), true); - } - } - - /** - * Save a lift to data + * Remove a lift from the database * - * @param liftName The name of the lift - * @param lift The lift itself + * @param lift The lift to remove + * @throws SQLException If the lift couldn't be removed */ - public void saveLift(String liftName, Lift lift, boolean sync) { - Bukkit.getLogger().info("[V10Lift] Saving lift " + liftName + " to data..."); - - byte[] blob = gson.toJson(lift).getBytes(); - if (sync) { - updateLift(liftName, blob); - } else { - Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> updateLift(liftName, blob)); - } - } - - /** - * Update a lift in data - * - * @param liftName The name of the lift - * @param liftData The JSON blob of the lift object - */ - private void updateLift(String liftName, byte[] liftData) { - try { - String query = "INSERT INTO lifts (liftName, liftData) VALUES (?, ?)"; - PreparedStatement statement = con.prepareStatement(query); - statement.setString(1, liftName); - statement.setBytes(2, liftData); - statement.executeUpdate(); - } catch (SQLException ignored) { - } - - try { - String query2 = "UPDATE lifts SET liftData = ? WHERE liftName = ?"; - PreparedStatement statement2 = con.prepareStatement(query2); - statement2.setBytes(1, liftData); - statement2.setString(2, liftName); - statement2.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } + public void remove(Lift lift) throws SQLException { + data.getStorm().delete(lift); } /** diff --git a/src/main/java/tech/sbdevelopment/v10lift/sbutils/ConfigUpdater.java b/src/main/java/tech/sbdevelopment/v10lift/sbutils/ConfigUpdater.java deleted file mode 100644 index 2950262..0000000 --- a/src/main/java/tech/sbdevelopment/v10lift/sbutils/ConfigUpdater.java +++ /dev/null @@ -1,335 +0,0 @@ -package tech.sbdevelopment.v10lift.sbutils; - -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.plugin.Plugin; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.stream.Collectors; - -/** - * A class to update/add new sections/keys to your config while keeping your current values and keeping your comments - * Algorithm: - * Read the new file and scan for comments and ignored sections, if ignored section is found it is treated as a comment. - * Read and write each line of the new config, if the old config has value for the given key it writes that value in the new config. - * If a key has an attached comment above it, it is written first. - * - * @author tchristofferson - */ -public class ConfigUpdater { - /** - * Update a yaml file from a resource inside your plugin jar - * - * @param plugin You plugin - * @param resourceName The yaml file name to update from, typically config.yml - * @param toUpdate The yaml file to update - * @param ignoredSections List of sections to ignore and copy from the current config - * @throws IOException If an IOException occurs - */ - public static void update(Plugin plugin, String resourceName, File toUpdate, List ignoredSections) throws IOException { - BufferedReader newReader = new BufferedReader(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8)); - List newLines = newReader.lines().collect(Collectors.toList()); - newReader.close(); - - FileConfiguration oldConfig = YamlConfiguration.loadConfiguration(toUpdate); - FileConfiguration newConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource(resourceName))); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toUpdate), StandardCharsets.UTF_8)); - - List ignoredSectionsArrayList = new ArrayList<>(ignoredSections); - //ignoredSections can ONLY contain configurations sections - ignoredSectionsArrayList.removeIf(ignoredSection -> !newConfig.isConfigurationSection(ignoredSection)); - - DumperOptions options = new DumperOptions(); - - options.setSplitLines(false); - Yaml yaml = new Yaml(options); - Map comments = parseComments(newLines, ignoredSectionsArrayList, oldConfig, yaml); - write(newConfig, oldConfig, comments, ignoredSectionsArrayList, writer, yaml); - } - - //Write method doing the work. - //It checks if key has a comment associated with it and writes comment then the key and value - private static void write(FileConfiguration newConfig, FileConfiguration oldConfig, Map comments, List ignoredSections, BufferedWriter writer, Yaml yaml) throws IOException { - outer: - for (String key : newConfig.getKeys(true)) { - String[] keys = key.split("\\."); - String actualKey = keys[keys.length - 1]; - String comment = comments.remove(key); - - StringBuilder prefixBuilder = new StringBuilder(); - int indents = keys.length - 1; - appendPrefixSpaces(prefixBuilder, indents); - String prefixSpaces = prefixBuilder.toString(); - - if (comment != null) { - writer.write(comment);//No \n character necessary, new line is automatically at end of comment - } - - for (String ignoredSection : ignoredSections) { - if (key.startsWith(ignoredSection)) { - continue outer; - } - } - - Object newObj = newConfig.get(key); - Object oldObj = oldConfig.get(key); - - if (newObj instanceof ConfigurationSection && oldObj instanceof ConfigurationSection) { - //write the old section - writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) oldObj); - } else if (newObj instanceof ConfigurationSection) { - //write the new section, old value is no more - writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) newObj); - } else if (oldObj != null) { - //write the old object - write(oldObj, actualKey, prefixSpaces, yaml, writer); - } else { - //write new object - write(newObj, actualKey, prefixSpaces, yaml, writer); - } - } - - String danglingComments = comments.get(null); - - if (danglingComments != null) { - writer.write(danglingComments); - } - - writer.close(); - } - - //Doesn't work with configuration sections, must be an actual object - //Auto checks if it is serializable and writes to file - private static void write(Object obj, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException { - if (obj instanceof ConfigurationSerializable) { - writer.write(prefixSpaces + actualKey + ": " + yaml.dump(((ConfigurationSerializable) obj).serialize())); - } else if (obj instanceof String || obj instanceof Character) { - if (obj instanceof String) { - String s = (String) obj; - obj = s.replace("\n", "\\n"); - } - - writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj)); - } else if (obj instanceof List) { - writeList((List) obj, actualKey, prefixSpaces, yaml, writer); - } else { - writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj)); - } - } - - //Writes a configuration section - private static void writeSection(BufferedWriter writer, String actualKey, String prefixSpaces, ConfigurationSection section) throws IOException { - if (section.getKeys(false).isEmpty()) { - writer.write(prefixSpaces + actualKey + ": {}"); - } else { - writer.write(prefixSpaces + actualKey + ":"); - } - - writer.write("\n"); - } - - //Writes a list of any object - private static void writeList(List list, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException { - writer.write(getListAsString(list, actualKey, prefixSpaces, yaml)); - } - - private static String getListAsString(List list, String actualKey, String prefixSpaces, Yaml yaml) { - StringBuilder builder = new StringBuilder(prefixSpaces).append(actualKey).append(":"); - - if (list.isEmpty()) { - builder.append(" []\n"); - return builder.toString(); - } - - builder.append("\n"); - - for (int i = 0; i < list.size(); i++) { - Object o = list.get(i); - - if (o instanceof String || o instanceof Character) { - builder.append(prefixSpaces).append("- '").append(o).append("'"); - } else if (o instanceof List) { - builder.append(prefixSpaces).append("- ").append(yaml.dump(o)); - } else { - builder.append(prefixSpaces).append("- ").append(o); - } - - if (i != list.size()) { - builder.append("\n"); - } - } - - return builder.toString(); - } - - //Key is the config key, value = comment and/or ignored sections - //Parses comments, blank lines, and ignored sections - private static Map parseComments(List lines, List ignoredSections, FileConfiguration oldConfig, Yaml yaml) { - Map comments = new HashMap<>(); - StringBuilder builder = new StringBuilder(); - StringBuilder keyBuilder = new StringBuilder(); - int lastLineIndentCount = 0; - - outer: - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - if (line != null && line.trim().startsWith("-")) - continue; - if (line == null || line.trim().equals("") || line.trim().startsWith("#")) { - builder.append(line).append("\n"); - } else { - lastLineIndentCount = setFullKey(keyBuilder, i, lines, lastLineIndentCount); - - for (String ignoredSection : ignoredSections) { - if (keyBuilder.toString().equals(ignoredSection)) { - Object value = oldConfig.get(keyBuilder.toString()); - - if (value instanceof ConfigurationSection) - appendSection(builder, (ConfigurationSection) value, new StringBuilder(getPrefixSpaces(lastLineIndentCount)), yaml); - - continue outer; - } - } - - if (keyBuilder.length() > 0) { - comments.put(keyBuilder.toString(), builder.toString()); - builder.setLength(0); - } - } - } - - if (builder.length() > 0) { - comments.put(null, builder.toString()); - } - return comments; - } - - private static void appendSection(StringBuilder builder, ConfigurationSection section, StringBuilder prefixSpaces, Yaml yaml) { - builder.append(prefixSpaces).append(getKeyFromFullKey(section.getCurrentPath())).append(":"); - Set keys = section.getKeys(false); - - if (keys.isEmpty()) { - builder.append(" {}\n"); - return; - } - - builder.append("\n"); - prefixSpaces.append(" "); - - for (String key : keys) { - Object value = section.get(key); - String actualKey = getKeyFromFullKey(key); - - if (value instanceof ConfigurationSection) { - appendSection(builder, (ConfigurationSection) value, prefixSpaces, yaml); - prefixSpaces.setLength(prefixSpaces.length() - 2); - } else if (value instanceof List) { - builder.append(getListAsString((List) value, actualKey, prefixSpaces.toString(), yaml)); - } else { - builder.append(prefixSpaces).append(actualKey).append(": ").append(yaml.dump(value)); - } - } - } - - //Check how many times spaces make a jump of at least two - private static int countIndents(int index, List lines) { - - int currentSpaces = getSpaces(lines.get(index)); - int indents = 0; - - for (int i = index - 1; i >= 0; i--) { - String line = lines.get(i); - if (line == null || line.trim().equals("")) continue; - int newSpaces = getSpaces(lines.get(i)); - // differs at least two - if (newSpaces < currentSpaces - 1) { - indents++; - currentSpaces = newSpaces; - } - if (currentSpaces <= 1) break; - } - return indents; - } - - private static int getSpaces(String line) { - int spaces = 0; - for (char c : line.toCharArray()) { - if (c == ' ') { - spaces += 1; - } else { - break; - } - } - return spaces; - } - - //Ex. keyBuilder = key1.key2.key3 --> key1.key2 - private static void removeLastKey(StringBuilder keyBuilder) { - String temp = keyBuilder.toString(); - String[] keys = temp.split("\\."); - - if (keys.length == 1) { - keyBuilder.setLength(0); - return; - } - - temp = temp.substring(0, temp.length() - keys[keys.length - 1].length() - 1); - keyBuilder.setLength(temp.length()); - } - - private static String getKeyFromFullKey(String fullKey) { - String[] keys = fullKey.split("\\."); - return keys[keys.length - 1]; - } - - //Updates the keyBuilder and returns configLines number of indents - private static int setFullKey(StringBuilder keyBuilder, int index, List configLines, int lastLineIndentCount) { - - int currentIndents = countIndents(index, configLines); - String key = configLines.get(index).trim().split(":")[0]; - - if (keyBuilder.length() == 0) { - keyBuilder.append(key); - } else if (currentIndents == lastLineIndentCount) { - //Replace the last part of the key with current key - removeLastKey(keyBuilder); - - if (keyBuilder.length() > 0) { - keyBuilder.append("."); - } - - keyBuilder.append(key); - } else if (currentIndents > lastLineIndentCount) { - //Append current key to the keyBuilder - keyBuilder.append(".").append(key); - } else { - int difference = lastLineIndentCount - currentIndents; - - for (int i = 0; i < difference + 1; i++) { - removeLastKey(keyBuilder); - } - - if (keyBuilder.length() > 0) { - keyBuilder.append("."); - } - - keyBuilder.append(key); - } - - return currentIndents; - } - - private static String getPrefixSpaces(int indents) { - return new String(new char[Math.max(0, indents)]).replace("\0", " "); - } - - private static void appendPrefixSpaces(StringBuilder builder, int indents) { - builder.append(getPrefixSpaces(indents)); - } -} \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/sbutils/SQLiteDB.java b/src/main/java/tech/sbdevelopment/v10lift/sbutils/SQLiteDB.java deleted file mode 100644 index 57e659c..0000000 --- a/src/main/java/tech/sbdevelopment/v10lift/sbutils/SQLiteDB.java +++ /dev/null @@ -1,89 +0,0 @@ -package tech.sbdevelopment.v10lift.sbutils; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.bukkit.Bukkit; -import tech.sbdevelopment.v10lift.V10LiftPlugin; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; - -public class SQLiteDB { - private final String dbName; - private HikariDataSource source; - private Connection con; - - /** - * Initialize a new connection - * - * @param dbName The database name - */ - public SQLiteDB(String dbName) { - this.dbName = dbName; - - File dbFile = new File(V10LiftPlugin.getInstance().getDataFolder(), dbName + ".db"); - - if (!dbFile.exists()) { - try { - Bukkit.getLogger().info("[V10Lift] Generating the " + dbName + ".db!"); - if (!dbFile.createNewFile()) { - Bukkit.getLogger().severe("[V10Lift] Couldn't generate the " + dbName + ".db!"); - return; - } - } catch (IOException e) { - Bukkit.getLogger().info("[V10Lift] Couldn't generate the " + dbName + ".db!"); - return; - } - } - - HikariConfig config = new HikariConfig(); - config.setPoolName("V10Lift"); - config.setUsername(null); - config.setPassword(null); - config.setDriverClassName("org.sqlite.JDBC"); - config.setConnectionTestQuery("SELECT 1"); - config.setMaximumPoolSize(1); - - Properties prop = new Properties(); - prop.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss"); - - config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath()); - config.setDataSourceProperties(prop); - this.source = new HikariDataSource(config); - - try { - this.con = this.source.getConnection(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * Get the connection, to execute queries - *

- * CREATE TABLE - execute() - * SELECT - executeQuery() - * UPDATE - executeUpdate() - * - * @return Connection - */ - public Connection getConnection() { - return this.con; - } - - /** - * Close the connection - */ - public void closeSource() { - Bukkit.getLogger().info("[V10Lift] Closing the database connection for " + dbName + ".db!"); - try { - this.con.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - this.source.close(); - } -} diff --git a/src/main/java/tech/sbdevelopment/v10lift/sbutils/StormSQLiteDB.java b/src/main/java/tech/sbdevelopment/v10lift/sbutils/StormSQLiteDB.java new file mode 100644 index 0000000..5c345f4 --- /dev/null +++ b/src/main/java/tech/sbdevelopment/v10lift/sbutils/StormSQLiteDB.java @@ -0,0 +1,72 @@ +package tech.sbdevelopment.v10lift.sbutils; + +import com.craftmend.storm.Storm; +import com.craftmend.storm.connection.hikaricp.HikariDriver; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; + +public class StormSQLiteDB { + private final JavaPlugin plugin; + private final String dbName; + private final Storm storm; + + /** + * Initialize a new database source + * + * @param dbName The database name + */ + public StormSQLiteDB(JavaPlugin plugin, String dbName) throws SQLException { + this.plugin = plugin; + this.dbName = dbName; + + File dbFile = new File(plugin.getDataFolder(), dbName + ".db"); + + if (!dbFile.exists()) { + try { + plugin.getLogger().info("Generating the " + dbName + ".db..."); + if (!dbFile.createNewFile()) { + throw new IOException("Couldn't generate the " + dbName + ".db!"); + } + } catch (IOException e) { + throw new RuntimeException("Couldn't generate the " + dbName + ".db!", e); + } + } + + HikariConfig config = new HikariConfig(); + config.setPoolName(plugin.getName()); + config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath()); + config.setUsername(null); + config.setPassword(null); + config.setDriverClassName("org.sqlite.JDBC"); + config.setConnectionTestQuery("SELECT 1"); + config.setMaxLifetime(60000); + config.setIdleTimeout(45000); + config.setMinimumIdle(10); + config.setMaximumPoolSize(50); + + this.storm = new Storm(new HikariDriver(config)); + } + + /** + * Close the connection + */ + public void closeSource() { + plugin.getLogger().info("Closing the database connection for " + dbName + ".db..."); + this.storm.getDriver().close(); + } + + /** + * Get the database connection + * + * @return The database connection + */ + public Storm getStorm() { + return storm; + } +} \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/sbutils/UpdateManager.java b/src/main/java/tech/sbdevelopment/v10lift/sbutils/UpdateManager.java index 04da6fa..6332ac8 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/sbutils/UpdateManager.java +++ b/src/main/java/tech/sbdevelopment/v10lift/sbutils/UpdateManager.java @@ -1,6 +1,5 @@ package tech.sbdevelopment.v10lift.sbutils; -import com.google.gson.JsonParser; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; @@ -12,68 +11,62 @@ import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; import java.util.function.BiConsumer; /** - * Update class for SBDevelopment + * Update checker class * * @author Stijn [SBDeveloper] - * @version 2.1 [19-11-2021] - This class supports both the v2 Spiget and v2 SBDUpdate API - * - *

© Stijn Bannink [stijnbannink23@gmail.com] - All rights reserved.

* @since 05-03-2020 + * @version 2.2 [17-04-2022] - Added Polymart support */ public class UpdateManager { - private static final JsonParser parser = new JsonParser(); - - private static final String SPIGOT_API = "https://api.spiget.org/v2/resources/%s/versions/latest"; + private static final String SPIGOT_API = "https://api.spigotmc.org/legacy/update.php?resource=%d"; private static final String SPIGOT_DOWNLOAD = "https://api.spiget.org/v2/resources/%s/download"; - private static final String SBDPLUGINS_API = "https://updates.sbdplugins.nl/api/v2/plugins/%d"; - private static final String SBDPLUGINS_DOWNLOAD = "https://updates.sbdplugins.nl/api/v2/download/%d"; + private static final String POLYMART_API = "https://api.polymart.org/v1/getResourceInfoSimple/?resource_id=%d&key=version"; + private static final String POLYMART_DOWNLOAD = "https://api.polymart.org/v1/requestUpdateURL/?inject_version=%d&resource_id=%d&user_id=%d&nonce=%d&download_agent=%d&download_time=%d&download_token=%s"; private final Plugin plugin; private final Version currentVersion; - private final int resourceID; private final CheckType type; - private final String license; + + //Spigot & Polymart + private final int resourceID; + + //Polymart only + private int injector_version; + private int user_id; + private int nonce; + private int download_agent; + private int download_time; + private String download_token; private BiConsumer versionResponse; private BiConsumer downloadResponse; /** - * Construct a new UpdateManager for Spigot + * Construct a new UpdateManager * - * @param plugin The javaplugin (Main class) - * @param resourceID The resourceID on spigot/sbdplugins + * @param plugin The plugin instance */ - public UpdateManager(Plugin plugin, int resourceID) { + public UpdateManager(Plugin plugin, CheckType type) { this.plugin = plugin; this.currentVersion = new Version(plugin.getDescription().getVersion()); - this.resourceID = resourceID; - this.type = CheckType.SPIGOT; - this.license = null; - } - - /** - * Construct a new UpdateManager for SBDPlugins - * - * @param plugin The javaplugin (Main class) - * @param resourceID The resourceID on spigot/sbdplugins - * @param license The license for the download - */ - public UpdateManager(Plugin plugin, int resourceID, String license) { - this.plugin = plugin; - this.currentVersion = new Version(plugin.getDescription().getVersion()); - this.resourceID = resourceID; - this.type = CheckType.SBDPLUGINS; - this.license = license; + this.type = type; + this.resourceID = Integer.parseInt("%%__RESOURCE__%%"); + if (type == CheckType.POLYMART_PAID) { + this.injector_version = Integer.parseInt("%%__INJECT_VER__%%"); + this.user_id = Integer.parseInt("%%__USER__%%"); + this.nonce = Integer.parseInt("%%__NONCE__%%"); + this.download_agent = Integer.parseInt("%%__AGENT__%%"); + this.download_time = Integer.parseInt("%%__TIMESTAMP__%%"); + this.download_token = "%%__VERIFY_TOKEN__%%"; + } } /** * Handle the response given by check(); - * * @param versionResponse The response * @return The updatemanager */ @@ -93,23 +86,16 @@ public class UpdateManager { public void check() { Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { try { - BufferedReader in = null; - if (type == CheckType.SPIGOT) { - HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("User-Agent", "Mozilla/5.0"); - - in = new BufferedReader(new InputStreamReader(con.getInputStream())); - } else if (type == CheckType.SBDPLUGINS) { - HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_API, this.resourceID)).openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("User-Agent", "Mozilla/5.0"); - - in = new BufferedReader(new InputStreamReader(con.getInputStream())); + HttpsURLConnection con; + if (type == CheckType.POLYMART_PAID) { + con = (HttpsURLConnection) new URL(String.format(POLYMART_API, this.resourceID)).openConnection(); + } else { + con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection(); } + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", "SBDChecker/2.1"); - if (in == null) return; - + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { @@ -117,10 +103,7 @@ public class UpdateManager { } in.close(); - String version = parser.parse(response.toString()).getAsJsonObject().get(type == CheckType.SPIGOT ? "name" : "version").getAsString(); - if (version == null) return; - - Version onlineVersion = new Version(version); + Version onlineVersion = new Version(response.toString()); VersionResponse verRes = this.currentVersion.check(onlineVersion); @@ -153,35 +136,16 @@ public class UpdateManager { ReadableByteChannel channel; try { //https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java - int response; - InputStream stream; HttpsURLConnection connection; - if (type == CheckType.SBDPLUGINS) { - connection = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_DOWNLOAD, this.resourceID)).openConnection(); - - String urlParameters = "license=" + license + "&port=" + Bukkit.getPort(); - byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); - int postDataLength = postData.length; - - connection.setRequestMethod("GET"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("charset", "utf-8"); - connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - connection.setDoOutput(true); - - DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); - wr.write(postData); - wr.close(); + if (type == CheckType.POLYMART_PAID) { + connection = (HttpsURLConnection) new URL(String.format(POLYMART_DOWNLOAD, this.injector_version, this.resourceID, this.user_id, this.nonce, this.download_agent, this.download_time, this.download_token)).openConnection(); } else { connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); } + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - response = connection.getResponseCode(); - stream = connection.getInputStream(); - - if (response != 200) { + InputStream stream = connection.getInputStream(); + if (connection.getResponseCode() != 200) { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String inputLine; @@ -191,7 +155,7 @@ public class UpdateManager { } in.close(); - throw new RuntimeException("Download returned status #" + response, new Throwable(responsestr.toString())); + throw new RuntimeException("Download returned status #" + connection.getResponseCode(), new Throwable(responsestr.toString())); } channel = Channels.newChannel(stream); @@ -234,9 +198,7 @@ public class UpdateManager { } private File getPluginFile() { - if (!(this.plugin instanceof JavaPlugin)) { - return null; - } + if (!(this.plugin instanceof JavaPlugin)) { return null; } try { Method method = JavaPlugin.class.getDeclaredMethod("getFile"); method.setAccessible(true); @@ -246,8 +208,8 @@ public class UpdateManager { } } - private enum CheckType { - SPIGOT, SBDPLUGINS + public enum CheckType { + SPIGOT, POLYMART_PAID } public enum VersionResponse { @@ -265,18 +227,18 @@ public class UpdateManager { private final String version; - private Version(String version) { - if (version == null) - throw new IllegalArgumentException("Version can not be null"); - if (!version.matches("[0-9]+(\\.[0-9]+)*")) - throw new IllegalArgumentException("Invalid version format"); - this.version = version; - } - public final String get() { return this.version; } + private Version(String version) { + if(version == null) + throw new IllegalArgumentException("Version can not be null"); + if(!version.matches("[0-9]+(\\.[0-9]+)*")) + throw new IllegalArgumentException("Invalid version format"); + this.version = version; + } + private VersionResponse check(Version that) { String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); @@ -285,12 +247,12 @@ public class UpdateManager { for (int i = 0; i < length; i++) { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; - if (thisPart < thatPart) + if(thisPart < thatPart) return VersionResponse.FOUND_NEW; - if (thisPart > thatPart) + if(thisPart > thatPart) return VersionResponse.THIS_NEWER; } return VersionResponse.LATEST; } } -} +} \ No newline at end of file diff --git a/src/main/java/tech/sbdevelopment/v10lift/utils/ConfigUtil.java b/src/main/java/tech/sbdevelopment/v10lift/utils/ConfigUtil.java index 1cc90e9..c7c4432 100644 --- a/src/main/java/tech/sbdevelopment/v10lift/utils/ConfigUtil.java +++ b/src/main/java/tech/sbdevelopment/v10lift/utils/ConfigUtil.java @@ -26,14 +26,14 @@ public class ConfigUtil { } /** - * Send a message from the messages.yml without variables + * Send a message from the lang_en.yml without variables * * @param p The commandsender to send it to * @param path The path to look for */ public static void sendMessage(CommandSender p, @Nonnull String path) { if (V10LiftPlugin.getMessages().getFile().get(path) == null) { - throw new NullPointerException("Message " + path + " not found in messages.yml!"); + throw new NullPointerException("Message " + path + " not found in lang_en.yml!"); } if (V10LiftPlugin.getMessages().getFile().isList(path)) { @@ -48,7 +48,7 @@ public class ConfigUtil { } /** - * Get a message from the messages.yml with variables + * Get a message from the lang_en.yml with variables * * @param p The commandsender to send it to * @param path The path to look for @@ -56,7 +56,7 @@ public class ConfigUtil { */ public static void sendMessage(CommandSender p, @Nonnull String path, Map replacement) { if (V10LiftPlugin.getMessages().getFile().get(path) == null) { - throw new NullPointerException("Message " + path + " not found in messages.yml!"); + throw new NullPointerException("Message " + path + " not found in lang_en.yml!"); } if (V10LiftPlugin.getMessages().getFile().isList(path)) { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 8ce27e2..d2f4f5c 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,3 +1,6 @@ +# The language to use for the messages +Locale: en + # Generic sign texts SignText: "[v10lift]" DefectText: "&kDefect!" diff --git a/src/main/resources/locale/lang_en.yml b/src/main/resources/locale/lang_en.yml new file mode 100644 index 0000000..2bab2fe --- /dev/null +++ b/src/main/resources/locale/lang_en.yml @@ -0,0 +1,147 @@ +v10lift: + general: + nopermission: '&cYou don''t have the permission to do this.' + playeronly: '&cOnly players can do this.' + incorrectusage: '&cPlease use %Command% instead' + internalerror: '&cSomething went wrong internally.' + doesntexists: '&cThere are no lifts with that name.' + alreadyexists: '&cA lift with that name already exists.' + switchonedit: '&cEnable editor mode before doing this.' + detectionfailed: '&cAutomatic floor detection failed!' + floordoesntexists: '&cThe floor %Name% doesn''t exists!' + nowhitelistpermission: '&cYou can''t go to that floor!' + nofloors: '&cThis elevator has no floors!' + removeliftfirst: '&cYou can''t do this! Remove the lift first.' + removeropefirst: '&cYou can''t do this! Remove the rope first.' + removedoorfirst: '&cYou can''t do this! Remove the door first.' + create: + addblocks: > + &aOkay, now add all the blocks from the cab by right-clicking them. + &awhen finished, type: /v10lift create + noblocks: '&cYou must add blocks first.' + created: '&aSuccessfully created lift %Name%.' + delete: + notremoved: '&cThe lift %Name% couldn''t be removed.' + removed: '&aSuccessfully removed lift %Name%.' + rename: + renamed: '&aLift successfully renamed!' + edit: + stillineditmode: '&cYou are still in editor mode.' + turnedon: '&aEnabled editor.' + turnedoff: '&aDisabled editor.' + floor: + tohigh: '&cThat floor is too high!' + alreadyexists: '&cThat floor already exists!' + doesntexists: '&cThat floor doesn''t exists!' + added: '&aFloor successfully added!' + removed: '&aFloor successfully removed!' + renamed: '&aFloor successfully renamed!' + input: + stilladjusting: '&cYou are still adjusting an input!' + nothingtoremove: '&cThere is no input to remove!' + alreadyadded: '&cThis block has already been chosen as an input. Choose another block!' + noinput: '&cThis block is not an input. Choose another block!' + rightclick: '&aNow right click on the input block!' + created: '&aInput created!' + removed: '&aInput removed!' + offlineinput: + stilladjusting: '&cYou are still adjusting an offline input!' + nothingtoremove: '&cThere is no offline input to remove!' + alreadyadded: '&cThis block has already been chosen as an offline input. Choose another block!' + noinput: '&cThis block is not an offline input. Choose another block!' + rightclick: '&aNow right click on the offline input block!' + created: '&aOffline input created!' + removed: '&aOffline input removed!' + build: + disabled: '&aConstruction mode disabled!' + enabled: > + &aNow right-click on the elevator blocks! + &aThen do /v10lift build to save it! + blockadded: '&aBlock added to the elevator.' + blockremoved: '&6Block removed from the elevator.' + blacklistedmaterial: '&cThe material %Name% cannot be used!' + noselection: '&cYou must select a region with the WorldEdit wand first!' + unsupportedselection: '&cThe selection must be cuboid or polygonal!' + blocksadded: '&aBlocks added to the elevator.' + blocksfailed: '&cNot all blocks could be added to the elevator. Failure amount: %Failed%' + worldeditnotenabled: '&cWorldEdit is not enabled on this server!' + rope: + stilladjusting: '&cYou are still adjusting a rope.' + onlyup: '&cA rope can only go up!' + onlyonematerial: '&cThe rope must be of the same material!' + alreadyarope: '&cPart of the rope is already part of another rope!' + notarope: '&cThis block is not part of the rope.' + blacklistedmaterial: '&cThe rope is built of blacklisted blocks!' + add: '&aNow right-click on the beginning and the end of the rope.' + delete: '&aNow right-click on the rope.' + clickonend: '&6Now right-click on the end of the rope!' + partremoved: > + &6Start removed! + &6Now right-click on the end of the rope! + created: '&aRope created.' + removed: '&aRope removed.' + door: + blacklistedmaterial: '&cThe material %Name% is currently not supported!' + disabled: '&aDoor editor mode disabled!' + enabled: > + &aNow right-click on the door blocks! (If they are real doors, click on the bottom block) + &aThen do /v10lift door to save it. + created: '&aDoor created.' + removed: '&6Door removed.' + whitelist: + group: + vaultnotfound: '&cYou can''t add a group when Vault is not found.' + notfound: '&cThe group %Name% is not found.' + alreadycontains: '&cThe whitelist already contains this group!' + doesntcontains: '&cThe whitelist doesn''t contain this group!' + added: '&aGroup added to whitelist!' + removed: '&aGroup removed from whitelist!' + player: + notfound: '&cThe player %Name% could not be found.' + alreadycontains: '&cThis user is already on the whitelist' + doesntcontains: '&cThis user isn''t on the whitelist' + added: '&aUser added to whitelist!' + removed: '&aUser removed from whitelist!' + whois: + usewithoutname: '&cYou need to be a player to use this command without a name.' + notalift: '&cThis block is not part of a lift.' + withoutname: '&aNow right-click on the block you want to check.' + speed: + wrongspeed: '&cThe speed %Speed% is incorrect.' + changed: '&aUpdated lift speed!' + sound: + turnedon: '&aSounds are now turned on!' + turnedoff: '&aSounds are now turned off!' + realistic: + turnedon: '&aRealistic mode turned on!' + turnedoff: '&aRealistic mode turned off!' + disable: + alreadydefective: '&cThis lift is already defective!' + disabled: '&aLift disabled!' + repair: + notdefective: '&cThis lift isn''t defective!' + itemsneeded: '&cYou need %Amount%x %ItemName%!' + repaired: '&aYou successfully repaired the lift!' + abort: + nothingtocancel: '&cOops! You can''t cancel anything.' + cancelled: '&6Cancelled.' + reload: + reloaded: '&6Plugin reloaded successfully!' + start: + nonplayer: '&cPlease give a name as a non-player!' + started: '&aLift %Name% started.' + stop: + nonplayer: '&cPlease give a name as a non-player!' + nomovingtasks: '&cLift %Name% doesn''t contain any moving tasks!' + started: '&aLift %Name% stopped.' + liftsign: + noname: '&cNo lift name given!' + created: '&aLift sign created!' + removed: '&6Lift sign removed!' + list: + nolifts: '&cThere are no lifts!' + header: '&6Lifts:' + lift: '&6- %Name%' + setoffline: + disabled: '&aThe lift is now offline!' + enabled: '&aThe lift is now online!' \ No newline at end of file diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml deleted file mode 100644 index ad600fd..0000000 --- a/src/main/resources/messages.yml +++ /dev/null @@ -1,175 +0,0 @@ -General: - NoPermission: '&cYou don''t have the permission to do this.' - PlayerOnly: '&cOnly players can do this.' - IncorrectUsage: '&cPlease use %Command% instead' - InternalError: '&cSomething went wrong internally.' - - DoesntExists: '&cThere are no lifts with that name.' - AlreadyExists: '&cA lift with that name already exists.' - SwitchOnEdit: '&cEnable editor mode before doing this.' - DetectionFailed: '&cAutomatic floor detection failed!' - FloorDoesntExists: '&cThe floor %Name% doesn''t exists!' - - NoWhitelistPermission: '&cYou can''t go to that floor!' - NoFloors: '&cThis elevator has no floors!' - - RemoveLiftFirst: '&cYou can''t do this! Remove the lift first.' - RemoveRopeFirst: '&cYou can''t do this! Remove the rope first.' - RemoveDoorFirst: '&cYou can''t do this! Remove the door first.' - -Create: - AddBlocks: |- - &aOkay, now add all the blocks from the cab by right-clicking them. - &awhen finished, type: /v10lift create - NoBlocks: '&cYou must add blocks first.' - Created: '&aSuccessfully created lift %Name%.' - -Delete: - NotRemoved: '&cThe lift %Name% couldn''t be removed.' - Removed: '&aSuccessfully removed lift %Name%.' - -Rename: - Renamed: '&aLift successfully renamed!' - -Edit: - StillInEditMode: '&cYou are still in editor mode.' - TurnedOn: '&aEnabled editor.' - TurnedOff: '&aDisabled editor.' - -Floor: - ToHigh: '&cThat floor is too high!' - AlreadyExists: '&cThat floor already exists!' - DoesntExists: '&cThat floor doesn''t exists!' - Added: '&aFloor successfully added!' - Removed: '&aFloor successfully removed!' - Renamed: '&aFloor successfully renamed!' - -Input: - StillAdjusting: '&cYou are still adjusting an input!' - NothingToRemove: '&cThere is no input to remove!' - AlreadyAdded: '&cThis block has already been chosen as an input. Choose another - block!' - NoInput: '&cThis block is not an input. Choose another block!' - RightClick: '&aNow right click on the input block!' - Created: '&aInput created!' - Removed: '&aInput removed!' - -OfflineInput: - StillAdjusting: '&cYou are still adjusting an offline input!' - NothingToRemove: '&cThere is no offline input to remove!' - AlreadyAdded: '&cThis block has already been chosen as an offline input. Choose - another block!' - NoInput: '&cThis block is not an offline input. Choose another block!' - RightClick: '&aNow right click on the offline input block!' - Created: '&aOffline input created!' - Removed: '&aOffline input removed!' - -Build: - Disabled: '&aConstruction mode disabled!' - Enabled: |- - &aNow right-click on the elevator blocks! - &aThen do /v10lift build to save it! - BlockAdded: '&aBlock added to the elevator.' - BlockRemoved: '&6Block removed from the elevator.' - BlacklistedMaterial: '&cThe material %Name% cannot be used!' - NoSelection: '&cYou must select a region with the WorldEdit wand first!' - UnsupportedSelection: '&cThe selection must be cuboid or polygonal!' - BlocksAdded: '&aBlocks added to the elevator.' - BlocksFailed: '&cNot all blocks could be added to the elevator. Failure amount: %Failed%' - WorldEditNotEnabled: '&cWorldEdit is not enabled on this server!' - -Rope: - StillAdjusting: '&cYou are still adjusting a rope.' - OnlyUp: '&cA rope can only go up!' - OnlyOneMaterial: '&cThe rope must be of the same material!' - AlreadyARope: '&cPart of the rope is already part of another rope!' - NotARope: '&cThis block is not part of the rope.' - BlacklistedMaterial: '&cThe rope is build of blacklisted blocks!' - Add: '&aNow right-click on the beginning and the end of the rope.' - Delete: '&aNow right-click on the rope.' - ClickOnEnd: '&6Now right-click on the end of the rope!' - PartRemoved: |- - &6Start removed! - &6Now right-click on the end of the rope! - Created: '&aRope created.' - Removed: '&aRope removed.' - -Door: - BlacklistedMaterial: '&cThe material %Name% is currently not supported!' - Disabled: '&aDoor editor mode disabled!' - Enabled: |- - &aNow right-click on the door blocks! (If it are real doors, click on the bottom block) - &aThen do /v10lift door to save it. - Created: '&aDoor created.' - Removed: '&6Door removed.' - -Whitelist: - Group: - VaultNotFound: '&cYou can''t add a group when Vault is not found.' - NotFound: '&cThe group %Name% is not found.' - AlreadyContains: '&cThe whitelist already contains this group!' - DoesntContains: '&cThe whitelist doesn''t contain this group!' - Added: '&aGroup added to whitelist!' - Removed: '&aGroup removed from whitelist!' - Player: - NotFound: '&cThe player %Name% could not be found.' - AlreadyContains: '&cThis user is already on the whitelist' - DoesntContains: '&cThis user isn''t on the whitelist' - Added: '&aUser added to whitelist!' - Removed: '&aUser removed from whitelist!' - -Whois: - UseWithoutName: '&cYou need to be a player to use this command without name.' - NotALift: '&cThis block is not part of a lift.' - WithoutName: '&aNow right-click on the block you want to check.' - -Speed: - WrongSpeed: '&cThe speed %Speed% is incorrect.' - Changed: '&aUpdated lift speed!' - -Sound: - TurnedOn: '&aSounds are now turned on!' - TurnedOff: '&aSounds are now turned off!' - -Realistic: - TurnedOn: '&aRealistic mode turned on!' - TurnedOff: '&aRealistic mode turned off!' - -Disable: - AlreadyDefective: '&cThis lift is already defective!' - Disabled: '&aLift disabled!' - -Repair: - NotDefective: '&cThis lift isn''t defective!' - ItemsNeeded: '&cYou need %Amount%x %ItemName%!' - Repaired: '&aYou successfully repaired the lift!' - -Abort: - NothingToCancel: '&cOops! You can''t cancel anything.' - Cancelled: '&6Cancelled.' - -Reload: - Reloaded: '&6Plugin reloaded successfully!' - -Start: - NonPlayer: '&cPlease give a name as non-player!' - Started: '&aLift %Name% started.' - -Stop: - NonPlayer: '&cPlease give a name as non-player!' - NoMovingTasks: '&cLift %Name% doesn''t contain any movingtasks!' - Started: '&aLift %Name% stopped.' - -LiftSign: - NoName: '&cNo lift name given!' - Created: '&aLift sign created!' - Removed: '&6Lift sign removed!' - -List: - NoLifts: '&cThere are no lifts!' - Header: '&6Lifts:' - Lift: '&6- %Name%' - -SetOffline: - Disabled: '&aThe lift is now offline!' - Enabled: '&aThe lift is now online!' \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 1316ce0..379cba8 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -3,27 +3,4 @@ main: tech.sbdevelopment.v10lift.V10LiftPlugin version: ${project.version} api-version: "1.13" author: SBDeveloper -softdepend: ["Vault", "WorldEdit"] -commands: - v10lift: - description: The V10Lift Command -permissions: - v10lift.admin: - description: The full power admin permission - default: op - v10lift.build: - description: The permission to build a lift - v10lift.reload: - description: Reload the plugin - v10lift.repair: - description: Repair a lift - v10lift.disable: - description: Disable a lift - v10lift.start: - description: Start a lift - v10lift.stop: - description: Stop a lift - v10lift.list: - description: List all lifts - v10lift.setoffline: - description: Set a lift offline / online \ No newline at end of file +softdepend: ["Vault", "WorldEdit"] \ No newline at end of file