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
This commit is contained in:
Kristian Knarvik 2021-02-12 00:26:47 +01:00
parent bd4586e386
commit 42fa6ed8d7
25 changed files with 1470 additions and 1269 deletions

View File

@ -9,27 +9,6 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign; import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign; 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 <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** /**
* This class represents a block location * This class represents a block location
* *

View File

@ -9,25 +9,6 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import java.util.UUID; import java.util.UUID;
/*
stargate - A portal plugin for Bukkit
Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
Copyright (C) 2021 Kristian Knarvik
<p>
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.
<p>
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.
<p>
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** /**
* This handler handles economy actions such as payment for using a gate * This handler handles economy actions such as payment for using a gate
*/ */

View File

@ -15,27 +15,6 @@ import java.util.Map;
import java.util.Scanner; import java.util.Scanner;
import java.util.logging.Level; 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 <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class Gate { public class Gate {
private static final Character ANYTHING = ' '; private static final Character ANYTHING = ' ';

View File

@ -18,25 +18,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
/*
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** /**
* This class is responsible for loading all strings which are translated into several languages * This class is responsible for loading all strings which are translated into several languages
*/ */

File diff suppressed because it is too large Load Diff

View File

@ -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<BlockLocation, Portal> lookupBlocks = new HashMap<>();
private static final Map<BlockLocation, Portal> lookupEntrances = new HashMap<>();
private static final Map<BlockLocation, Portal> lookupControls = new HashMap<>();
private static final List<Portal> allPortals = new ArrayList<>();
private static final HashMap<String, List<String>> allPortalsNet = new HashMap<>();
private static final HashMap<String, HashMap<String, Portal>> lookupNamesNet = new HashMap<>();
// A list of Bungee gates
private static final Map<String, Portal> bungeePortals = new HashMap<>();
public static List<String> getNetwork(String network) {
return allPortalsNet.get(network.toLowerCase());
}
/**
* Gets all destinations in the network viewable by the given player
* @param player <p>The player who wants to see destinations</p>
* @param network <p>The network to get destinations from</p>
* @return <p>All destinations the player can go to</p>
*/
public static ArrayList<String> getDestinations(Player player, String network) {
ArrayList<String> 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 <p>The portal to un-register</p>
* @param removeAll <p>Whether to remove the portal from the list of all portals</p>
*/
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 <p>The portal to register</p>
*/
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 <p>The sign change event which initialized the creation</p>
* @param player <p>The player who's creating the portal</p>
* @return <p>The created portal</p>
*/
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<String> 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 <p>The name of the portal</p>
* @param network <p>The network the portal is connected to</p>
* @return <p>The portal with the given name or null</p>
*/
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 <p>The location of the portal's entrance</p>
* @return <p>The portal at the given location</p>
*/
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 <p>The block at the portal's entrance</p>
* @return <p>The portal at the given block's location</p>
*/
public static Portal getByEntrance(Block block) {
return lookupEntrances.get(new BlockLocation(block));
}
/**
* Gets a portal given a location adjacent to its entrance
* @param loc <p>A location adjacent to the portal's entrance</p>
* @return <p>The portal adjacent to the given location</p>
*/
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 <p>The portal's control block</p>
* @return <p>The gate with the given control block</p>
*/
public static Portal getByControl(Block block) {
return lookupControls.get(new BlockLocation(block));
}
/**
* Gets a portal given a block
* @param block <p>One of the loaded lookup blocks</p>
* @return <p>The portal corresponding to the block</p>
*/
public static Portal getByBlock(Block block) {
return lookupBlocks.get(new BlockLocation(block));
}
/**
* Gets a bungee gate given its name
* @param name <p>The name of the bungee gate to get</p>
* @return <p>A bungee gate</p>
*/
public static Portal getBungeeGate(String name) {
return bungeePortals.get(name.toLowerCase());
}
/**
* Saves all gates for the given world
* @param world <p>The world to save gates for</p>
*/
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 <p>The world to load gates for</p>
* @return <p>True if gates could be loaded</p>
*/
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 <p>The world to load gates for</p>
* @param database <p>The database file containing the gates</p>
* @return <p>True if the gates were loaded successfully</p>
*/
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<Integer, Integer> 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 <p>The portal to apply the options to</p>
* @param portalData <p>The string list containing all information about a portal</p>
*/
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 <p>A TwoTuple where the first value is the number of always open gates and the second value is the total number of gates</p>
*/
private static TwoTuple<Integer, Integer> openAlwaysOpenGates() {
int portalCount = 0;
int openCount = 0;
for (Iterator<Portal> 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 <p>The portal of the star gate</p>
*/
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 <p>The name to filter</p>
* @return <p>The filtered name</p>
*/
public static String filterName(String input) {
if (input == null) {
return "";
}
return input.replaceAll("[|:#]", "").trim();
}
}

View File

@ -1,32 +1,22 @@
package net.knarcraft.stargate; package net.knarcraft.stargate;
/** /**
* stargate - A portal plugin for Bukkit * This stores a block location as a vector in an alternate coordinate system
* Copyright (C) 2011 Shaun (sturmeh) *
* Copyright (C) 2011 Dinnerbone * <p></p>
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
public class RelativeBlockVector { public class RelativeBlockVector {
private int right = 0; private int right;
private int depth = 0; private int depth;
private int distance = 0; private int distance;
/**
* Instantiates a new relative block vector
* @param right <p>The x coordinate in the gate description</p>
* @param depth <p>The y coordinate in the gate description</p>
* @param distance <p></p>
*/
public RelativeBlockVector(int right, int depth, int distance) { public RelativeBlockVector(int right, int depth, int distance) {
this.right = right; this.right = right;
this.depth = depth; this.depth = depth;

View File

@ -24,6 +24,7 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader; import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.HashMap;
@ -36,27 +37,6 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; 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 <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class Stargate extends JavaPlugin { public class Stargate extends JavaPlugin {
@ -121,8 +101,8 @@ public class Stargate extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
Portal.closeAllGates(); PortalHandler.closeAllGates();
Portal.clearGates(); PortalHandler.clearGates();
managedWorlds.clear(); managedWorlds.clear();
getServer().getScheduler().cancelTasks(this); getServer().getScheduler().cancelTasks(this);
} }
@ -251,7 +231,7 @@ public class Stargate extends JavaPlugin {
public void loadAllPortals() { public void loadAllPortals() {
for (World world : getServer().getWorlds()) { for (World world : getServer().getWorlds()) {
if (!managedWorlds.contains(world.getName())) { if (!managedWorlds.contains(world.getName())) {
Portal.loadAllGates(world); PortalHandler.loadAllGates(world);
managedWorlds.add(world.getName()); managedWorlds.add(world.getName());
} }
} }
@ -261,11 +241,15 @@ public class Stargate extends JavaPlugin {
// Only migrate if new file doesn't exist. // Only migrate if new file doesn't exist.
File newPortalDir = new File(portalFolder); File newPortalDir = new File(portalFolder);
if (!newPortalDir.exists()) { 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"); File newFile = new File(portalFolder, getServer().getWorlds().get(0).getName() + ".db");
if (!newFile.exists()) { 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 @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(); String cmd = command.getName();
if (cmd.equalsIgnoreCase("sg")) { if (cmd.equalsIgnoreCase("sg")) {
if (args.length != 1) return false; if (args.length != 1) return false;
@ -680,7 +664,7 @@ public class Stargate extends JavaPlugin {
activeList.clear(); activeList.clear();
openList.clear(); openList.clear();
managedWorlds.clear(); managedWorlds.clear();
Portal.clearGates(); PortalHandler.clearGates();
Gate.clearGates(); Gate.clearGates();
// Store the old Bungee enabled value // Store the old Bungee enabled value

View File

@ -0,0 +1,39 @@
package net.knarcraft.stargate;
/**
* This class allows storing two values of any type
* @param <K> <p>The first type</p>
* @param <L> <p>The second type</p>
*/
public class TwoTuple<K,L> {
private K firstValue;
private L secondValue;
/**
* Instantiate a new TwoTuple
* @param firstValue <p>The first value</p>
* @param secondValue <p>The second value</p>
*/
public TwoTuple(K firstValue, L secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
/**
* Gets the first value
* @return <p>The first value</p>
*/
public K getFirstValue() {
return firstValue;
}
/**
* Gets the second value
* @return <p>The second value</p>
*/
public L getSecondValue() {
return secondValue;
}
}

View File

@ -4,26 +4,6 @@ import net.knarcraft.stargate.Portal;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
/*
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* 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 <http://www.gnu.org/licenses/>.
*/
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class StargateAccessEvent extends StargateEvent { public class StargateAccessEvent extends StargateEvent {
@ -32,15 +12,21 @@ public class StargateAccessEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
/**
* Gets a handler-list containing all event handlers
* @return <p>A handler-list with all event handlers</p>
*/
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
/**
* Instantiates a new stargate access event
* @param player <p>The player involved in the vent</p>
* @param portal <p>The portal involved in the event</p>
* @param deny <p>Whether the event should be denied</p>
*/
public StargateAccessEvent(Player player, Portal portal, boolean deny) { public StargateAccessEvent(Player player, Portal portal, boolean deny) {
super("StargateAccessEvent", portal); super("StargateAccessEvent", portal);
@ -63,9 +49,17 @@ public class StargateAccessEvent extends StargateEvent {
public void setDeny(boolean deny) { public void setDeny(boolean deny) {
this.deny = deny; this.deny = deny;
} }
/**
* Gets the player involved in this stargate access event
* @return <p>The player involved in this event</p>
*/
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
@Override
public @org.jetbrains.annotations.NotNull HandlerList getHandlers() {
return handlers;
}
} }

View File

@ -3,28 +3,10 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargateActivateEvent extends StargateEvent { public class StargateActivateEvent extends StargateEvent {
private final Player player; private final Player player;
@ -33,6 +15,7 @@ public class StargateActivateEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -2,25 +2,7 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargateCloseEvent extends StargateEvent { public class StargateCloseEvent extends StargateEvent {
@ -28,6 +10,7 @@ public class StargateCloseEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -3,25 +3,7 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargateCreateEvent extends StargateEvent { public class StargateCreateEvent extends StargateEvent {
@ -33,6 +15,7 @@ public class StargateCreateEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -2,30 +2,13 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargateDeactivateEvent extends StargateEvent { public class StargateDeactivateEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -3,26 +3,11 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/** /**
* stargate - A portal plugin for Bukkit * This event represents an event where a star gate is destroyed or attempted to be destroyed
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
public class StargateDestroyEvent extends StargateEvent { public class StargateDestroyEvent extends StargateEvent {
private final Player player; private final Player player;
@ -32,14 +17,27 @@ public class StargateDestroyEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
/**
* Gets a handler-list containing all event handlers
* @return <p>A handler-list with all event handlers</p>
*/
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
/**
* Instantiates a new Stargate Destroy Event
* @param portal <p>The portal destroyed</p>
* @param player <p>The player destroying the portal</p>
* @param deny <p>Whether the event should be denied (cancelled)</p>
* @param denyMsg <p>The message to display if the event is denied</p>
* @param cost <p>The cost of destroying the portal</p>
*/
public StargateDestroyEvent(Portal portal, Player player, boolean deny, String denyMsg, int cost) { public StargateDestroyEvent(Portal portal, Player player, boolean deny, String denyMsg, int cost) {
super("StargateDestroyEvent", portal); super("StargateDestroyEvent", portal);
this.player = player; this.player = player;
@ -48,30 +46,58 @@ public class StargateDestroyEvent extends StargateEvent {
this.cost = cost; this.cost = cost;
} }
/**
* Gets the player causing the destroy event
* @return <p>The player causing the destroy event</p>
*/
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
/**
* Gets whether this event should be denied
* @return <p>Whether this event should be denied</p>
*/
public boolean getDeny() { public boolean getDeny() {
return deny; return deny;
} }
/**
* Sets whether this event should be denied
* @param deny <p>Whether this event should be denied</p>
*/
public void setDeny(boolean deny) { public void setDeny(boolean deny) {
this.deny = deny; this.deny = deny;
} }
/**
* Gets the reason the event was denied
* @return <p>The reason the event was denied</p>
*/
public String getDenyReason() { public String getDenyReason() {
return denyReason; return denyReason;
} }
/**
* Sets the reason the event was denied
* @param denyReason <p>The reason the event was denied</p>
*/
public void setDenyReason(String denyReason) { public void setDenyReason(String denyReason) {
this.denyReason = denyReason; this.denyReason = denyReason;
} }
/**
* Gets the cost of destroying the portal
* @return <p>The cost of destroying the portal</p>
*/
public int getCost() { public int getCost() {
return cost; return cost;
} }
/**
* Sets the cost of destroying the portal
* @param cost <p>The cost of destroying the portal</p>
*/
public void setCost(int cost) { public void setCost(int cost) {
this.cost = cost; this.cost = cost;
} }

View File

@ -4,25 +4,6 @@ import net.knarcraft.stargate.Portal;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
/*
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** /**
* An abstract event describing any stargate event * An abstract event describing any stargate event
*/ */
@ -37,6 +18,7 @@ public abstract class StargateEvent extends Event implements Cancellable {
this.cancelled = false; this.cancelled = false;
} }
public Portal getPortal() { public Portal getPortal() {
return portal; return portal;
} }

View File

@ -3,25 +3,7 @@ package net.knarcraft.stargate.event;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargateOpenEvent extends StargateEvent { public class StargateOpenEvent extends StargateEvent {
@ -30,6 +12,7 @@ public class StargateOpenEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -4,25 +4,7 @@ import net.knarcraft.stargate.Portal;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* stargate - A portal plugin for Bukkit
* Copyright (C) 2011, 2012 Steven "Drakia" Scott <Contact@TheDgtl.net>
* Copyright (C) 2021 Kristian Knarvik
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class StargatePortalEvent extends StargateEvent { public class StargatePortalEvent extends StargateEvent {
@ -32,6 +14,7 @@ public class StargatePortalEvent extends StargateEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@NotNull
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -1,9 +1,10 @@
package net.knarcraft.stargate.listener; package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.EconomyHandler;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.PortalHandler;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.event.StargateDestroyEvent; import net.knarcraft.stargate.event.StargateDestroyEvent;
import net.knarcraft.stargate.utility.EconomyHelper;
import net.knarcraft.stargate.utility.MaterialHelper; import net.knarcraft.stargate.utility.MaterialHelper;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -22,7 +23,17 @@ import org.bukkit.event.block.SignChangeEvent;
import java.util.List; 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 { public class BlockEventListener implements Listener {
/**
* Detects sign changes to detect if the user is creating a new gate
*
* @param event <p>The triggered event</p>
*/
@EventHandler @EventHandler
public void onSignChange(SignChangeEvent event) { public void onSignChange(SignChangeEvent event) {
if (event.isCancelled()) { if (event.isCancelled()) {
@ -30,11 +41,12 @@ public class BlockEventListener implements Listener {
} }
Player player = event.getPlayer(); Player player = event.getPlayer();
Block block = event.getBlock(); Block block = event.getBlock();
//Ignore normal signs
if (!(block.getBlockData() instanceof WallSign)) { if (!(block.getBlockData() instanceof WallSign)) {
return; return;
} }
final Portal portal = Portal.createPortal(event, player); final Portal portal = PortalHandler.createPortal(event, player);
// Not creating a gate, just placing a sign // Not creating a gate, just placing a sign
if (portal == null) { if (portal == null) {
return; return;
@ -42,69 +54,94 @@ public class BlockEventListener implements Listener {
Stargate.sendMessage(player, Stargate.getString("createMsg"), false); Stargate.sendMessage(player, Stargate.getString("createMsg"), false);
Stargate.debug("onSignChange", "Initialized stargate: " + portal.getName()); 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) // Switch to HIGHEST priority so as to come after block protection plugins (Hopefully)
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) return; if (event.isCancelled()) {
return;
}
Block block = event.getBlock(); Block block = event.getBlock();
Player player = event.getPlayer(); Player player = event.getPlayer();
Portal portal = Portal.getByBlock(block); //Decide if a portal is broken
if (portal == null && Stargate.protectEntrance) Portal portal = PortalHandler.getByBlock(block);
portal = Portal.getByEntrance(block); if (portal == null && Stargate.protectEntrance) {
if (portal == null) return; portal = PortalHandler.getByEntrance(block);
}
if (portal == null) {
return;
}
boolean deny = false; boolean deny = false;
String denyMsg = ""; String denyMsg = "";
//Decide if the user can destroy the portal
if (!Stargate.canDestroy(player, portal)) { if (!Stargate.canDestroy(player, portal)) {
denyMsg = "Permission Denied"; // TODO: Change to stargate.getString() denyMsg = Stargate.getString("denyMsg");
deny = true; deny = true;
Stargate.log.info(Stargate.getString("prefix") + player.getName() + " tried to destroy gate"); Stargate.log.info(Stargate.getString("prefix") + player.getName() + " tried to destroy gate");
} }
int cost = Stargate.getDestroyCost(player, portal.getGate()); int cost = Stargate.getDestroyCost(player, portal.getGate());
//Create and call a StarGateDestroyEvent
StargateDestroyEvent destroyEvent = new StargateDestroyEvent(portal, player, deny, denyMsg, cost); StargateDestroyEvent destroyEvent = new StargateDestroyEvent(portal, player, deny, denyMsg, cost);
Stargate.server.getPluginManager().callEvent(destroyEvent); Stargate.server.getPluginManager().callEvent(destroyEvent);
if (destroyEvent.isCancelled()) { if (destroyEvent.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
//Destroy denied
if (destroyEvent.getDeny()) { if (destroyEvent.getDeny()) {
Stargate.sendMessage(player, destroyEvent.getDenyReason()); Stargate.sendMessage(player, destroyEvent.getDenyReason());
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
cost = destroyEvent.getCost(); //Take care of payment transactions
if (!handleEconomyPayment(destroyEvent, player, portal, event)) {
if (cost != 0) { return;
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);
}
} }
portal.unregister(true); PortalHandler.unregister(portal, true);
Stargate.sendMessage(player, Stargate.getString("destroyMsg"), false); Stargate.sendMessage(player, Stargate.getString("destroyMsg"), false);
} }
/**
* Handles economy payment for breaking the portal
* @param destroyEvent <p>The destroy event</p>
* @param player <p>The player which triggered the event</p>
* @param portal <p>The broken portal</p>
* @param event <p>The break event</p>
* @return <p>True if the payment was successful. False if the event was cancelled</p>
*/
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 <p>The event to check and possibly cancel</p>
*/
@EventHandler @EventHandler
public void onBlockPhysics(BlockPhysicsEvent event) { public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock(); Block block = event.getBlock();
@ -112,27 +149,44 @@ public class BlockEventListener implements Listener {
// Handle keeping portal material and buttons around // Handle keeping portal material and buttons around
if (block.getType() == Material.NETHER_PORTAL) { if (block.getType() == Material.NETHER_PORTAL) {
portal = Portal.getByEntrance(block); portal = PortalHandler.getByEntrance(block);
} else if (MaterialHelper.isButtonCompatible(block.getType())) { } 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 <p>The event to check and possibly cancel</p>
*/
@EventHandler @EventHandler
public void onBlockFromTo(BlockFromToEvent event) { public void onBlockFromTo(BlockFromToEvent event) {
Portal portal = Portal.getByEntrance(event.getBlock()); Portal portal = PortalHandler.getByEntrance(event.getBlock());
if (portal != null) { if (portal != null) {
event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); event.setCancelled((event.getBlock().getY() == event.getToBlock().getY()));
} }
} }
/**
* Cancels any piston extend events if the target block is part of a portal
*
* @param event <p>The event to check and possibly cancel</p>
*/
@EventHandler @EventHandler
public void onPistonExtend(BlockPistonExtendEvent event) { public void onPistonExtend(BlockPistonExtendEvent event) {
cancelPistonEvent(event, event.getBlocks()); cancelPistonEvent(event, event.getBlocks());
} }
/**
* Cancels any piston retract events if the target block is part of a portal
*
* @param event <p>The event to check and possibly cancel</p>
*/
@EventHandler @EventHandler
public void onPistonRetract(BlockPistonRetractEvent event) { public void onPistonRetract(BlockPistonRetractEvent event) {
if (!event.isSticky()) { if (!event.isSticky()) {
@ -143,16 +197,18 @@ public class BlockEventListener implements Listener {
/** /**
* Cancels a piston event if it would destroy a portal * Cancels a piston event if it would destroy a portal
* @param event <p>The event to cancel</p> *
* @param event <p>The event to cancel</p>
* @param blocks <p>The blocks included in the event</p> * @param blocks <p>The blocks included in the event</p>
*/ */
private void cancelPistonEvent(BlockPistonEvent event, List<Block> blocks) { private void cancelPistonEvent(BlockPistonEvent event, List<Block> blocks) {
for (Block block : blocks) { for (Block block : blocks) {
Portal portal = Portal.getByBlock(block); Portal portal = PortalHandler.getByBlock(block);
if (portal != null) { if (portal != null) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
} }
} }

View File

@ -1,9 +1,11 @@
package net.knarcraft.stargate.listener; package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.PortalHandler;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener; import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
@ -19,7 +21,7 @@ import java.io.IOException;
public class BungeeCordListener implements PluginMessageListener { public class BungeeCordListener implements PluginMessageListener {
@Override @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")) { if (!Stargate.enableBungee || !channel.equals("BungeeCord")) {
return; return;
} }
@ -39,7 +41,7 @@ public class BungeeCordListener implements PluginMessageListener {
if (player == null) { if (player == null) {
Stargate.bungeeQueue.put(playerName.toLowerCase(), destination); Stargate.bungeeQueue.put(playerName.toLowerCase(), destination);
} else { } 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 // Specified an invalid gate. For now we'll just let them connect at their current location
if (destinationPortal == null) { if (destinationPortal == null) {
Stargate.log.info(Stargate.getString("prefix") + "Bungee gate " + destination + " does not exist"); Stargate.log.info(Stargate.getString("prefix") + "Bungee gate " + destination + " does not exist");

View File

@ -1,25 +1,39 @@
package net.knarcraft.stargate.listener; package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.PortalHandler;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
/**
* This listener listens for any relevant events on portal entities
*/
@SuppressWarnings("unused")
public class EntityEventListener implements Listener { public class EntityEventListener implements Listener {
/**
* This method catches any explosion events
*
* <p>If destroyed by explosions is enabled, any portals destroyed by the explosion will be unregistered. If not,
* the explosion will be cancelled.</p>
*
* @param event <p>The triggered explosion event</p>
*/
@EventHandler @EventHandler
public void onEntityExplode(EntityExplodeEvent event) { public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
for (Block b : event.blockList()) { for (Block block : event.blockList()) {
Portal portal = Portal.getByBlock(b); Portal portal = PortalHandler.getByBlock(block);
if (portal == null) { if (portal == null) {
continue; continue;
} }
if (Stargate.destroyedByExplosion()) { if (Stargate.destroyedByExplosion()) {
portal.unregister(true); PortalHandler.unregister(portal, true);
} else { } else {
event.setCancelled(true); event.setCancelled(true);
break; break;

View File

@ -1,6 +1,7 @@
package net.knarcraft.stargate.listener; 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.utility.MaterialHelper;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
@ -39,7 +40,7 @@ public class PlayerEventsListener implements Listener {
return; return;
} }
Portal portal = Portal.getBungeeGate(destination); Portal portal = PortalHandler.getBungeeGate(destination);
if (portal == null) { if (portal == null) {
Stargate.debug("PlayerJoin", "Error fetching destination portal: " + destination); Stargate.debug("PlayerJoin", "Error fetching destination portal: " + destination);
return; return;
@ -54,7 +55,7 @@ public class PlayerEventsListener implements Listener {
if (!event.isCancelled() if (!event.isCancelled()
&& (cause == PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && (cause == PlayerTeleportEvent.TeleportCause.NETHER_PORTAL
|| cause == PlayerTeleportEvent.TeleportCause.END_GATEWAY && World.Environment.THE_END == event.getFrom().getWorld().getEnvironment()) || 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); event.setCancelled(true);
} }
} }
@ -69,29 +70,29 @@ public class PlayerEventsListener implements Listener {
} }
Player player = event.getPlayer(); Player player = event.getPlayer();
Portal portal = Portal.getByEntrance(event.getTo()); Portal entracePortal = PortalHandler.getByEntrance(event.getTo());
// No portal or not open // No portal or not open
if (portal == null || !portal.isOpen()) return; if (entracePortal == null || !entracePortal.isOpen()) return;
// Not open for this player // Not open for this player
if (!portal.isOpenFor(player)) { if (!entracePortal.isOpenFor(player)) {
Stargate.sendMessage(player, Stargate.getString("denyMsg")); Stargate.sendMessage(player, Stargate.getString("denyMsg"));
portal.teleport(player, portal, event); entracePortal.teleport(player, entracePortal, event);
return; return;
} }
Portal destination = portal.getDestination(player); Portal destination = entracePortal.getDestination(player);
if (!portal.isBungee() && destination == null) return; if (!entracePortal.isBungee() && destination == null) return;
boolean deny = false; boolean deny = false;
// Check if player has access to this server for Bungee gates // Check if player has access to this server for Bungee gates
if (portal.isBungee()) { if (entracePortal.isBungee()) {
if (!Stargate.canAccessServer(player, portal.getNetwork())) { if (!Stargate.canAccessServer(player, entracePortal.getNetwork())) {
deny = true; deny = true;
} }
} else { } else {
// Check if player has access to this network // Check if player has access to this network
if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { if (!Stargate.canAccessNetwork(player, entracePortal.getNetwork())) {
deny = true; 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")); Stargate.sendMessage(player, Stargate.getString("denyMsg"));
portal.teleport(player, portal, event); entracePortal.teleport(player, entracePortal, event);
portal.close(false); entracePortal.close(false);
return; return;
} }
int cost = Stargate.getUseCost(player, portal, destination); int cost = Stargate.getUseCost(player, entracePortal, destination);
if (cost > 0) { if (cost > 0) {
boolean success; if (!EconomyHelper.payTeleportFee(entracePortal, player, cost)) {
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);
return; 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); Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false);
// BungeeCord Support // BungeeCord Support
if (portal.isBungee()) { if (entracePortal.isBungee()) {
if (!Stargate.enableBungee) { if (!Stargate.enableBungee) {
player.sendMessage(Stargate.getString("bungeeDisabled")); player.sendMessage(Stargate.getString("bungeeDisabled"));
portal.close(false); entracePortal.close(false);
return; return;
} }
// Teleport the player back to this gate, for sanity's sake // 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 // Send the SGBungee packet first, it will be queued by BC if required
try { try {
// Build the message, format is <player>#@#<destination> // Build the message, format is <player>#@#<destination>
String msg = event.getPlayer().getName() + "#@#" + portal.getDestinationName(); String msg = event.getPlayer().getName() + "#@#" + entracePortal.getDestinationName();
// Build the message data, sent over the SGBungee bungeecord channel // Build the message data, sent over the SGBungee bungeecord channel
ByteArrayOutputStream bao = new ByteArrayOutputStream(); ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream msgData = new DataOutputStream(bao); DataOutputStream msgData = new DataOutputStream(bao);
msgData.writeUTF("Forward"); msgData.writeUTF("Forward");
msgData.writeUTF(portal.getNetwork()); // Server msgData.writeUTF(entracePortal.getNetwork()); // Server
msgData.writeUTF("SGBungee"); // Channel msgData.writeUTF("SGBungee"); // Channel
msgData.writeShort(msg.length()); // Data Length msgData.writeShort(msg.length()); // Data Length
msgData.writeBytes(msg); // Data msgData.writeBytes(msg); // Data
@ -177,7 +153,7 @@ public class PlayerEventsListener implements Listener {
ByteArrayOutputStream bao = new ByteArrayOutputStream(); ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream msgData = new DataOutputStream(bao); DataOutputStream msgData = new DataOutputStream(bao);
msgData.writeUTF("Connect"); msgData.writeUTF("Connect");
msgData.writeUTF(portal.getNetwork()); msgData.writeUTF(entracePortal.getNetwork());
player.sendPluginMessage(Stargate.stargate, "BungeeCord", bao.toByteArray()); player.sendPluginMessage(Stargate.stargate, "BungeeCord", bao.toByteArray());
bao.reset(); bao.reset();
@ -188,12 +164,12 @@ public class PlayerEventsListener implements Listener {
} }
// Close portal if required (Should never be) // Close portal if required (Should never be)
portal.close(false); entracePortal.close(false);
return; return;
} }
destination.teleport(player, portal, event); destination.teleport(player, entracePortal, event);
portal.close(false); entracePortal.close(false);
} }
@EventHandler @EventHandler
@ -208,7 +184,7 @@ public class PlayerEventsListener implements Listener {
// Right click // Right click
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (block.getBlockData() instanceof WallSign) { if (block.getBlockData() instanceof WallSign) {
Portal portal = Portal.getByBlock(block); Portal portal = PortalHandler.getByBlock(block);
if (portal == null) { if (portal == null) {
return; return;
} }
@ -246,7 +222,7 @@ public class PlayerEventsListener implements Listener {
eventTime = System.currentTimeMillis(); eventTime = System.currentTimeMillis();
} }
Portal portal = Portal.getByBlock(block); Portal portal = PortalHandler.getByBlock(block);
if (portal == null) { if (portal == null) {
return; return;
} }
@ -277,8 +253,10 @@ public class PlayerEventsListener implements Listener {
if (event.getAction() == Action.LEFT_CLICK_BLOCK) { if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
// Check if we're scrolling a sign // Check if we're scrolling a sign
if (block.getBlockData() instanceof WallSign) { if (block.getBlockData() instanceof WallSign) {
Portal portal = Portal.getByBlock(block); Portal portal = PortalHandler.getByBlock(block);
if (portal == null) return; if (portal == null) {
return;
}
event.setUseInteractedBlock(Event.Result.DENY); event.setUseInteractedBlock(Event.Result.DENY);
// Only cancel event in creative mode // Only cancel event in creative mode

View File

@ -1,7 +1,9 @@
package net.knarcraft.stargate.listener; package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.PortalHandler;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.utility.EconomyHelper;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle; import org.bukkit.entity.Vehicle;
@ -11,90 +13,86 @@ import org.bukkit.event.vehicle.VehicleMoveEvent;
import java.util.List; import java.util.List;
@SuppressWarnings("unused")
public class VehicleEventListener implements Listener { public class VehicleEventListener implements Listener {
/**
* Check for a vehicle moving through a portal
* @param event <p>The triggered move event</p>
*/
@EventHandler @EventHandler
public void onVehicleMove(VehicleMoveEvent event) { public void onVehicleMove(VehicleMoveEvent event) {
if (!Stargate.handleVehicles) return; if (!Stargate.handleVehicles) {
return;
}
List<Entity> passengers = event.getVehicle().getPassengers(); List<Entity> passengers = event.getVehicle().getPassengers();
Vehicle vehicle = event.getVehicle(); Vehicle vehicle = event.getVehicle();
Portal portal = Portal.getByEntrance(event.getTo()); Portal entrancePortal = PortalHandler.getByEntrance(event.getTo());
if (portal == null || !portal.isOpen()) return;
// We don't support vehicles in Bungee portals //Return if the portal cannot be teleported through
if (portal.isBungee()) return; if (entrancePortal == null || !entrancePortal.isOpen() || entrancePortal.isBungee()) {
return;
}
if (!passengers.isEmpty() && passengers.get(0) instanceof Player) { if (!passengers.isEmpty() && passengers.get(0) instanceof Player) {
/* Stargate.log.info(Stargate.getString("prefox") + "Found passenger minecart");
Player player = (Player) passengers.get(0); teleportPlayerAndVehicle(entrancePortal, vehicle, passengers);
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);
*/
} else { } else {
Portal dest = portal.getDestination(); Stargate.log.info(Stargate.getString("prefox") + "Found empty minecart");
if (dest == null) return; Portal destinationPortal = entrancePortal.getDestination();
dest.teleport(vehicle); 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 <p>The portal the minecart entered</p>
* @param vehicle <p>The vehicle to teleport</p>
* @param passengers <p>Any entities sitting in the minecart</p>
*/
private void teleportPlayerAndVehicle(Portal entrancePortal, Vehicle vehicle, List<Entity> 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);
}
} }

View File

@ -1,6 +1,7 @@
package net.knarcraft.stargate.listener; package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Portal; import net.knarcraft.stargate.Portal;
import net.knarcraft.stargate.PortalHandler;
import net.knarcraft.stargate.Stargate; import net.knarcraft.stargate.Stargate;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -12,7 +13,7 @@ public class WorldEventListener implements Listener {
@EventHandler @EventHandler
public void onWorldLoad(WorldLoadEvent event) { public void onWorldLoad(WorldLoadEvent event) {
if (!Stargate.managedWorlds.contains(event.getWorld().getName()) if (!Stargate.managedWorlds.contains(event.getWorld().getName())
&& Portal.loadAllGates(event.getWorld())) { && PortalHandler.loadAllGates(event.getWorld())) {
Stargate.managedWorlds.add(event.getWorld().getName()); Stargate.managedWorlds.add(event.getWorld().getName());
} }
} }
@ -24,10 +25,10 @@ public class WorldEventListener implements Listener {
World w = event.getWorld(); World w = event.getWorld();
if (Stargate.managedWorlds.contains(w.getName())) { if (Stargate.managedWorlds.contains(w.getName())) {
Stargate.managedWorlds.remove(w.getName()); Stargate.managedWorlds.remove(w.getName());
Portal.clearGates(); PortalHandler.clearGates();
for (World world : Stargate.server.getWorlds()) { for (World world : Stargate.server.getWorlds()) {
if (Stargate.managedWorlds.contains(world.getName())) { if (Stargate.managedWorlds.contains(world.getName())) {
Portal.loadAllGates(world); PortalHandler.loadAllGates(world);
} }
} }
} }

View File

@ -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 <p>The portal the player is entering</p>
* @param player <p>The player wishing to teleport</p>
* @param cost <p>The cost of teleportation</p>
* @return <p>True if payment was successful</p>
*/
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 <p>The name of the used portal</p>
* @param portalOwner <p>The owner of the portal</p>
* @param earnings <p>The amount the owner earned</p>
*/
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 <p>The name of the portal interacted with</p>
* @param player <p>The interacting player</p>
* @param cost <p>The cost of the interaction</p>
*/
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 <p>The name of the portal interacted with</p>
* @param player <p>The interacting player</p>
* @param cost <p>The cost of the interaction</p>
*/
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 <p>The name of the broken portal</p>
* @param player <p>The player breaking the portal</p>
* @param cost <p>The amount the user has to pay for destroying the portal. (expects a negative value)</p>
*/
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 <p>The message to replace variables in</p>
* @param portalName <p>The name of the relevant portal</p>
* @param cost <p>The cost for a given interaction</p>
* @return <p>The same string with cost and portal variables replaced</p>
*/
private static String replaceVars(String message, String portalName, int cost) {
return Stargate.replaceVars(message, new String[]{"%cost%", "%portal%"},
new String[]{EconomyHandler.format(cost), portalName});
}
}