From 42fa6ed8d7ddb23322fffd0f1c9a2e5b0d77192f Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Fri, 12 Feb 2021 00:26:47 +0100 Subject: [PATCH] Huge refactoring Splits Portal into Portal and PortalHandler Adds EconomyHelper to make messaging of economy string easier Adds a lot of missing comments Adds vehicle teleportation again, but it needs a lot of changes to work properly --- .../net/knarcraft/stargate/BlockLocation.java | 21 - .../knarcraft/stargate/EconomyHandler.java | 19 - .../java/net/knarcraft/stargate/Gate.java | 21 - .../knarcraft/stargate/LanguageLoader.java | 19 - .../java/net/knarcraft/stargate/Portal.java | 923 +++--------------- .../net/knarcraft/stargate/PortalHandler.java | 865 ++++++++++++++++ .../stargate/RelativeBlockVector.java | 34 +- .../java/net/knarcraft/stargate/Stargate.java | 40 +- .../java/net/knarcraft/stargate/TwoTuple.java | 39 + .../stargate/event/StargateAccessEvent.java | 46 +- .../stargate/event/StargateActivateEvent.java | 21 +- .../stargate/event/StargateCloseEvent.java | 21 +- .../stargate/event/StargateCreateEvent.java | 21 +- .../event/StargateDeactivateEvent.java | 21 +- .../stargate/event/StargateDestroyEvent.java | 60 +- .../stargate/event/StargateEvent.java | 20 +- .../stargate/event/StargateOpenEvent.java | 21 +- .../stargate/event/StargatePortalEvent.java | 21 +- .../stargate/listener/BlockEventListener.java | 126 ++- .../stargate/listener/BungeeCordListener.java | 6 +- .../listener/EntityEventListener.java | 20 +- .../listener/PlayerEventsListener.java | 88 +- .../listener/VehicleEventListener.java | 146 ++- .../stargate/listener/WorldEventListener.java | 7 +- .../stargate/utility/EconomyHelper.java | 113 +++ 25 files changed, 1470 insertions(+), 1269 deletions(-) create mode 100644 src/main/java/net/knarcraft/stargate/PortalHandler.java create mode 100644 src/main/java/net/knarcraft/stargate/TwoTuple.java create mode 100644 src/main/java/net/knarcraft/stargate/utility/EconomyHelper.java diff --git a/src/main/java/net/knarcraft/stargate/BlockLocation.java b/src/main/java/net/knarcraft/stargate/BlockLocation.java index 49d9db2..59d6c62 100644 --- a/src/main/java/net/knarcraft/stargate/BlockLocation.java +++ b/src/main/java/net/knarcraft/stargate/BlockLocation.java @@ -9,27 +9,6 @@ import org.bukkit.block.data.BlockData; import org.bukkit.block.data.type.Sign; import org.bukkit.block.data.type.WallSign; -/* - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - /** * This class represents a block location * diff --git a/src/main/java/net/knarcraft/stargate/EconomyHandler.java b/src/main/java/net/knarcraft/stargate/EconomyHandler.java index 1d7f984..83bd86c 100644 --- a/src/main/java/net/knarcraft/stargate/EconomyHandler.java +++ b/src/main/java/net/knarcraft/stargate/EconomyHandler.java @@ -9,25 +9,6 @@ import org.bukkit.plugin.RegisteredServiceProvider; import java.util.UUID; -/* - stargate - A portal plugin for Bukkit - Copyright (C) 2011, 2012 Steven "Drakia" Scott - Copyright (C) 2021 Kristian Knarvik -

- This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. -

- This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. -

- You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - */ - /** * This handler handles economy actions such as payment for using a gate */ diff --git a/src/main/java/net/knarcraft/stargate/Gate.java b/src/main/java/net/knarcraft/stargate/Gate.java index 83ec460..a499453 100644 --- a/src/main/java/net/knarcraft/stargate/Gate.java +++ b/src/main/java/net/knarcraft/stargate/Gate.java @@ -15,27 +15,6 @@ import java.util.Map; import java.util.Scanner; import java.util.logging.Level; -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - public class Gate { private static final Character ANYTHING = ' '; diff --git a/src/main/java/net/knarcraft/stargate/LanguageLoader.java b/src/main/java/net/knarcraft/stargate/LanguageLoader.java index b539696..bc74785 100644 --- a/src/main/java/net/knarcraft/stargate/LanguageLoader.java +++ b/src/main/java/net/knarcraft/stargate/LanguageLoader.java @@ -18,25 +18,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -/* - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - /** * This class is responsible for loading all strings which are translated into several languages */ diff --git a/src/main/java/net/knarcraft/stargate/Portal.java b/src/main/java/net/knarcraft/stargate/Portal.java index 9fbb522..4b9db19 100644 --- a/src/main/java/net/knarcraft/stargate/Portal.java +++ b/src/main/java/net/knarcraft/stargate/Portal.java @@ -2,81 +2,36 @@ package net.knarcraft.stargate; import net.knarcraft.stargate.event.StargateActivateEvent; import net.knarcraft.stargate.event.StargateCloseEvent; -import net.knarcraft.stargate.event.StargateCreateEvent; import net.knarcraft.stargate.event.StargateDeactivateEvent; import net.knarcraft.stargate.event.StargateOpenEvent; import net.knarcraft.stargate.event.StargatePortalEvent; import org.bukkit.Axis; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.OfflinePlayer; import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.block.data.Bisected; import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; import org.bukkit.block.data.Powerable; -import org.bukkit.block.data.type.WallSign; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; import org.bukkit.entity.minecart.StorageMinecart; -import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.util.Vector; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Random; -import java.util.Scanner; import java.util.UUID; import java.util.logging.Level; -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - public class Portal { - // Static variables used to store portal lists - private static final HashMap lookupBlocks = new HashMap<>(); - private static final HashMap lookupEntrances = new HashMap<>(); - private static final HashMap lookupControls = new HashMap<>(); - private static final ArrayList allPortals = new ArrayList<>(); - private static final HashMap> allPortalsNet = new HashMap<>(); - private static final HashMap> lookupNamesNet = new HashMap<>(); - - // A list of Bungee gates - private static final HashMap bungeePortals = new HashMap<>(); - // Gate location block info private final BlockLocation topLeft; private final int modX; @@ -93,11 +48,11 @@ public class Portal { // Gate information private String name; private String destination; - private String lastDest = ""; + private String lastDestination = ""; private String network; private final Gate gate; - private String ownerName = ""; - private UUID ownerUUID = null; + private String ownerName; + private UUID ownerUUID; private final World world; private boolean verified; private boolean fixed; @@ -105,7 +60,7 @@ public class Portal { // Options private boolean hidden = false; private boolean alwaysOn = false; - private boolean priv = false; + private boolean isPrivate = false; private boolean free = false; private boolean backwards = false; private boolean show = false; @@ -120,11 +75,45 @@ public class Portal { private boolean isOpen = false; private long openTime; - private Portal(BlockLocation topLeft, int modX, int modZ, - float rotX, BlockLocation id, BlockLocation button, - String dest, String name, - boolean verified, String network, Gate gate, UUID ownerUUID, String ownerName, - boolean hidden, boolean alwaysOn, boolean priv, boolean free, boolean backwards, boolean show, boolean noNetwork, boolean random, boolean bungee) { + Portal(BlockLocation topLeft, int modX, int modZ, float rotX, BlockLocation id, BlockLocation button, + String dest, String name, boolean verified, String network, Gate gate, UUID ownerUUID, String ownerName) { + this.topLeft = topLeft; + this.modX = modX; + this.modZ = modZ; + this.rotX = rotX; + this.rot = rotX == 0.0F || rotX == 180.0F ? Axis.X : Axis.Z; + this.id = id; + this.destination = dest; + this.button = button; + this.verified = verified; + this.network = network; + this.name = name; + this.gate = gate; + this.ownerUUID = ownerUUID; + this.ownerName = ownerName; + this.world = topLeft.getWorld(); + this.fixed = dest.length() > 0 || this.random || this.bungee; + + if (this.isAlwaysOn() && !this.isFixed()) { + this.alwaysOn = false; + Stargate.debug("Portal", "Can not create a non-fixed always-on gate. Setting AlwaysOn = false"); + } + + if (this.random && !this.isAlwaysOn()) { + this.alwaysOn = true; + Stargate.debug("Portal", "Gate marked as random, set to always-on"); + } + + if (verified) { + this.drawSign(); + } + } + + Portal(BlockLocation topLeft, int modX, int modZ, + float rotX, BlockLocation id, BlockLocation button, + String dest, String name, + boolean verified, String network, Gate gate, UUID ownerUUID, String ownerName, + boolean hidden, boolean alwaysOn, boolean isPrivate, boolean free, boolean backwards, boolean show, boolean noNetwork, boolean random, boolean bungee) { this.topLeft = topLeft; this.modX = modX; this.modZ = modZ; @@ -141,7 +130,7 @@ public class Portal { this.ownerName = ownerName; this.hidden = hidden; this.alwaysOn = alwaysOn; - this.priv = priv; + this.isPrivate = isPrivate; this.free = free; this.backwards = backwards; this.show = show; @@ -182,7 +171,7 @@ public class Portal { } public boolean isPrivate() { - return priv; + return isPrivate; } public boolean isFree() { @@ -209,36 +198,54 @@ public class Portal { return bungee; } - public void setAlwaysOn(boolean alwaysOn) { + public Portal setAlwaysOn(boolean alwaysOn) { this.alwaysOn = alwaysOn; + return this; } - public void setHidden(boolean hidden) { + public Portal setHidden(boolean hidden) { this.hidden = hidden; + return this; } - public void setPrivate(boolean priv) { - this.priv = priv; + public Portal setPrivate(boolean priv) { + this.isPrivate = priv; + return this; } - public void setFree(boolean free) { + public Portal setFree(boolean free) { this.free = free; + return this; } - public void setBackwards(boolean backwards) { + public Portal setBackwards(boolean backwards) { this.backwards = backwards; + return this; } - public void setShown(boolean show) { + public Portal setShown(boolean show) { this.show = show; + return this; } - public void setNoNetwork(boolean noNetwork) { + + public Portal setNoNetwork(boolean noNetwork) { this.noNetwork = noNetwork; + return this; } - public void setRandom(boolean random) { + public Portal setRandom(boolean random) { this.random = random; + return this; + } + + public Portal setBungee(boolean bungee) { + this.bungee = bungee; + return this; + } + + public void setFixed(boolean fixed) { + this.fixed = fixed; } /** @@ -280,15 +287,15 @@ public class Portal { public Portal getDestination(Player player) { if (isRandom()) { - destinations = getDestinations(player, getNetwork()); + destinations = PortalHandler.getDestinations(player, getNetwork()); if (destinations.size() == 0) { return null; } String dest = destinations.get((new Random()).nextInt(destinations.size())); destinations.clear(); - return Portal.getByName(dest, getNetwork()); + return PortalHandler.getByName(dest, getNetwork()); } - return Portal.getByName(destination, getNetwork()); + return PortalHandler.getByName(destination, getNetwork()); } public Portal getDestination() { @@ -374,10 +381,6 @@ public class Portal { this.button = button; } - public static ArrayList getNetwork(String network) { - return allPortalsNet.get(network.toLowerCase()); - } - public boolean open(boolean force) { return open(null, force); } @@ -513,7 +516,8 @@ public class Portal { } public void teleport(final Vehicle vehicle) { - Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), vehicle.getLocation().getZ()); + Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), + vehicle.getLocation().getZ()); Location exit = getExit(traveller); double velocity = vehicle.getVelocity().length(); @@ -526,25 +530,33 @@ public class Portal { newVelocity.multiply(velocity); List passengers = vehicle.getPassengers(); + World vehicleWorld = exit.getWorld(); + if (vehicleWorld == null) { + Stargate.log.warning(Stargate.getString("prefix") + "Unable to get the world to teleport the vehicle to"); + return; + } + Vehicle mineCart = vehicleWorld.spawn(exit, vehicle.getClass()); + if (!passengers.isEmpty()) { - final Vehicle v = exit.getWorld().spawn(exit, vehicle.getClass()); final Entity passenger = passengers.get(0); vehicle.eject(); vehicle.remove(); passenger.eject(); passenger.teleport(exit); Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, () -> { - v.addPassenger(passenger); - v.setVelocity(newVelocity); + mineCart.addPassenger(passenger); + mineCart.setVelocity(newVelocity); }, 1); } else { - Vehicle mc = exit.getWorld().spawn(exit, vehicle.getClass()); - if (mc instanceof StorageMinecart) { - StorageMinecart smc = (StorageMinecart) mc; - smc.getInventory().setContents(((StorageMinecart) vehicle).getInventory().getContents()); + if (mineCart instanceof StorageMinecart) { + StorageMinecart storageMinecart = (StorageMinecart) mineCart; + storageMinecart.getInventory().setContents(((StorageMinecart) vehicle).getInventory().getContents()); } - mc.setVelocity(newVelocity); + Stargate.log.info(Stargate.getString("prefix") + "Teleported minecart to " + mineCart.getLocation()); vehicle.remove(); + Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, () -> { + mineCart.setVelocity(newVelocity); + }, 1); } } @@ -575,6 +587,26 @@ public class Portal { return getWorld().isChunkLoaded(topLeft.getBlock().getChunk()); } + public BlockLocation getId() { + return this.id; + } + + public int getModX() { + return this.modX; + } + + public int getModZ() { + return this.modZ; + } + + public float getRotX() { + return this.rotX; + } + + public BlockLocation getTopLeft() { + return this.topLeft; + } + public boolean isVerified() { verified = true; if (!Stargate.verifyPortals) { @@ -600,46 +632,18 @@ public class Portal { return gate.matches(topLeft, modX, modZ); } - public ArrayList getDestinations(Player player, String network) { - ArrayList destinations = new ArrayList<>(); - for (String dest : allPortalsNet.get(network.toLowerCase())) { - Portal portal = getByName(dest, network); - if (portal == null) continue; - // Check if dest is a random gate - if (portal.isRandom()) continue; - // Check if dest is always open (Don't show if so) - if (portal.isAlwaysOn() && !portal.isShown()) continue; - // Check if dest is this portal - if (dest.equalsIgnoreCase(getName())) continue; - // Check if dest is a fixed gate not pointing to this gate - if (portal.isFixed() && !portal.getDestinationName().equalsIgnoreCase(getName())) continue; - // Allow random use by non-players (Minecarts) - if (player == null) { - destinations.add(portal.getName()); - continue; - } - // Check if this player can access the dest world - if (!Stargate.canAccessWorld(player, portal.getWorld().getName())) continue; - // Visible to this player. - if (Stargate.canSee(player, portal)) { - destinations.add(portal.getName()); - } - } - return destinations; - } - public boolean activate(Player player) { destinations.clear(); destination = ""; Stargate.activeList.add(this); activePlayer = player; String network = getNetwork(); - destinations = getDestinations(player, network); + destinations = PortalHandler.getDestinations(player, network); if (Stargate.sortLists) { Collections.sort(destinations); } - if (Stargate.destMemory && !lastDest.isEmpty() && destinations.contains(lastDest)) { - destination = lastDest; + if (Stargate.destMemory && !lastDestination.isEmpty() && destinations.contains(lastDestination)) { + destination = lastDestination; } StargateActivateEvent event = new StargateActivateEvent(this, player, destinations, destination); @@ -684,7 +688,7 @@ public class Portal { if (!activate(player)) { return; } - Stargate.debug("cycleDestination", "Network Size: " + allPortalsNet.get(network.toLowerCase()).size()); + Stargate.debug("cycleDestination", "Network Size: " + PortalHandler.getNetwork(network).size()); Stargate.debug("cycleDestination", "Player has access to: " + destinations.size()); activate = true; } @@ -694,7 +698,7 @@ public class Portal { return; } - if (!Stargate.destMemory || !activate || lastDest.isEmpty()) { + if (!Stargate.destMemory || !activate || lastDestination.isEmpty()) { int index = destinations.indexOf(destination); index += dir; if (index >= destinations.size()) @@ -702,7 +706,7 @@ public class Portal { else if (index < 0) index = destinations.size() - 1; destination = destinations.get(index); - lastDest = destination; + lastDestination = destination; } openTime = System.currentTimeMillis() / 1000; drawSign(); @@ -743,7 +747,7 @@ public class Portal { } else { Stargate.setLine(sign, ++done, "(" + network + ")"); } - Portal dest = Portal.getByName(destination, network); + Portal dest = PortalHandler.getByName(destination, network); if (dest == null && !isRandom()) { Stargate.setLine(sign, ++done, Stargate.getString("signDisconnected")); } else { @@ -753,7 +757,7 @@ public class Portal { int index = destinations.indexOf(destination); if ((index == max) && (max > 1) && (++done <= 3)) { if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index - 2), network); + Portal dest = PortalHandler.getByName(destinations.get(index - 2), network); boolean green = Stargate.isFree(activePlayer, this, dest); Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 2)); } else { @@ -762,7 +766,7 @@ public class Portal { } if ((index > 0) && (++done <= 3)) { if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index - 1), network); + Portal dest = PortalHandler.getByName(destinations.get(index - 1), network); boolean green = Stargate.isFree(activePlayer, this, dest); Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 1)); } else { @@ -771,7 +775,7 @@ public class Portal { } if (++done <= 3) { if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destination, network); + Portal dest = PortalHandler.getByName(destination, network); boolean green = Stargate.isFree(activePlayer, this, dest); Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + ">" + destination + "<"); } else { @@ -780,7 +784,7 @@ public class Portal { } if ((max >= index + 1) && (++done <= 3)) { if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index + 1), network); + Portal dest = PortalHandler.getByName(destinations.get(index + 1), network); boolean green = Stargate.isFree(activePlayer, this, dest); Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 1)); } else { @@ -789,7 +793,7 @@ public class Portal { } if ((max >= index + 2) && (++done <= 3)) { if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index + 2), network); + Portal dest = PortalHandler.getByName(destinations.get(index + 2), network); boolean green = Stargate.isFree(activePlayer, this, dest); Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 2)); } else { @@ -806,683 +810,20 @@ public class Portal { sign.update(); } - public void unregister(boolean removeAll) { - Stargate.debug("Unregister", "Unregistering gate " + getName()); - close(true); - - for (BlockLocation block : getFrame()) { - lookupBlocks.remove(block); - } - // Include the sign and button - lookupBlocks.remove(id); - if (button != null) { - lookupBlocks.remove(button); - } - - lookupControls.remove(id); - if (button != null) - lookupControls.remove(button); - - for (BlockLocation entrance : getEntrances()) { - lookupEntrances.remove(entrance); - } - - if (removeAll) - allPortals.remove(this); - - if (bungee) { - bungeePortals.remove(getName().toLowerCase()); - } else { - lookupNamesNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - allPortalsNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - - for (String originName : allPortalsNet.get(getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, getNetwork()); - if (origin == null) continue; - if (!origin.getDestinationName().equalsIgnoreCase(getName())) continue; - if (!origin.isVerified()) continue; - if (origin.isFixed()) origin.drawSign(); - if (origin.isAlwaysOn()) origin.close(true); - } - } - - if (id.getBlock().getBlockData() instanceof WallSign) { - Sign sign = (Sign) id.getBlock().getState(); - sign.setLine(0, getName()); - sign.setLine(1, ""); - sign.setLine(2, ""); - sign.setLine(3, ""); - sign.update(); - } - - saveAllGates(getWorld()); - } - - private BlockLocation getBlockAt(RelativeBlockVector vector) { + BlockLocation getBlockAt(RelativeBlockVector vector) { return topLeft.modRelative(vector.getRight(), vector.getDepth(), vector.getDistance(), modX, 1, modZ); } - private void register() { - fixed = destination.length() > 0 || random || bungee; - - // Bungee gates are stored in their own list - if (isBungee()) { - bungeePortals.put(getName().toLowerCase(), this); - } else { - // Check if network exists in our network list - if (!lookupNamesNet.containsKey(getNetwork().toLowerCase())) { - Stargate.debug("register", "Network " + getNetwork() + " not in lookupNamesNet, adding"); - lookupNamesNet.put(getNetwork().toLowerCase(), new HashMap<>()); - } - lookupNamesNet.get(getNetwork().toLowerCase()).put(getName().toLowerCase(), this); - - // Check if this network exists - if (!allPortalsNet.containsKey(getNetwork().toLowerCase())) { - Stargate.debug("register", "Network " + getNetwork() + " not in allPortalsNet, adding"); - allPortalsNet.put(getNetwork().toLowerCase(), new ArrayList<>()); - } - allPortalsNet.get(getNetwork().toLowerCase()).add(getName().toLowerCase()); - } - - for (BlockLocation block : getFrame()) { - lookupBlocks.put(block, this); - } - // Include the sign and button - lookupBlocks.put(id, this); - if (button != null) { - lookupBlocks.put(button, this); - } - - lookupControls.put(id, this); - if (button != null) - lookupControls.put(button, this); - - for (BlockLocation entrance : getEntrances()) { - lookupEntrances.put(entrance, this); - } - - allPortals.add(this); - } - - public static Portal createPortal(SignChangeEvent event, Player player) { - BlockLocation id = new BlockLocation(event.getBlock()); - Block idParent = id.getParent(); - if (idParent == null) { - return null; - } - - if (Gate.getGatesByControlBlock(idParent).length == 0) { - return null; - } - - if (Portal.getByBlock(idParent) != null) { - Stargate.debug("createPortal", "idParent belongs to existing gate"); - return null; - } - - BlockLocation parent = new BlockLocation(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); - BlockLocation topleft = null; - String name = filterName(event.getLine(0)); - String destName = filterName(event.getLine(1)); - String network = filterName(event.getLine(2)); - String options = filterName(event.getLine(3)).toLowerCase(); - - boolean hidden = (options.indexOf('h') != -1); - boolean alwaysOn = (options.indexOf('a') != -1); - boolean priv = (options.indexOf('p') != -1); - boolean free = (options.indexOf('f') != -1); - boolean backwards = (options.indexOf('b') != -1); - boolean show = (options.indexOf('s') != -1); - boolean noNetwork = (options.indexOf('n') != -1); - boolean random = (options.indexOf('r') != -1); - boolean bungee = (options.indexOf('u') != -1); - - // Check permissions for options. - if (hidden && !Stargate.canOption(player, "hidden")) { - hidden = false; - } - if (alwaysOn && !Stargate.canOption(player, "alwayson")) { - alwaysOn = false; - } - if (priv && !Stargate.canOption(player, "private")) { - priv = false; - } - if (free && !Stargate.canOption(player, "free")) { - free = false; - } - if (backwards && !Stargate.canOption(player, "backwards")) { - backwards = false; - } - if (show && !Stargate.canOption(player, "show")) { - show = false; - } - if (noNetwork && !Stargate.canOption(player, "nonetwork")) { - noNetwork = false; - } - if (random && !Stargate.canOption(player, "random")) { - random = false; - } - - // Can not create a non-fixed always-on gate. - if (alwaysOn && destName.length() == 0) { - alwaysOn = false; - } - - // Show isn't useful if A is false - if (show && !alwaysOn) { - show = false; - } - - // Random gates are always on and can't be shown - if (random) { - alwaysOn = true; - show = false; - } - - // Bungee gates are always on and don't support Random - if (bungee) { - alwaysOn = true; - random = false; - } - - // Moved the layout check so as to avoid invalid messages when not making a gate - int modX = 0; - int modZ = 0; - float rotX = 0f; - BlockFace buttonfacing = BlockFace.DOWN; - - if (idParent.getX() > id.getBlock().getX()) { - modZ -= 1; - rotX = 90f; - buttonfacing = BlockFace.WEST; - } else if (idParent.getX() < id.getBlock().getX()) { - modZ += 1; - rotX = 270f; - buttonfacing = BlockFace.EAST; - } else if (idParent.getZ() > id.getBlock().getZ()) { - modX += 1; - rotX = 180f; - buttonfacing = BlockFace.NORTH; - } else if (idParent.getZ() < id.getBlock().getZ()) { - modX -= 1; - rotX = 0f; - buttonfacing = BlockFace.SOUTH; - } - - Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); - Gate gate = null; - RelativeBlockVector buttonVector = null; - - for (Gate possibility : possibleGates) { - if (gate != null || buttonVector != null) { - break; - } - RelativeBlockVector[] vectors = possibility.getControls(); - RelativeBlockVector otherControl = null; - - for (RelativeBlockVector vector : vectors) { - BlockLocation tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); - - if (gate == null) { - if (possibility.matches(tl, modX, modZ, true)) { - gate = possibility; - topleft = tl; - - if (otherControl != null) { - buttonVector = otherControl; - } - } - } else if (otherControl != null) { - buttonVector = vector; - } - - otherControl = vector; - } - } - - if ((gate == null) || (buttonVector == null)) { - Stargate.debug("createPortal", "Could not find matching gate layout"); - return null; - } - - // If the player is trying to create a Bungee gate without permissions, drop out here - // Do this after the gate layout check, in the least - if (bungee) { - if (!Stargate.enableBungee) { - Stargate.sendMessage(player, Stargate.getString("bungeeDisabled")); - return null; - } else if (!Stargate.hasPerm(player, "stargate.admin.bungee")) { - Stargate.sendMessage(player, Stargate.getString("bungeeDeny")); - return null; - } else if (destName.isEmpty() || network.isEmpty()) { - Stargate.sendMessage(player, Stargate.getString("bungeeEmpty")); - return null; - } - } - - // Debug - Stargate.debug("createPortal", "h = " + hidden + " a = " + alwaysOn + " p = " + priv + " f = " + free + " b = " + backwards + " s = " + show + " n = " + noNetwork + " r = " + random + " u = " + bungee); - - if (!bungee && (network.length() < 1 || network.length() > 11)) { - network = Stargate.getDefaultNetwork(); - } - - boolean deny = false; - String denyMsg = ""; - - // Check if the player can create gates on this network - if (!bungee && !Stargate.canCreate(player, network)) { - Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal"); - if (Stargate.canCreatePersonal(player)) { - network = player.getName(); - if (network.length() > 11) network = network.substring(0, 11); - Stargate.debug("createPortal", "Creating personal portal"); - Stargate.sendMessage(player, Stargate.getString("createPersonal")); - } else { - Stargate.debug("createPortal", "Player does not have access to network"); - deny = true; - denyMsg = Stargate.getString("createNetDeny"); - //return null; - } - } - - // Check if the player can create this gate layout - String gateName = gate.getFilename(); - gateName = gateName.substring(0, gateName.indexOf('.')); - if (!deny && !Stargate.canCreateGate(player, gateName)) { - Stargate.debug("createPortal", "Player does not have access to gate layout"); - deny = true; - denyMsg = Stargate.getString("createGateDeny"); - } - - // Check if the user can create gates to this world. - if (!bungee && !deny && destName.length() > 0) { - Portal p = Portal.getByName(destName, network); - if (p != null) { - String world = p.getWorld().getName(); - if (!Stargate.canAccessWorld(player, world)) { - Stargate.debug("canCreate", "Player does not have access to destination world"); - deny = true; - denyMsg = Stargate.getString("createWorldDeny"); - } - } - } - - // Bleh, gotta check to make sure none of this gate belongs to another gate. Boo slow. - for (RelativeBlockVector v : gate.getBorder()) { - BlockLocation b = topleft.modRelative(v.getRight(), v.getDepth(), v.getDistance(), modX, 1, modZ); - if (Portal.getByBlock(b.getBlock()) != null) { - Stargate.debug("createPortal", "Gate conflicts with existing gate"); - Stargate.sendMessage(player, Stargate.getString("createConflict")); - return null; - } - } - - BlockLocation button = null; - Portal portal; - portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, false, network, gate, player.getUniqueId(), player.getName(), hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); - - int cost = Stargate.getCreateCost(player, gate); - - // Call StargateCreateEvent - StargateCreateEvent cEvent = new StargateCreateEvent(player, portal, event.getLines(), deny, denyMsg, cost); - Stargate.server.getPluginManager().callEvent(cEvent); - if (cEvent.isCancelled()) { - return null; - } - if (cEvent.getDeny()) { - Stargate.sendMessage(player, cEvent.getDenyReason()); - return null; - } - - cost = cEvent.getCost(); - - // Name & Network can be changed in the event, so do these checks here. - if (portal.getName().length() < 1 || portal.getName().length() > 11) { - Stargate.debug("createPortal", "Name length error"); - Stargate.sendMessage(player, Stargate.getString("createNameLength")); - return null; - } - - // Don't do network checks for bungee gates - if (portal.isBungee()) { - if (bungeePortals.get(portal.getName().toLowerCase()) != null) { - Stargate.debug("createPortal::Bungee", "Gate Exists"); - Stargate.sendMessage(player, Stargate.getString("createExists")); - return null; - } - } else { - if (getByName(portal.getName(), portal.getNetwork()) != null) { - Stargate.debug("createPortal", "Name Error"); - Stargate.sendMessage(player, Stargate.getString("createExists")); - return null; - } - - // Check if there are too many gates in this network - ArrayList netList = allPortalsNet.get(portal.getNetwork().toLowerCase()); - if (Stargate.maxGates > 0 && netList != null && netList.size() >= Stargate.maxGates) { - Stargate.sendMessage(player, Stargate.getString("createFull")); - return null; - } - } - - if (cost > 0) { - if (!Stargate.chargePlayer(player, cost)) { - String inFundMsg = Stargate.getString("ecoInFunds"); - inFundMsg = Stargate.replaceVars(inFundMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), name}); - Stargate.sendMessage(player, inFundMsg); - Stargate.debug("createPortal", "Insufficient Funds"); - return null; - } - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), name}); - Stargate.sendMessage(player, deductMsg, false); - } - - // No button on an always-open gate. - if (!alwaysOn) { - button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); - Directional buttondata = (Directional) Bukkit.createBlockData(gate.getButton()); - buttondata.setFacing(buttonfacing); - button.getBlock().setBlockData(buttondata); - portal.setButton(button); - } - - portal.register(); - portal.drawSign(); - // Open always on gate - if (portal.isRandom() || portal.isBungee()) { - portal.open(true); - } else if (portal.isAlwaysOn()) { - Portal dest = Portal.getByName(destName, portal.getNetwork()); - if (dest != null) { - portal.open(true); - dest.drawSign(); - } - // Set the inside of the gate to its closed material - } else { - for (BlockLocation inside : portal.getEntrances()) { - inside.setType(portal.getGate().getPortalBlockClosed()); - } - } - - // Don't do network stuff for bungee gates - if (!portal.isBungee()) { - // Open any always on gate pointing at this gate - for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, portal.getNetwork()); - if (origin == null) continue; - if (!origin.getDestinationName().equalsIgnoreCase(portal.getName())) continue; - if (!origin.isVerified()) continue; - if (origin.isFixed()) origin.drawSign(); - if (origin.isAlwaysOn()) origin.open(true); - } - } - - saveAllGates(portal.getWorld()); - - return portal; - } - - public static Portal getByName(String name, String network) { - if (!lookupNamesNet.containsKey(network.toLowerCase())) return null; - return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); - - } - - public static Portal getByEntrance(Location location) { - return lookupEntrances.get(new BlockLocation(location.getWorld(), location.getBlockX(), location.getBlockY(), - location.getBlockZ())); - } - - public static Portal getByEntrance(Block block) { - return lookupEntrances.get(new BlockLocation(block)); - } - - public static Portal getByAdjacentEntrance(Location loc) { - int centerX = loc.getBlockX(); - int centerY = loc.getBlockY(); - int centerZ = loc.getBlockZ(); - World world = loc.getWorld(); - Portal portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ)); - if (portal != null) { - return portal; - } - portal = lookupEntrances.get(new BlockLocation(world, centerX + 1, centerY, centerZ)); - if (portal != null) { - return portal; - } - portal = lookupEntrances.get(new BlockLocation(world, centerX - 1, centerY, centerZ)); - if (portal != null) { - return portal; - } - portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ + 1)); - if (portal != null) { - return portal; - } - portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ - 1)); - if (portal != null) { - return portal; - } - return null; - } - - public static Portal getByControl(Block block) { - return lookupControls.get(new BlockLocation(block)); - } - - public static Portal getByBlock(Block block) { - return lookupBlocks.get(new BlockLocation(block)); - } - - public static Portal getBungeeGate(String name) { - return bungeePortals.get(name.toLowerCase()); - } - - public static void saveAllGates(World world) { - Stargate.managedWorlds.add(world.getName()); - String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; - - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); - - for (Portal portal : allPortals) { - String wName = portal.world.getName(); - if (!wName.equalsIgnoreCase(world.getName())) continue; - StringBuilder builder = new StringBuilder(); - BlockLocation button = portal.button; - - builder.append(portal.name); - builder.append(':'); - builder.append(portal.id.toString()); - builder.append(':'); - builder.append((button != null) ? button.toString() : ""); - builder.append(':'); - builder.append(portal.modX); - builder.append(':'); - builder.append(portal.modZ); - builder.append(':'); - builder.append(portal.rotX); - builder.append(':'); - builder.append(portal.topLeft.toString()); - builder.append(':'); - builder.append(portal.gate.getFilename()); - builder.append(':'); - builder.append(portal.isFixed() ? portal.getDestinationName() : ""); - builder.append(':'); - builder.append(portal.getNetwork()); - builder.append(':'); - UUID owner = portal.getOwnerUUID(); - if (owner != null) { - builder.append(portal.getOwnerUUID().toString()); - } else { - builder.append(portal.getOwnerName()); - } - builder.append(':'); - builder.append(portal.isHidden()); - builder.append(':'); - builder.append(portal.isAlwaysOn()); - builder.append(':'); - builder.append(portal.isPrivate()); - builder.append(':'); - builder.append(portal.world.getName()); - builder.append(':'); - builder.append(portal.isFree()); - builder.append(':'); - builder.append(portal.isBackwards()); - builder.append(':'); - builder.append(portal.isShown()); - builder.append(':'); - builder.append(portal.isNoNetwork()); - builder.append(':'); - builder.append(portal.isRandom()); - builder.append(':'); - builder.append(portal.isBungee()); - - bw.append(builder.toString()); - bw.newLine(); - } - - bw.close(); - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); - } - } - - public static void clearGates() { - lookupBlocks.clear(); - lookupNamesNet.clear(); - lookupEntrances.clear(); - lookupControls.clear(); - allPortals.clear(); - allPortalsNet.clear(); - } - - public static boolean loadAllGates(World world) { - String location = Stargate.getSaveLocation(); - - File db = new File(location, world.getName() + ".db"); - - if (db.exists()) { - int l = 0; - int portalCount = 0; - try { - Scanner scanner = new Scanner(db); - while (scanner.hasNextLine()) { - l++; - String line = scanner.nextLine().trim(); - if (line.startsWith("#") || line.isEmpty()) { - continue; - } - String[] split = line.split(":"); - if (split.length < 8) { - Stargate.log.info(Stargate.getString("prefix") + "Invalid line - " + l); - continue; - } - String name = split[0]; - BlockLocation sign = new BlockLocation(world, split[1]); - BlockLocation button = (split[2].length() > 0) ? new BlockLocation(world, split[2]) : null; - int modX = Integer.parseInt(split[3]); - int modZ = Integer.parseInt(split[4]); - float rotX = Float.parseFloat(split[5]); - BlockLocation topLeft = new BlockLocation(world, split[6]); - Gate gate = Gate.getGateByName(split[7]); - if (gate == null) { - Stargate.log.info(Stargate.getString("prefix") + "Gate layout on line " + l + " does not exist [" + split[7] + "]"); - continue; - } - - String dest = (split.length > 8) ? split[8] : ""; - String network = (split.length > 9) ? split[9] : Stargate.getDefaultNetwork(); - if (network.isEmpty()) network = Stargate.getDefaultNetwork(); - String ownerString = (split.length > 10) ? split[10] : ""; - boolean hidden = (split.length > 11) && split[11].equalsIgnoreCase("true"); - boolean alwaysOn = (split.length > 12) && split[12].equalsIgnoreCase("true"); - boolean priv = (split.length > 13) && split[13].equalsIgnoreCase("true"); - boolean free = (split.length > 15) && split[15].equalsIgnoreCase("true"); - boolean backwards = (split.length > 16) && split[16].equalsIgnoreCase("true"); - boolean show = (split.length > 17) && split[17].equalsIgnoreCase("true"); - boolean noNetwork = (split.length > 18) && split[18].equalsIgnoreCase("true"); - boolean random = (split.length > 19) && split[19].equalsIgnoreCase("true"); - boolean bungee = (split.length > 20) && split[20].equalsIgnoreCase("true"); - - // Attempt to get owner as UUID - UUID ownerUUID = null; - String ownerName; - if (ownerString.length() > 16) { - try { - ownerUUID = UUID.fromString(ownerString); - OfflinePlayer offlineOwner = Bukkit.getServer().getOfflinePlayer(ownerUUID); - ownerName = offlineOwner.getName(); - } catch (IllegalArgumentException ex) { - // neither name nor UUID, so keep it as-is - ownerName = ownerString; - Stargate.debug("loadAllGates", "Invalid stargate owner string: " + ownerString); - } - } else { - ownerName = ownerString; - } - - Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, dest, name, false, network, gate, ownerUUID, ownerName, hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); - portal.register(); - portal.close(true); - } - scanner.close(); - - // Open any always-on gates. Do this here as it should be more efficient than in the loop. - int OpenCount = 0; - for (Iterator iter = allPortals.iterator(); iter.hasNext(); ) { - Portal portal = iter.next(); - if (portal == null) continue; - - // Verify portal integrity/register portal - if (!portal.wasVerified()) { - if (!portal.isVerified() || !portal.checkIntegrity()) { - // DEBUG - for (RelativeBlockVector control : portal.getGate().getControls()) { - if (!portal.getBlockAt(control).getBlock().getType().equals(portal.getGate().getControlBlock())) { - Stargate.debug("loadAllGates", "Control Block Type == " + portal.getBlockAt(control).getBlock().getType().name()); - } - } - portal.unregister(false); - iter.remove(); - Stargate.log.info(Stargate.getString("prefix") + "Destroying stargate at " + portal.toString()); - continue; - } - } - portalCount++; - - if (portal.isFixed() && (Stargate.enableBungee && portal.isBungee() - || portal.getDestination() != null && portal.isAlwaysOn())) { - portal.open(true); - OpenCount++; - } - } - Stargate.log.info(Stargate.getString("prefix") + "{" + world.getName() + "} Loaded " + portalCount + " stargates with " + OpenCount + " set as always-on"); - return true; - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + db.getName() + ": " + l); - e.printStackTrace(); - } - } else { - Stargate.log.info(Stargate.getString("prefix") + "{" + world.getName() + "} No stargates for world "); - } - return false; - } - - public static void closeAllGates() { - Stargate.log.info("Closing all stargates."); - for (Portal p : allPortals) { - if (p == null) continue; - p.close(true); - } - } - + /** + * Removes the special characters |, : and # from a portal name + * @param input

The name to filter

+ * @return

The filtered name

+ */ public static String filterName(String input) { if (input == null) { return ""; } - return input.replaceAll("[\\|:#]", "").trim(); + return input.replaceAll("[|:#]", "").trim(); } @Override diff --git a/src/main/java/net/knarcraft/stargate/PortalHandler.java b/src/main/java/net/knarcraft/stargate/PortalHandler.java new file mode 100644 index 0000000..d20aaa3 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/PortalHandler.java @@ -0,0 +1,865 @@ +package net.knarcraft.stargate; + +import net.knarcraft.stargate.event.StargateCreateEvent; +import net.knarcraft.stargate.utility.EconomyHelper; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Sign; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.type.WallSign; +import org.bukkit.entity.Player; +import org.bukkit.event.block.SignChangeEvent; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import java.util.UUID; +import java.util.logging.Level; + +public class PortalHandler { + // Static variables used to store portal lists + private static final Map lookupBlocks = new HashMap<>(); + private static final Map lookupEntrances = new HashMap<>(); + private static final Map lookupControls = new HashMap<>(); + private static final List allPortals = new ArrayList<>(); + private static final HashMap> allPortalsNet = new HashMap<>(); + private static final HashMap> lookupNamesNet = new HashMap<>(); + + // A list of Bungee gates + private static final Map bungeePortals = new HashMap<>(); + + public static List getNetwork(String network) { + return allPortalsNet.get(network.toLowerCase()); + } + + /** + * Gets all destinations in the network viewable by the given player + * @param player

The player who wants to see destinations

+ * @param network

The network to get destinations from

+ * @return

All destinations the player can go to

+ */ + public static ArrayList getDestinations(Player player, String network) { + ArrayList destinations = new ArrayList<>(); + for (String dest : allPortalsNet.get(network.toLowerCase())) { + Portal portal = getByName(dest, network); + if (portal == null) continue; + // Check if dest is a random gate + if (portal.isRandom()) continue; + // Check if dest is always open (Don't show if so) + if (portal.isAlwaysOn() && !portal.isShown()) continue; + // Check if dest is this portal + if (dest.equalsIgnoreCase(portal.getName())) continue; + // Check if dest is a fixed gate not pointing to this gate + if (portal.isFixed() && !portal.getDestinationName().equalsIgnoreCase(portal.getName())) continue; + // Allow random use by non-players (Minecarts) + if (player == null) { + destinations.add(portal.getName()); + continue; + } + // Check if this player can access the dest world + if (!Stargate.canAccessWorld(player, portal.getWorld().getName())) continue; + // Visible to this player. + if (Stargate.canSee(player, portal)) { + destinations.add(portal.getName()); + } + } + return destinations; + } + + /** + * Un-registers the given portal + * @param portal

The portal to un-register

+ * @param removeAll

Whether to remove the portal from the list of all portals

+ */ + public static void unregister(Portal portal, boolean removeAll) { + Stargate.debug("Unregister", "Unregistering gate " + portal.getName()); + portal.close(true); + + for (BlockLocation block : portal.getFrame()) { + lookupBlocks.remove(block); + } + // Include the sign and button + lookupBlocks.remove(portal.getId()); + lookupControls.remove(portal.getId()); + if (portal.getButton() != null) { + lookupBlocks.remove(portal.getButton()); + lookupControls.remove(portal.getButton()); + } + + for (BlockLocation entrance : portal.getEntrances()) { + lookupEntrances.remove(entrance); + } + + if (removeAll) { + allPortals.remove(portal); + } + + if (portal.isBungee()) { + bungeePortals.remove(portal.getName().toLowerCase()); + } else { + lookupNamesNet.get(portal.getNetwork().toLowerCase()).remove(portal.getName().toLowerCase()); + allPortalsNet.get(portal.getNetwork().toLowerCase()).remove(portal.getName().toLowerCase()); + + for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { + Portal origin = getByName(originName, portal.getNetwork()); + if (origin == null) continue; + if (!origin.getDestinationName().equalsIgnoreCase(portal.getName())) continue; + if (!origin.isVerified()) continue; + if (origin.isFixed()) origin.drawSign(); + if (origin.isAlwaysOn()) origin.close(true); + } + } + + if (portal.getId().getBlock().getBlockData() instanceof WallSign) { + Sign sign = (Sign) portal.getId().getBlock().getState(); + sign.setLine(0, portal.getName()); + sign.setLine(1, ""); + sign.setLine(2, ""); + sign.setLine(3, ""); + sign.update(); + } + + saveAllGates(portal.getWorld()); + } + + /** + * Registers a portal + * @param portal

The portal to register

+ */ + static void register(Portal portal) { + portal.setFixed(portal.getDestinationName().length() > 0 || portal.isRandom() || portal.isBungee()); + + // Bungee gates are stored in their own list + if (portal.isBungee()) { + bungeePortals.put(portal.getName().toLowerCase(), portal); + } else { + // Check if network exists in our network list + if (!lookupNamesNet.containsKey(portal.getNetwork().toLowerCase())) { + Stargate.debug("register", "Network " + portal.getNetwork() + " not in lookupNamesNet, adding"); + lookupNamesNet.put(portal.getNetwork().toLowerCase(), new HashMap<>()); + } + lookupNamesNet.get(portal.getNetwork().toLowerCase()).put(portal.getName().toLowerCase(), portal); + + // Check if this network exists + if (!allPortalsNet.containsKey(portal.getNetwork().toLowerCase())) { + Stargate.debug("register", "Network " + portal.getNetwork() + " not in allPortalsNet, adding"); + allPortalsNet.put(portal.getNetwork().toLowerCase(), new ArrayList<>()); + } + allPortalsNet.get(portal.getNetwork().toLowerCase()).add(portal.getName().toLowerCase()); + } + + for (BlockLocation block : portal.getFrame()) { + lookupBlocks.put(block, portal); + } + // Include the sign and button + lookupBlocks.put(portal.getId(), portal); + lookupControls.put(portal.getId(), portal); + if (portal.getButton() != null) { + lookupBlocks.put(portal.getButton(), portal); + lookupControls.put(portal.getButton(), portal); + } + + + for (BlockLocation entrance : portal.getEntrances()) { + lookupEntrances.put(entrance, portal); + } + + allPortals.add(portal); + } + + /** + * Creates a new portal + * @param event

The sign change event which initialized the creation

+ * @param player

The player who's creating the portal

+ * @return

The created portal

+ */ + public static Portal createPortal(SignChangeEvent event, Player player) { + BlockLocation id = new BlockLocation(event.getBlock()); + Block idParent = id.getParent(); + if (idParent == null) { + return null; + } + + if (Gate.getGatesByControlBlock(idParent).length == 0) { + return null; + } + + if (getByBlock(idParent) != null) { + Stargate.debug("createPortal", "idParent belongs to existing gate"); + return null; + } + + BlockLocation parent = new BlockLocation(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); + BlockLocation topleft = null; + String name = filterName(event.getLine(0)); + String destName = filterName(event.getLine(1)); + String network = filterName(event.getLine(2)); + String options = filterName(event.getLine(3)).toLowerCase(); + + boolean hidden = (options.indexOf('h') != -1); + boolean alwaysOn = (options.indexOf('a') != -1); + boolean priv = (options.indexOf('p') != -1); + boolean free = (options.indexOf('f') != -1); + boolean backwards = (options.indexOf('b') != -1); + boolean show = (options.indexOf('s') != -1); + boolean noNetwork = (options.indexOf('n') != -1); + boolean random = (options.indexOf('r') != -1); + boolean bungee = (options.indexOf('u') != -1); + + // Check permissions for options. + if (hidden && !Stargate.canOption(player, "hidden")) { + hidden = false; + } + if (alwaysOn && !Stargate.canOption(player, "alwayson")) { + alwaysOn = false; + } + if (priv && !Stargate.canOption(player, "private")) { + priv = false; + } + if (free && !Stargate.canOption(player, "free")) { + free = false; + } + if (backwards && !Stargate.canOption(player, "backwards")) { + backwards = false; + } + if (show && !Stargate.canOption(player, "show")) { + show = false; + } + if (noNetwork && !Stargate.canOption(player, "nonetwork")) { + noNetwork = false; + } + if (random && !Stargate.canOption(player, "random")) { + random = false; + } + + // Can not create a non-fixed always-on gate. + if (alwaysOn && destName.length() == 0) { + alwaysOn = false; + } + + // Show isn't useful if A is false + if (show && !alwaysOn) { + show = false; + } + + // Random gates are always on and can't be shown + if (random) { + alwaysOn = true; + show = false; + } + + // Bungee gates are always on and don't support Random + if (bungee) { + alwaysOn = true; + random = false; + } + + // Moved the layout check so as to avoid invalid messages when not making a gate + int modX = 0; + int modZ = 0; + float rotX = 0f; + BlockFace buttonfacing = BlockFace.DOWN; + + if (idParent.getX() > id.getBlock().getX()) { + modZ -= 1; + rotX = 90f; + buttonfacing = BlockFace.WEST; + } else if (idParent.getX() < id.getBlock().getX()) { + modZ += 1; + rotX = 270f; + buttonfacing = BlockFace.EAST; + } else if (idParent.getZ() > id.getBlock().getZ()) { + modX += 1; + rotX = 180f; + buttonfacing = BlockFace.NORTH; + } else if (idParent.getZ() < id.getBlock().getZ()) { + modX -= 1; + rotX = 0f; + buttonfacing = BlockFace.SOUTH; + } + + Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); + Gate gate = null; + RelativeBlockVector buttonVector = null; + + for (Gate possibility : possibleGates) { + if (gate != null || buttonVector != null) { + break; + } + RelativeBlockVector[] vectors = possibility.getControls(); + RelativeBlockVector otherControl = null; + + for (RelativeBlockVector vector : vectors) { + BlockLocation tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); + + if (gate == null) { + if (possibility.matches(tl, modX, modZ, true)) { + gate = possibility; + topleft = tl; + + if (otherControl != null) { + buttonVector = otherControl; + } + } + } else if (otherControl != null) { + buttonVector = vector; + } + + otherControl = vector; + } + } + + if ((gate == null) || (buttonVector == null)) { + Stargate.debug("createPortal", "Could not find matching gate layout"); + return null; + } + + // If the player is trying to create a Bungee gate without permissions, drop out here + // Do this after the gate layout check, in the least + if (bungee) { + if (!Stargate.enableBungee) { + Stargate.sendMessage(player, Stargate.getString("bungeeDisabled")); + return null; + } else if (!Stargate.hasPerm(player, "stargate.admin.bungee")) { + Stargate.sendMessage(player, Stargate.getString("bungeeDeny")); + return null; + } else if (destName.isEmpty() || network.isEmpty()) { + Stargate.sendMessage(player, Stargate.getString("bungeeEmpty")); + return null; + } + } + + // Debug + Stargate.debug("createPortal", "h = " + hidden + " a = " + alwaysOn + " p = " + priv + " f = " + free + " b = " + backwards + " s = " + show + " n = " + noNetwork + " r = " + random + " u = " + bungee); + + if (!bungee && (network.length() < 1 || network.length() > 11)) { + network = Stargate.getDefaultNetwork(); + } + + boolean deny = false; + String denyMsg = ""; + + // Check if the player can create gates on this network + if (!bungee && !Stargate.canCreate(player, network)) { + Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal"); + if (Stargate.canCreatePersonal(player)) { + network = player.getName(); + if (network.length() > 11) network = network.substring(0, 11); + Stargate.debug("createPortal", "Creating personal portal"); + Stargate.sendMessage(player, Stargate.getString("createPersonal")); + } else { + Stargate.debug("createPortal", "Player does not have access to network"); + deny = true; + denyMsg = Stargate.getString("createNetDeny"); + //return null; + } + } + + // Check if the player can create this gate layout + String gateName = gate.getFilename(); + gateName = gateName.substring(0, gateName.indexOf('.')); + if (!deny && !Stargate.canCreateGate(player, gateName)) { + Stargate.debug("createPortal", "Player does not have access to gate layout"); + deny = true; + denyMsg = Stargate.getString("createGateDeny"); + } + + // Check if the user can create gates to this world. + if (!bungee && !deny && destName.length() > 0) { + Portal p = getByName(destName, network); + if (p != null) { + String world = p.getWorld().getName(); + if (!Stargate.canAccessWorld(player, world)) { + Stargate.debug("canCreate", "Player does not have access to destination world"); + deny = true; + denyMsg = Stargate.getString("createWorldDeny"); + } + } + } + + // Bleh, gotta check to make sure none of this gate belongs to another gate. Boo slow. + for (RelativeBlockVector v : gate.getBorder()) { + BlockLocation b = topleft.modRelative(v.getRight(), v.getDepth(), v.getDistance(), modX, 1, modZ); + if (getByBlock(b.getBlock()) != null) { + Stargate.debug("createPortal", "Gate conflicts with existing gate"); + Stargate.sendMessage(player, Stargate.getString("createConflict")); + return null; + } + } + + BlockLocation button = null; + Portal portal; + portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, false, network, gate, player.getUniqueId(), player.getName(), hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); + + int cost = Stargate.getCreateCost(player, gate); + + // Call StargateCreateEvent + StargateCreateEvent cEvent = new StargateCreateEvent(player, portal, event.getLines(), deny, denyMsg, cost); + Stargate.server.getPluginManager().callEvent(cEvent); + if (cEvent.isCancelled()) { + return null; + } + if (cEvent.getDeny()) { + Stargate.sendMessage(player, cEvent.getDenyReason()); + return null; + } + + cost = cEvent.getCost(); + + // Name & Network can be changed in the event, so do these checks here. + if (portal.getName().length() < 1 || portal.getName().length() > 11) { + Stargate.debug("createPortal", "Name length error"); + Stargate.sendMessage(player, Stargate.getString("createNameLength")); + return null; + } + + // Don't do network checks for bungee gates + if (portal.isBungee()) { + if (bungeePortals.get(portal.getName().toLowerCase()) != null) { + Stargate.debug("createPortal::Bungee", "Gate Exists"); + Stargate.sendMessage(player, Stargate.getString("createExists")); + return null; + } + } else { + if (getByName(portal.getName(), portal.getNetwork()) != null) { + Stargate.debug("createPortal", "Name Error"); + Stargate.sendMessage(player, Stargate.getString("createExists")); + return null; + } + + // Check if there are too many gates in this network + List netList = allPortalsNet.get(portal.getNetwork().toLowerCase()); + if (Stargate.maxGates > 0 && netList != null && netList.size() >= Stargate.maxGates) { + Stargate.sendMessage(player, Stargate.getString("createFull")); + return null; + } + } + + if (cost > 0) { + if (!Stargate.chargePlayer(player, cost)) { + EconomyHelper.sendInsufficientFundsMessage(name, player, cost); + Stargate.debug("createPortal", "Insufficient Funds"); + return null; + } + EconomyHelper.sendDeductMessage(name, player, cost); + } + + // No button on an always-open gate. + if (!alwaysOn) { + button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); + Directional buttondata = (Directional) Bukkit.createBlockData(gate.getButton()); + buttondata.setFacing(buttonfacing); + button.getBlock().setBlockData(buttondata); + portal.setButton(button); + } + + register(portal); + portal.drawSign(); + // Open always on gate + if (portal.isRandom() || portal.isBungee()) { + portal.open(true); + } else if (portal.isAlwaysOn()) { + Portal dest = getByName(destName, portal.getNetwork()); + if (dest != null) { + portal.open(true); + dest.drawSign(); + } + // Set the inside of the gate to its closed material + } else { + for (BlockLocation inside : portal.getEntrances()) { + inside.setType(portal.getGate().getPortalBlockClosed()); + } + } + + // Don't do network stuff for bungee gates + if (!portal.isBungee()) { + // Open any always on gate pointing at this gate + for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { + Portal origin = getByName(originName, portal.getNetwork()); + if (origin == null) continue; + if (!origin.getDestinationName().equalsIgnoreCase(portal.getName())) continue; + if (!origin.isVerified()) continue; + if (origin.isFixed()) origin.drawSign(); + if (origin.isAlwaysOn()) origin.open(true); + } + } + + saveAllGates(portal.getWorld()); + + return portal; + } + + /** + * Gets a portal given its name + * @param name

The name of the portal

+ * @param network

The network the portal is connected to

+ * @return

The portal with the given name or null

+ */ + public static Portal getByName(String name, String network) { + if (!lookupNamesNet.containsKey(network.toLowerCase())) { + return null; + } + return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); + + } + + /** + * Gets a portal given its entrance + * @param location

The location of the portal's entrance

+ * @return

The portal at the given location

+ */ + public static Portal getByEntrance(Location location) { + return lookupEntrances.get(new BlockLocation(location.getWorld(), location.getBlockX(), location.getBlockY(), + location.getBlockZ())); + } + + /** + * Gets a portal given its entrance + * @param block

The block at the portal's entrance

+ * @return

The portal at the given block's location

+ */ + public static Portal getByEntrance(Block block) { + return lookupEntrances.get(new BlockLocation(block)); + } + + /** + * Gets a portal given a location adjacent to its entrance + * @param loc

A location adjacent to the portal's entrance

+ * @return

The portal adjacent to the given location

+ */ + public static Portal getByAdjacentEntrance(Location loc) { + int centerX = loc.getBlockX(); + int centerY = loc.getBlockY(); + int centerZ = loc.getBlockZ(); + World world = loc.getWorld(); + Portal portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX + 1, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX - 1, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ + 1)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ - 1)); + if (portal != null) { + return portal; + } + return null; + } + + /** + * Gets a portal given its control block (the block type used for the sign and button) + * @param block

The portal's control block

+ * @return

The gate with the given control block

+ */ + public static Portal getByControl(Block block) { + return lookupControls.get(new BlockLocation(block)); + } + + /** + * Gets a portal given a block + * @param block

One of the loaded lookup blocks

+ * @return

The portal corresponding to the block

+ */ + public static Portal getByBlock(Block block) { + return lookupBlocks.get(new BlockLocation(block)); + } + + /** + * Gets a bungee gate given its name + * @param name

The name of the bungee gate to get

+ * @return

A bungee gate

+ */ + public static Portal getBungeeGate(String name) { + return bungeePortals.get(name.toLowerCase()); + } + + /** + * Saves all gates for the given world + * @param world

The world to save gates for

+ */ + public static void saveAllGates(World world) { + Stargate.managedWorlds.add(world.getName()); + String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; + + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); + + for (Portal portal : allPortals) { + String wName = portal.getWorld().getName(); + if (!wName.equalsIgnoreCase(world.getName())) continue; + StringBuilder builder = new StringBuilder(); + BlockLocation button = portal.getButton(); + + builder.append(portal.getName()); + builder.append(':'); + builder.append(portal.getId().toString()); + builder.append(':'); + builder.append((button != null) ? button.toString() : ""); + builder.append(':'); + builder.append(portal.getModX()); + builder.append(':'); + builder.append(portal.getModZ()); + builder.append(':'); + builder.append(portal.getRotX()); + builder.append(':'); + builder.append(portal.getTopLeft().toString()); + builder.append(':'); + builder.append(portal.getGate().getFilename()); + builder.append(':'); + builder.append(portal.isFixed() ? portal.getDestinationName() : ""); + builder.append(':'); + builder.append(portal.getNetwork()); + builder.append(':'); + UUID owner = portal.getOwnerUUID(); + if (owner != null) { + builder.append(portal.getOwnerUUID().toString()); + } else { + builder.append(portal.getOwnerName()); + } + builder.append(':'); + builder.append(portal.isHidden()); + builder.append(':'); + builder.append(portal.isAlwaysOn()); + builder.append(':'); + builder.append(portal.isPrivate()); + builder.append(':'); + builder.append(portal.getWorld().getName()); + builder.append(':'); + builder.append(portal.isFree()); + builder.append(':'); + builder.append(portal.isBackwards()); + builder.append(':'); + builder.append(portal.isShown()); + builder.append(':'); + builder.append(portal.isNoNetwork()); + builder.append(':'); + builder.append(portal.isRandom()); + builder.append(':'); + builder.append(portal.isBungee()); + + bw.append(builder.toString()); + bw.newLine(); + } + + bw.close(); + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); + } + } + + /** + * Clears all loaded gates and gate data + */ + public static void clearGates() { + lookupBlocks.clear(); + lookupNamesNet.clear(); + lookupEntrances.clear(); + lookupControls.clear(); + allPortals.clear(); + allPortalsNet.clear(); + } + + /** + * Loads all gates for the given world + * @param world

The world to load gates for

+ * @return

True if gates could be loaded

+ */ + public static boolean loadAllGates(World world) { + String location = Stargate.getSaveLocation(); + + File database = new File(location, world.getName() + ".db"); + + if (database.exists()) { + return loadGates(world, database); + } else { + Stargate.log.info(Stargate.getString("prefix") + "{" + world.getName() + "} No stargates for world "); + } + return false; + } + + /** + * Loads all the given gates + * @param world

The world to load gates for

+ * @param database

The database file containing the gates

+ * @return

True if the gates were loaded successfully

+ */ + private static boolean loadGates(World world, File database) { + int l = 0; + try { + Scanner scanner = new Scanner(database); + while (scanner.hasNextLine()) { + l++; + String line = scanner.nextLine().trim(); + if (line.startsWith("#") || line.isEmpty()) { + continue; + } + String[] portalData = line.split(":"); + if (portalData.length < 8) { + Stargate.log.info(Stargate.getString("prefix") + "Invalid line - " + l); + continue; + } + String name = portalData[0]; + BlockLocation sign = new BlockLocation(world, portalData[1]); + BlockLocation button = (portalData[2].length() > 0) ? new BlockLocation(world, portalData[2]) : null; + int modX = Integer.parseInt(portalData[3]); + int modZ = Integer.parseInt(portalData[4]); + float rotX = Float.parseFloat(portalData[5]); + BlockLocation topLeft = new BlockLocation(world, portalData[6]); + Gate gate = Gate.getGateByName(portalData[7]); + if (gate == null) { + Stargate.log.info(Stargate.getString("prefix") + "Gate layout on line " + l + " does not exist [" + portalData[7] + "]"); + continue; + } + + String destination = (portalData.length > 8) ? portalData[8] : ""; + String network = (portalData.length > 9) ? portalData[9] : Stargate.getDefaultNetwork(); + if (network.isEmpty()) network = Stargate.getDefaultNetwork(); + String ownerString = (portalData.length > 10) ? portalData[10] : ""; + + // Attempt to get owner as UUID + UUID ownerUUID = null; + String ownerName; + if (ownerString.length() > 16) { + try { + ownerUUID = UUID.fromString(ownerString); + OfflinePlayer offlineOwner = Bukkit.getServer().getOfflinePlayer(ownerUUID); + ownerName = offlineOwner.getName(); + } catch (IllegalArgumentException ex) { + // neither name nor UUID, so keep it as-is + ownerName = ownerString; + Stargate.debug("loadAllGates", "Invalid stargate owner string: " + ownerString); + } + } else { + ownerName = ownerString; + } + + //Creates the new portal + Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, destination, name, false, network, + gate, ownerUUID, ownerName); + loadPortalOptions(portal, portalData); + + register(portal); + portal.close(true); + } + scanner.close(); + + // Open any always-on gates. Do this here as it should be more efficient than in the loop. + TwoTuple portalCounts = openAlwaysOpenGates(); + + Stargate.log.info(Stargate.getString("prefix") + "{" + world.getName() + "} Loaded " + portalCounts.getSecondValue() + " stargates with " + portalCounts.getFirstValue() + " set as always-on"); + return true; + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + database.getName() + ": " + l); + e.printStackTrace(); + } + return false; + } + + /** + * Loads all portal options and updates the given portal + * @param portal

The portal to apply the options to

+ * @param portalData

The string list containing all information about a portal

+ */ + private static void loadPortalOptions(Portal portal, String[] portalData) { + boolean hidden = (portalData.length > 11) && portalData[11].equalsIgnoreCase("true"); + boolean alwaysOn = (portalData.length > 12) && portalData[12].equalsIgnoreCase("true"); + boolean isPrivate = (portalData.length > 13) && portalData[13].equalsIgnoreCase("true"); + boolean free = (portalData.length > 15) && portalData[15].equalsIgnoreCase("true"); + boolean backwards = (portalData.length > 16) && portalData[16].equalsIgnoreCase("true"); + boolean show = (portalData.length > 17) && portalData[17].equalsIgnoreCase("true"); + boolean noNetwork = (portalData.length > 18) && portalData[18].equalsIgnoreCase("true"); + boolean random = (portalData.length > 19) && portalData[19].equalsIgnoreCase("true"); + boolean bungee = (portalData.length > 20) && portalData[20].equalsIgnoreCase("true"); + portal.setHidden(hidden).setAlwaysOn(alwaysOn).setPrivate(isPrivate).setFree(free).setBungee(bungee); + portal.setBackwards(backwards).setShown(show).setNoNetwork(noNetwork).setRandom(random); + } + + /** + * Opens all always open gates + * @return

A TwoTuple where the first value is the number of always open gates and the second value is the total number of gates

+ */ + private static TwoTuple openAlwaysOpenGates() { + int portalCount = 0; + int openCount = 0; + for (Iterator iterator = allPortals.iterator(); iterator.hasNext(); ) { + Portal portal = iterator.next(); + if (portal == null) { + continue; + } + + // Verify portal integrity/register portal + if (!portal.wasVerified() && (!portal.isVerified() || !portal.checkIntegrity())) { + destroyInvalidStarGate(portal); + iterator.remove(); + continue; + } + portalCount++; + + //Open the gate if it's set as always open or if it's a bungee gate + if (portal.isFixed() && (Stargate.enableBungee && portal.isBungee() || portal.getDestination() != null && + portal.isAlwaysOn())) { + portal.open(true); + openCount++; + } + } + return new TwoTuple<>(openCount, portalCount); + } + + /** + * Destroys a star gate which has failed its integrity test + * @param portal

The portal of the star gate

+ */ + private static void destroyInvalidStarGate(Portal portal) { + // DEBUG + for (RelativeBlockVector control : portal.getGate().getControls()) { + if (!portal.getBlockAt(control).getBlock().getType().equals(portal.getGate().getControlBlock())) { + Stargate.debug("loadAllGates", "Control Block Type == " + portal.getBlockAt(control).getBlock().getType().name()); + } + } + PortalHandler.unregister(portal, false); + Stargate.log.info(Stargate.getString("prefix") + "Destroying stargate at " + portal.toString()); + } + + /** + * Closes all star gate portals + */ + public static void closeAllGates() { + Stargate.log.info("Closing all stargates."); + for (Portal portal : allPortals) { + if (portal != null) { + portal.close(true); + } + } + } + + /** + * Removes the special characters |, : and # from a portal name + * @param input

The name to filter

+ * @return

The filtered name

+ */ + public static String filterName(String input) { + if (input == null) { + return ""; + } + return input.replaceAll("[|:#]", "").trim(); + } +} diff --git a/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java b/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java index c3e40f3..3078f2e 100644 --- a/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java +++ b/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java @@ -1,32 +1,22 @@ package net.knarcraft.stargate; /** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . + * This stores a block location as a vector in an alternate coordinate system + * + *

*/ - public class RelativeBlockVector { - private int right = 0; - private int depth = 0; - private int distance = 0; + private int right; + private int depth; + private int distance; + /** + * Instantiates a new relative block vector + * @param right

The x coordinate in the gate description

+ * @param depth

The y coordinate in the gate description

+ * @param distance

+ */ public RelativeBlockVector(int right, int depth, int distance) { this.right = right; this.depth = depth; diff --git a/src/main/java/net/knarcraft/stargate/Stargate.java b/src/main/java/net/knarcraft/stargate/Stargate.java index 4d3a0b5..6f1b808 100644 --- a/src/main/java/net/knarcraft/stargate/Stargate.java +++ b/src/main/java/net/knarcraft/stargate/Stargate.java @@ -24,6 +24,7 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.HashMap; @@ -36,27 +37,6 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - @SuppressWarnings("unused") public class Stargate extends JavaPlugin { @@ -121,8 +101,8 @@ public class Stargate extends JavaPlugin { @Override public void onDisable() { - Portal.closeAllGates(); - Portal.clearGates(); + PortalHandler.closeAllGates(); + PortalHandler.clearGates(); managedWorlds.clear(); getServer().getScheduler().cancelTasks(this); } @@ -251,7 +231,7 @@ public class Stargate extends JavaPlugin { public void loadAllPortals() { for (World world : getServer().getWorlds()) { if (!managedWorlds.contains(world.getName())) { - Portal.loadAllGates(world); + PortalHandler.loadAllGates(world); managedWorlds.add(world.getName()); } } @@ -261,11 +241,15 @@ public class Stargate extends JavaPlugin { // Only migrate if new file doesn't exist. File newPortalDir = new File(portalFolder); if (!newPortalDir.exists()) { - newPortalDir.mkdirs(); + if (!newPortalDir.mkdirs()) { + log.severe("Unable to create portal directory"); + } } File newFile = new File(portalFolder, getServer().getWorlds().get(0).getName() + ".db"); if (!newFile.exists()) { - newFile.getParentFile().mkdirs(); + if (!newFile.getParentFile().mkdirs()) { + log.severe("Unable to create portal directory"); + } } } @@ -652,7 +636,7 @@ public class Stargate extends JavaPlugin { @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { String cmd = command.getName(); if (cmd.equalsIgnoreCase("sg")) { if (args.length != 1) return false; @@ -680,7 +664,7 @@ public class Stargate extends JavaPlugin { activeList.clear(); openList.clear(); managedWorlds.clear(); - Portal.clearGates(); + PortalHandler.clearGates(); Gate.clearGates(); // Store the old Bungee enabled value diff --git a/src/main/java/net/knarcraft/stargate/TwoTuple.java b/src/main/java/net/knarcraft/stargate/TwoTuple.java new file mode 100644 index 0000000..f2a8593 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/TwoTuple.java @@ -0,0 +1,39 @@ +package net.knarcraft.stargate; + +/** + * This class allows storing two values of any type + * @param

The first type

+ * @param

The second type

+ */ +public class TwoTuple { + + private K firstValue; + private L secondValue; + + /** + * Instantiate a new TwoTuple + * @param firstValue

The first value

+ * @param secondValue

The second value

+ */ + public TwoTuple(K firstValue, L secondValue) { + this.firstValue = firstValue; + this.secondValue = secondValue; + } + + /** + * Gets the first value + * @return

The first value

+ */ + public K getFirstValue() { + return firstValue; + } + + /** + * Gets the second value + * @return

The second value

+ */ + public L getSecondValue() { + return secondValue; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java index 07d58a3..919ff6d 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java @@ -4,26 +4,6 @@ import net.knarcraft.stargate.Portal; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; -/* - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - - @SuppressWarnings("unused") public class StargateAccessEvent extends StargateEvent { @@ -32,15 +12,21 @@ public class StargateAccessEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); - @Override - public HandlerList getHandlers() { - return handlers; - } + /** + * Gets a handler-list containing all event handlers + * @return

A handler-list with all event handlers

+ */ public static HandlerList getHandlerList() { return handlers; } - + + /** + * Instantiates a new stargate access event + * @param player

The player involved in the vent

+ * @param portal

The portal involved in the event

+ * @param deny

Whether the event should be denied

+ */ public StargateAccessEvent(Player player, Portal portal, boolean deny) { super("StargateAccessEvent", portal); @@ -63,9 +49,17 @@ public class StargateAccessEvent extends StargateEvent { public void setDeny(boolean deny) { this.deny = deny; } - + + /** + * Gets the player involved in this stargate access event + * @return

The player involved in this event

+ */ public Player getPlayer() { return this.player; } + @Override + public @org.jetbrains.annotations.NotNull HandlerList getHandlers() { + return handlers; + } } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java index c66a65f..085c622 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java @@ -3,28 +3,10 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - public class StargateActivateEvent extends StargateEvent { private final Player player; @@ -33,6 +15,7 @@ public class StargateActivateEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java index 89d586e..070a4b3 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java @@ -2,25 +2,7 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.event.HandlerList; - -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ +import org.jetbrains.annotations.NotNull; public class StargateCloseEvent extends StargateEvent { @@ -28,6 +10,7 @@ public class StargateCloseEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java index eed8d74..bba2060 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java @@ -3,25 +3,7 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; - -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ +import org.jetbrains.annotations.NotNull; public class StargateCreateEvent extends StargateEvent { @@ -33,6 +15,7 @@ public class StargateCreateEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java index 41b061e..922e68f 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java @@ -2,30 +2,13 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.event.HandlerList; - -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ +import org.jetbrains.annotations.NotNull; public class StargateDeactivateEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java index 227e0c5..9d4f965 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java @@ -3,26 +3,11 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; /** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . + * This event represents an event where a star gate is destroyed or attempted to be destroyed */ - public class StargateDestroyEvent extends StargateEvent { private final Player player; @@ -32,14 +17,27 @@ public class StargateDestroyEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } + /** + * Gets a handler-list containing all event handlers + * @return

A handler-list with all event handlers

+ */ public static HandlerList getHandlerList() { return handlers; } + /** + * Instantiates a new Stargate Destroy Event + * @param portal

The portal destroyed

+ * @param player

The player destroying the portal

+ * @param deny

Whether the event should be denied (cancelled)

+ * @param denyMsg

The message to display if the event is denied

+ * @param cost

The cost of destroying the portal

+ */ public StargateDestroyEvent(Portal portal, Player player, boolean deny, String denyMsg, int cost) { super("StargateDestroyEvent", portal); this.player = player; @@ -48,30 +46,58 @@ public class StargateDestroyEvent extends StargateEvent { this.cost = cost; } + /** + * Gets the player causing the destroy event + * @return

The player causing the destroy event

+ */ public Player getPlayer() { return player; } + /** + * Gets whether this event should be denied + * @return

Whether this event should be denied

+ */ public boolean getDeny() { return deny; } + /** + * Sets whether this event should be denied + * @param deny

Whether this event should be denied

+ */ public void setDeny(boolean deny) { this.deny = deny; } + /** + * Gets the reason the event was denied + * @return

The reason the event was denied

+ */ public String getDenyReason() { return denyReason; } + /** + * Sets the reason the event was denied + * @param denyReason

The reason the event was denied

+ */ public void setDenyReason(String denyReason) { this.denyReason = denyReason; } + /** + * Gets the cost of destroying the portal + * @return

The cost of destroying the portal

+ */ public int getCost() { return cost; } + /** + * Sets the cost of destroying the portal + * @param cost

The cost of destroying the portal

+ */ public void setCost(int cost) { this.cost = cost; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateEvent.java index a3a40ce..1dbc915 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateEvent.java @@ -4,25 +4,6 @@ import net.knarcraft.stargate.Portal; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; -/* - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - /** * An abstract event describing any stargate event */ @@ -37,6 +18,7 @@ public abstract class StargateEvent extends Event implements Cancellable { this.cancelled = false; } + public Portal getPortal() { return portal; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java index 180b700..75a3bf4 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java @@ -3,25 +3,7 @@ package net.knarcraft.stargate.event; import net.knarcraft.stargate.Portal; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; - -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ +import org.jetbrains.annotations.NotNull; public class StargateOpenEvent extends StargateEvent { @@ -30,6 +12,7 @@ public class StargateOpenEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java b/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java index 2a3a537..3b46461 100644 --- a/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java @@ -4,25 +4,7 @@ import net.knarcraft.stargate.Portal; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; - -/** - * stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * Copyright (C) 2021 Kristian Knarvik - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - *

- * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ +import org.jetbrains.annotations.NotNull; public class StargatePortalEvent extends StargateEvent { @@ -32,6 +14,7 @@ public class StargatePortalEvent extends StargateEvent { private static final HandlerList handlers = new HandlerList(); + @NotNull public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/net/knarcraft/stargate/listener/BlockEventListener.java b/src/main/java/net/knarcraft/stargate/listener/BlockEventListener.java index 90b2703..2bbe2cd 100644 --- a/src/main/java/net/knarcraft/stargate/listener/BlockEventListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/BlockEventListener.java @@ -1,9 +1,10 @@ package net.knarcraft.stargate.listener; -import net.knarcraft.stargate.EconomyHandler; import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.PortalHandler; import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.event.StargateDestroyEvent; +import net.knarcraft.stargate.utility.EconomyHelper; import net.knarcraft.stargate.utility.MaterialHelper; import org.bukkit.Material; import org.bukkit.block.Block; @@ -22,7 +23,17 @@ import org.bukkit.event.block.SignChangeEvent; import java.util.List; +/** + * This class is responsible for listening to relevant block events related to creating and breaking portals + */ +@SuppressWarnings("unused") public class BlockEventListener implements Listener { + + /** + * Detects sign changes to detect if the user is creating a new gate + * + * @param event

The triggered event

+ */ @EventHandler public void onSignChange(SignChangeEvent event) { if (event.isCancelled()) { @@ -30,11 +41,12 @@ public class BlockEventListener implements Listener { } Player player = event.getPlayer(); Block block = event.getBlock(); + //Ignore normal signs if (!(block.getBlockData() instanceof WallSign)) { return; } - final Portal portal = Portal.createPortal(event, player); + final Portal portal = PortalHandler.createPortal(event, player); // Not creating a gate, just placing a sign if (portal == null) { return; @@ -42,69 +54,94 @@ public class BlockEventListener implements Listener { Stargate.sendMessage(player, Stargate.getString("createMsg"), false); Stargate.debug("onSignChange", "Initialized stargate: " + portal.getName()); - Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, () -> portal.drawSign(), 1); + Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, portal::drawSign, 1); } // Switch to HIGHEST priority so as to come after block protection plugins (Hopefully) @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { - if (event.isCancelled()) return; + if (event.isCancelled()) { + return; + } Block block = event.getBlock(); Player player = event.getPlayer(); - Portal portal = Portal.getByBlock(block); - if (portal == null && Stargate.protectEntrance) - portal = Portal.getByEntrance(block); - if (portal == null) return; + //Decide if a portal is broken + Portal portal = PortalHandler.getByBlock(block); + if (portal == null && Stargate.protectEntrance) { + portal = PortalHandler.getByEntrance(block); + } + if (portal == null) { + return; + } boolean deny = false; String denyMsg = ""; + //Decide if the user can destroy the portal if (!Stargate.canDestroy(player, portal)) { - denyMsg = "Permission Denied"; // TODO: Change to stargate.getString() + denyMsg = Stargate.getString("denyMsg"); deny = true; Stargate.log.info(Stargate.getString("prefix") + player.getName() + " tried to destroy gate"); } int cost = Stargate.getDestroyCost(player, portal.getGate()); + //Create and call a StarGateDestroyEvent StargateDestroyEvent destroyEvent = new StargateDestroyEvent(portal, player, deny, denyMsg, cost); Stargate.server.getPluginManager().callEvent(destroyEvent); if (destroyEvent.isCancelled()) { event.setCancelled(true); return; } + + //Destroy denied if (destroyEvent.getDeny()) { Stargate.sendMessage(player, destroyEvent.getDenyReason()); event.setCancelled(true); return; } - cost = destroyEvent.getCost(); - - if (cost != 0) { - if (!Stargate.chargePlayer(player, cost)) { - Stargate.debug("onBlockBreak", "Insufficient Funds"); - Stargate.sendMessage(player, Stargate.getString("inFunds")); - event.setCancelled(true); - return; - } - - if (cost > 0) { - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); - Stargate.sendMessage(player, deductMsg, false); - } else { - String refundMsg = Stargate.getString("ecoRefund"); - refundMsg = Stargate.replaceVars(refundMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(-cost), portal.getName()}); - Stargate.sendMessage(player, refundMsg, false); - } + //Take care of payment transactions + if (!handleEconomyPayment(destroyEvent, player, portal, event)) { + return; } - portal.unregister(true); + PortalHandler.unregister(portal, true); Stargate.sendMessage(player, Stargate.getString("destroyMsg"), false); } + /** + * Handles economy payment for breaking the portal + * @param destroyEvent

The destroy event

+ * @param player

The player which triggered the event

+ * @param portal

The broken portal

+ * @param event

The break event

+ * @return

True if the payment was successful. False if the event was cancelled

+ */ + private boolean handleEconomyPayment(StargateDestroyEvent destroyEvent, Player player, Portal portal, + BlockBreakEvent event) { + int cost = destroyEvent.getCost(); + if (cost != 0) { + if (!Stargate.chargePlayer(player, cost)) { + Stargate.debug("onBlockBreak", "Insufficient Funds"); + EconomyHelper.sendInsufficientFundsMessage(portal.getName(), player, cost); + event.setCancelled(true); + return false; + } + if (cost > 0) { + EconomyHelper.sendDeductMessage(portal.getName(), player, cost); + } else { + EconomyHelper.sendRefundMessage(portal.getName(), player, cost); + } + } + return true; + } + + /** + * Prevents any block physics events which may damage parts of the portal + * @param event

The event to check and possibly cancel

+ */ @EventHandler public void onBlockPhysics(BlockPhysicsEvent event) { Block block = event.getBlock(); @@ -112,27 +149,44 @@ public class BlockEventListener implements Listener { // Handle keeping portal material and buttons around if (block.getType() == Material.NETHER_PORTAL) { - portal = Portal.getByEntrance(block); + portal = PortalHandler.getByEntrance(block); } else if (MaterialHelper.isButtonCompatible(block.getType())) { - portal = Portal.getByControl(block); + portal = PortalHandler.getByControl(block); + } + if (portal != null) { + event.setCancelled(true); } - if (portal != null) event.setCancelled(true); } + /** + * Cancels any block move events which may cause a block to enter the opening of a portal + * + * @param event

The event to check and possibly cancel

+ */ @EventHandler public void onBlockFromTo(BlockFromToEvent event) { - Portal portal = Portal.getByEntrance(event.getBlock()); + Portal portal = PortalHandler.getByEntrance(event.getBlock()); if (portal != null) { event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); } } + /** + * Cancels any piston extend events if the target block is part of a portal + * + * @param event

The event to check and possibly cancel

+ */ @EventHandler public void onPistonExtend(BlockPistonExtendEvent event) { cancelPistonEvent(event, event.getBlocks()); } + /** + * Cancels any piston retract events if the target block is part of a portal + * + * @param event

The event to check and possibly cancel

+ */ @EventHandler public void onPistonRetract(BlockPistonRetractEvent event) { if (!event.isSticky()) { @@ -143,16 +197,18 @@ public class BlockEventListener implements Listener { /** * Cancels a piston event if it would destroy a portal - * @param event

The event to cancel

+ * + * @param event

The event to cancel

* @param blocks

The blocks included in the event

*/ private void cancelPistonEvent(BlockPistonEvent event, List blocks) { for (Block block : blocks) { - Portal portal = Portal.getByBlock(block); + Portal portal = PortalHandler.getByBlock(block); if (portal != null) { event.setCancelled(true); return; } } } + } diff --git a/src/main/java/net/knarcraft/stargate/listener/BungeeCordListener.java b/src/main/java/net/knarcraft/stargate/listener/BungeeCordListener.java index 51be7d5..69f5105 100644 --- a/src/main/java/net/knarcraft/stargate/listener/BungeeCordListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/BungeeCordListener.java @@ -1,9 +1,11 @@ package net.knarcraft.stargate.listener; import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.PortalHandler; import net.knarcraft.stargate.Stargate; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; +import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.io.DataInputStream; @@ -19,7 +21,7 @@ import java.io.IOException; public class BungeeCordListener implements PluginMessageListener { @Override - public void onPluginMessageReceived(String channel, Player unused, byte[] message) { + public void onPluginMessageReceived(@NotNull String channel, @NotNull Player unused, @NotNull byte[] message) { if (!Stargate.enableBungee || !channel.equals("BungeeCord")) { return; } @@ -39,7 +41,7 @@ public class BungeeCordListener implements PluginMessageListener { if (player == null) { Stargate.bungeeQueue.put(playerName.toLowerCase(), destination); } else { - Portal destinationPortal = Portal.getBungeeGate(destination); + Portal destinationPortal = PortalHandler.getBungeeGate(destination); // Specified an invalid gate. For now we'll just let them connect at their current location if (destinationPortal == null) { Stargate.log.info(Stargate.getString("prefix") + "Bungee gate " + destination + " does not exist"); diff --git a/src/main/java/net/knarcraft/stargate/listener/EntityEventListener.java b/src/main/java/net/knarcraft/stargate/listener/EntityEventListener.java index a0f7759..dafec9d 100644 --- a/src/main/java/net/knarcraft/stargate/listener/EntityEventListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/EntityEventListener.java @@ -1,25 +1,39 @@ package net.knarcraft.stargate.listener; import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.PortalHandler; import net.knarcraft.stargate.Stargate; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityExplodeEvent; +/** + * This listener listens for any relevant events on portal entities + */ +@SuppressWarnings("unused") public class EntityEventListener implements Listener { + + /** + * This method catches any explosion events + * + *

If destroyed by explosions is enabled, any portals destroyed by the explosion will be unregistered. If not, + * the explosion will be cancelled.

+ * + * @param event

The triggered explosion event

+ */ @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (event.isCancelled()) { return; } - for (Block b : event.blockList()) { - Portal portal = Portal.getByBlock(b); + for (Block block : event.blockList()) { + Portal portal = PortalHandler.getByBlock(block); if (portal == null) { continue; } if (Stargate.destroyedByExplosion()) { - portal.unregister(true); + PortalHandler.unregister(portal, true); } else { event.setCancelled(true); break; diff --git a/src/main/java/net/knarcraft/stargate/listener/PlayerEventsListener.java b/src/main/java/net/knarcraft/stargate/listener/PlayerEventsListener.java index 36399b9..6d7e3c4 100644 --- a/src/main/java/net/knarcraft/stargate/listener/PlayerEventsListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/PlayerEventsListener.java @@ -1,6 +1,7 @@ package net.knarcraft.stargate.listener; -import net.knarcraft.stargate.EconomyHandler; +import net.knarcraft.stargate.PortalHandler; +import net.knarcraft.stargate.utility.EconomyHelper; import net.knarcraft.stargate.utility.MaterialHelper; import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Stargate; @@ -39,7 +40,7 @@ public class PlayerEventsListener implements Listener { return; } - Portal portal = Portal.getBungeeGate(destination); + Portal portal = PortalHandler.getBungeeGate(destination); if (portal == null) { Stargate.debug("PlayerJoin", "Error fetching destination portal: " + destination); return; @@ -54,7 +55,7 @@ public class PlayerEventsListener implements Listener { if (!event.isCancelled() && (cause == PlayerTeleportEvent.TeleportCause.NETHER_PORTAL || cause == PlayerTeleportEvent.TeleportCause.END_GATEWAY && World.Environment.THE_END == event.getFrom().getWorld().getEnvironment()) - && Portal.getByAdjacentEntrance(event.getFrom()) != null) { + && PortalHandler.getByAdjacentEntrance(event.getFrom()) != null) { event.setCancelled(true); } } @@ -69,29 +70,29 @@ public class PlayerEventsListener implements Listener { } Player player = event.getPlayer(); - Portal portal = Portal.getByEntrance(event.getTo()); + Portal entracePortal = PortalHandler.getByEntrance(event.getTo()); // No portal or not open - if (portal == null || !portal.isOpen()) return; + if (entracePortal == null || !entracePortal.isOpen()) return; // Not open for this player - if (!portal.isOpenFor(player)) { + if (!entracePortal.isOpenFor(player)) { Stargate.sendMessage(player, Stargate.getString("denyMsg")); - portal.teleport(player, portal, event); + entracePortal.teleport(player, entracePortal, event); return; } - Portal destination = portal.getDestination(player); - if (!portal.isBungee() && destination == null) return; + Portal destination = entracePortal.getDestination(player); + if (!entracePortal.isBungee() && destination == null) return; boolean deny = false; // Check if player has access to this server for Bungee gates - if (portal.isBungee()) { - if (!Stargate.canAccessServer(player, portal.getNetwork())) { + if (entracePortal.isBungee()) { + if (!Stargate.canAccessServer(player, entracePortal.getNetwork())) { deny = true; } } else { // Check if player has access to this network - if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { + if (!Stargate.canAccessNetwork(player, entracePortal.getNetwork())) { deny = true; } @@ -101,67 +102,42 @@ public class PlayerEventsListener implements Listener { } } - if (!Stargate.canAccessPortal(player, portal, deny)) { + if (!Stargate.canAccessPortal(player, entracePortal, deny)) { Stargate.sendMessage(player, Stargate.getString("denyMsg")); - portal.teleport(player, portal, event); - portal.close(false); + entracePortal.teleport(player, entracePortal, event); + entracePortal.close(false); return; } - int cost = Stargate.getUseCost(player, portal, destination); + int cost = Stargate.getUseCost(player, entracePortal, destination); if (cost > 0) { - boolean success; - if (portal.getGate().getToOwner()) { - success = portal.getOwnerUUID() != null && Stargate.chargePlayer(player, portal.getOwnerUUID(), cost); - } else { - success = Stargate.chargePlayer(player, cost); - } - if (!success) { - // Insufficient Funds - Stargate.sendMessage(player, Stargate.getString("inFunds")); - portal.close(false); + if (!EconomyHelper.payTeleportFee(entracePortal, player, cost)) { return; } - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); - Stargate.sendMessage(player, deductMsg, false); - if (portal.getGate().getToOwner() && portal.getOwnerUUID() != null) { - Player p; - if (portal.getOwnerUUID() != null) { - p = Stargate.server.getPlayer(portal.getOwnerUUID()); - } else { - p = Stargate.server.getPlayer(portal.getOwnerName()); - } - if (p != null) { - String obtainedMsg = Stargate.getString("ecoObtain"); - obtainedMsg = Stargate.replaceVars(obtainedMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); - Stargate.sendMessage(p, obtainedMsg, false); - } - } } Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false); // BungeeCord Support - if (portal.isBungee()) { + if (entracePortal.isBungee()) { if (!Stargate.enableBungee) { player.sendMessage(Stargate.getString("bungeeDisabled")); - portal.close(false); + entracePortal.close(false); return; } // Teleport the player back to this gate, for sanity's sake - portal.teleport(player, portal, event); + entracePortal.teleport(player, entracePortal, event); // Send the SGBungee packet first, it will be queued by BC if required try { // Build the message, format is #@# - String msg = event.getPlayer().getName() + "#@#" + portal.getDestinationName(); + String msg = event.getPlayer().getName() + "#@#" + entracePortal.getDestinationName(); // Build the message data, sent over the SGBungee bungeecord channel ByteArrayOutputStream bao = new ByteArrayOutputStream(); DataOutputStream msgData = new DataOutputStream(bao); msgData.writeUTF("Forward"); - msgData.writeUTF(portal.getNetwork()); // Server + msgData.writeUTF(entracePortal.getNetwork()); // Server msgData.writeUTF("SGBungee"); // Channel msgData.writeShort(msg.length()); // Data Length msgData.writeBytes(msg); // Data @@ -177,7 +153,7 @@ public class PlayerEventsListener implements Listener { ByteArrayOutputStream bao = new ByteArrayOutputStream(); DataOutputStream msgData = new DataOutputStream(bao); msgData.writeUTF("Connect"); - msgData.writeUTF(portal.getNetwork()); + msgData.writeUTF(entracePortal.getNetwork()); player.sendPluginMessage(Stargate.stargate, "BungeeCord", bao.toByteArray()); bao.reset(); @@ -188,12 +164,12 @@ public class PlayerEventsListener implements Listener { } // Close portal if required (Should never be) - portal.close(false); + entracePortal.close(false); return; } - destination.teleport(player, portal, event); - portal.close(false); + destination.teleport(player, entracePortal, event); + entracePortal.close(false); } @EventHandler @@ -208,7 +184,7 @@ public class PlayerEventsListener implements Listener { // Right click if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (block.getBlockData() instanceof WallSign) { - Portal portal = Portal.getByBlock(block); + Portal portal = PortalHandler.getByBlock(block); if (portal == null) { return; } @@ -246,7 +222,7 @@ public class PlayerEventsListener implements Listener { eventTime = System.currentTimeMillis(); } - Portal portal = Portal.getByBlock(block); + Portal portal = PortalHandler.getByBlock(block); if (portal == null) { return; } @@ -277,8 +253,10 @@ public class PlayerEventsListener implements Listener { if (event.getAction() == Action.LEFT_CLICK_BLOCK) { // Check if we're scrolling a sign if (block.getBlockData() instanceof WallSign) { - Portal portal = Portal.getByBlock(block); - if (portal == null) return; + Portal portal = PortalHandler.getByBlock(block); + if (portal == null) { + return; + } event.setUseInteractedBlock(Event.Result.DENY); // Only cancel event in creative mode diff --git a/src/main/java/net/knarcraft/stargate/listener/VehicleEventListener.java b/src/main/java/net/knarcraft/stargate/listener/VehicleEventListener.java index 1c31b69..31fd75a 100644 --- a/src/main/java/net/knarcraft/stargate/listener/VehicleEventListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/VehicleEventListener.java @@ -1,7 +1,9 @@ package net.knarcraft.stargate.listener; import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.PortalHandler; import net.knarcraft.stargate.Stargate; +import net.knarcraft.stargate.utility.EconomyHelper; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; @@ -11,90 +13,86 @@ import org.bukkit.event.vehicle.VehicleMoveEvent; import java.util.List; +@SuppressWarnings("unused") public class VehicleEventListener implements Listener { + + /** + * Check for a vehicle moving through a portal + * @param event

The triggered move event

+ */ @EventHandler public void onVehicleMove(VehicleMoveEvent event) { - if (!Stargate.handleVehicles) return; + if (!Stargate.handleVehicles) { + return; + } List passengers = event.getVehicle().getPassengers(); Vehicle vehicle = event.getVehicle(); - Portal portal = Portal.getByEntrance(event.getTo()); - if (portal == null || !portal.isOpen()) return; + Portal entrancePortal = PortalHandler.getByEntrance(event.getTo()); - // We don't support vehicles in Bungee portals - if (portal.isBungee()) return; + //Return if the portal cannot be teleported through + if (entrancePortal == null || !entrancePortal.isOpen() || entrancePortal.isBungee()) { + return; + } if (!passengers.isEmpty() && passengers.get(0) instanceof Player) { - /* - Player player = (Player) passengers.get(0); - if (!portal.isOpenFor(player)) { - stargate.sendMessage(player, stargate.getString("denyMsg")); - return; - } - - Portal dest = portal.getDestination(player); - if (dest == null) return; - boolean deny = false; - // Check if player has access to this network - if (!canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - // Check if player has access to destination world - if (!canAccessWorld(player, dest.getWorld().getName())) { - deny = true; - } - - if (!canAccessPortal(player, portal, deny)) { - stargate.sendMessage(player, stargate.getString("denyMsg")); - portal.close(false); - return; - } - - int cost = stargate.getUseCost(player, portal, dest); - if (cost > 0) { - boolean success; - if(portal.getGate().getToOwner()) { - if(portal.getOwnerUUID() == null) { - success = stargate.chargePlayer(player, portal.getOwnerUUID(), cost); - } else { - success = stargate.chargePlayer(player, portal.getOwnerName(), cost); - } - } else { - success = stargate.chargePlayer(player, cost); - } - if(!success) { - // Insufficient Funds - stargate.sendMessage(player, stargate.getString("inFunds")); - portal.close(false); - return; - } - String deductMsg = stargate.getString("ecoDeduct"); - deductMsg = stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - sendMessage(player, deductMsg, false); - if (portal.getGate().getToOwner()) { - Player p; - if(portal.getOwnerUUID() != null) { - p = server.getPlayer(portal.getOwnerUUID()); - } else { - p = server.getPlayer(portal.getOwnerName()); - } - if (p != null) { - String obtainedMsg = stargate.getString("ecoObtain"); - obtainedMsg = stargate.replaceVars(obtainedMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - stargate.sendMessage(p, obtainedMsg, false); - } - } - } - - stargate.sendMessage(player, stargate.getString("teleportMsg"), false); - dest.teleport(vehicle); - portal.close(false); - */ + Stargate.log.info(Stargate.getString("prefox") + "Found passenger minecart"); + teleportPlayerAndVehicle(entrancePortal, vehicle, passengers); } else { - Portal dest = portal.getDestination(); - if (dest == null) return; - dest.teleport(vehicle); + Stargate.log.info(Stargate.getString("prefox") + "Found empty minecart"); + Portal destinationPortal = entrancePortal.getDestination(); + if (destinationPortal == null) { + Stargate.log.warning(Stargate.getString("prefox") + "Unable to find portal destination"); + return; + } + destinationPortal.teleport(vehicle); } } + + /** + * Teleports a player and the minecart the player sits in + * @param entrancePortal

The portal the minecart entered

+ * @param vehicle

The vehicle to teleport

+ * @param passengers

Any entities sitting in the minecart

+ */ + private void teleportPlayerAndVehicle(Portal entrancePortal, Vehicle vehicle, List passengers) { + Player player = (Player) passengers.get(0); + if (!entrancePortal.isOpenFor(player)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + Portal destinationPortal = entrancePortal.getDestination(player); + if (destinationPortal == null) { + return; + } + boolean deny = false; + // Check if player has access to this network + if (!Stargate.canAccessNetwork(player, entrancePortal.getNetwork())) { + deny = true; + } + + // Check if player has access to destination world + if (!Stargate.canAccessWorld(player, destinationPortal.getWorld().getName())) { + deny = true; + } + + if (!Stargate.canAccessPortal(player, entrancePortal, deny)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + entrancePortal.close(false); + return; + } + + int cost = Stargate.getUseCost(player, entrancePortal, destinationPortal); + if (cost > 0) { + if (!EconomyHelper.payTeleportFee(entrancePortal, player, cost)) { + return; + } + } + + Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false); + destinationPortal.teleport(vehicle); + entrancePortal.close(false); + } + } diff --git a/src/main/java/net/knarcraft/stargate/listener/WorldEventListener.java b/src/main/java/net/knarcraft/stargate/listener/WorldEventListener.java index e7d33be..252dbe3 100644 --- a/src/main/java/net/knarcraft/stargate/listener/WorldEventListener.java +++ b/src/main/java/net/knarcraft/stargate/listener/WorldEventListener.java @@ -1,6 +1,7 @@ package net.knarcraft.stargate.listener; import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.PortalHandler; import net.knarcraft.stargate.Stargate; import org.bukkit.World; import org.bukkit.event.EventHandler; @@ -12,7 +13,7 @@ public class WorldEventListener implements Listener { @EventHandler public void onWorldLoad(WorldLoadEvent event) { if (!Stargate.managedWorlds.contains(event.getWorld().getName()) - && Portal.loadAllGates(event.getWorld())) { + && PortalHandler.loadAllGates(event.getWorld())) { Stargate.managedWorlds.add(event.getWorld().getName()); } } @@ -24,10 +25,10 @@ public class WorldEventListener implements Listener { World w = event.getWorld(); if (Stargate.managedWorlds.contains(w.getName())) { Stargate.managedWorlds.remove(w.getName()); - Portal.clearGates(); + PortalHandler.clearGates(); for (World world : Stargate.server.getWorlds()) { if (Stargate.managedWorlds.contains(world.getName())) { - Portal.loadAllGates(world); + PortalHandler.loadAllGates(world); } } } diff --git a/src/main/java/net/knarcraft/stargate/utility/EconomyHelper.java b/src/main/java/net/knarcraft/stargate/utility/EconomyHelper.java new file mode 100644 index 0000000..59ed896 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/utility/EconomyHelper.java @@ -0,0 +1,113 @@ +package net.knarcraft.stargate.utility; + +import net.knarcraft.stargate.EconomyHandler; +import net.knarcraft.stargate.Portal; +import net.knarcraft.stargate.Stargate; +import org.bukkit.entity.Player; + +public class EconomyHelper { + + /** + * Tries to make the given user pay the teleport fee + * @param entrancePortal

The portal the player is entering

+ * @param player

The player wishing to teleport

+ * @param cost

The cost of teleportation

+ * @return

True if payment was successful

+ */ + public static boolean payTeleportFee(Portal entrancePortal, Player player, int cost) { + boolean success; + + //Try to charge the player + if (entrancePortal.getGate().getToOwner()) { + success = entrancePortal.getOwnerUUID() != null && Stargate.chargePlayer(player, entrancePortal.getOwnerUUID(), cost); + } else { + success = Stargate.chargePlayer(player, cost); + } + + // Insufficient Funds + if (!success) { + sendInsufficientFundsMessage(entrancePortal.getName(), player, cost); + entrancePortal.close(false); + return false; + } + + //Send the deduct message to the player + sendDeductMessage(entrancePortal.getName(), player, cost); + + if (entrancePortal.getGate().getToOwner()) { + Player gateOwner; + if (entrancePortal.getOwnerUUID() != null) { + gateOwner = Stargate.server.getPlayer(entrancePortal.getOwnerUUID()); + } else { + gateOwner = Stargate.server.getPlayer(entrancePortal.getOwnerName()); + } + + //Notify the gate owner of received payment + if (gateOwner != null) { + sendObtainMessage(entrancePortal.getName(), gateOwner, cost); + } + } + return true; + } + + /** + * Sends a message to the gate owner telling him/her how much he/she earned from a player using his/her gate + * @param portalName

The name of the used portal

+ * @param portalOwner

The owner of the portal

+ * @param earnings

The amount the owner earned

+ */ + public static void sendObtainMessage(String portalName, Player portalOwner, int earnings) { + String obtainedMsg = Stargate.getString("ecoObtain"); + obtainedMsg = replaceVars(obtainedMsg, portalName, earnings); + Stargate.sendMessage(portalOwner, obtainedMsg, false); + } + + /** + * Sends a message telling the user how much they paid for interacting with a portal + * @param portalName

The name of the portal interacted with

+ * @param player

The interacting player

+ * @param cost

The cost of the interaction

+ */ + public static void sendDeductMessage(String portalName, Player player, int cost) { + String deductMsg = Stargate.getString("ecoDeduct"); + deductMsg = replaceVars(deductMsg, portalName, cost); + Stargate.sendMessage(player, deductMsg, false); + } + + /** + * Sends a message telling the user they don't have enough funds to do a portal interaction + * @param portalName

The name of the portal interacted with

+ * @param player

The interacting player

+ * @param cost

The cost of the interaction

+ */ + public static void sendInsufficientFundsMessage(String portalName, Player player, int cost) { + String inFundMsg = Stargate.getString("ecoInFunds"); + inFundMsg = replaceVars(inFundMsg, portalName, cost); + Stargate.sendMessage(player, inFundMsg); + } + + /** + * Sends a message telling the user how much they are refunded for breaking their portal + * @param portalName

The name of the broken portal

+ * @param player

The player breaking the portal

+ * @param cost

The amount the user has to pay for destroying the portal. (expects a negative value)

+ */ + public static void sendRefundMessage(String portalName, Player player, int cost) { + String refundMsg = Stargate.getString("ecoRefund"); + refundMsg = replaceVars(refundMsg, portalName, -cost); + Stargate.sendMessage(player, refundMsg, false); + } + + /** + * Replaces the cost and portal variables in a string + * @param message

The message to replace variables in

+ * @param portalName

The name of the relevant portal

+ * @param cost

The cost for a given interaction

+ * @return

The same string with cost and portal variables replaced

+ */ + private static String replaceVars(String message, String portalName, int cost) { + return Stargate.replaceVars(message, new String[]{"%cost%", "%portal%"}, + new String[]{EconomyHandler.format(cost), portalName}); + } + +}