Reduces some code complexity

This commit is contained in:
2024-02-20 20:48:29 +01:00
parent cde20e35d5
commit 9abf60bb31
8 changed files with 190 additions and 109 deletions

View File

@@ -467,7 +467,7 @@ public final class StargateConfig {
*/ */
@NotNull @NotNull
private String replacePluginFolderPath(@NotNull String input) { private String replacePluginFolderPath(@NotNull String input) {
Pattern pattern = Pattern.compile("(?i)^plugins[\\\\\\/]Stargate"); Pattern pattern = Pattern.compile("(?i)^plugins[\\\\/]Stargate");
Matcher matcher = pattern.matcher(input); Matcher matcher = pattern.matcher(input);
if (matcher.find()) { if (matcher.find()) {
return dataFolderPath + matcher.replaceAll(""); return dataFolderPath + matcher.replaceAll("");

View File

@@ -79,6 +79,8 @@ public class PortalCreator {
String network = PortalHandler.filterName(event.getLine(2)); String network = PortalHandler.filterName(event.getLine(2));
String options = PortalHandler.filterName(event.getLine(3)).toLowerCase(); String options = PortalHandler.filterName(event.getLine(3)).toLowerCase();
PortalStrings portalStrings = new PortalStrings(portalName, network, destinationName);
//Get portal options available to the player creating the portal //Get portal options available to the player creating the portal
Map<PortalOption, Boolean> portalOptions = PortalHandler.getPortalOptions(player, destinationName, options); Map<PortalOption, Boolean> portalOptions = PortalHandler.getPortalOptions(player, destinationName, options);
@@ -94,6 +96,12 @@ public class PortalCreator {
Stargate.debug("createPortal", "Finished getting all portal info"); Stargate.debug("createPortal", "Finished getting all portal info");
return createPortal(portalStrings, portalOptions, yaw, portalLocation);
}
@Nullable
private Portal createPortal(@NotNull PortalStrings portalStrings, @NotNull Map<PortalOption, Boolean> portalOptions,
float yaw, @NotNull PortalLocation portalLocation) {
//Try and find a gate matching the new portal //Try and find a gate matching the new portal
Gate gate = PortalHandler.findMatchingGate(portalLocation, player.getWorld()); Gate gate = PortalHandler.findMatchingGate(portalLocation, player.getWorld());
if ((gate == null) || (portalLocation.getButtonVector() == null)) { if ((gate == null) || (portalLocation.getButtonVector() == null)) {
@@ -102,7 +110,8 @@ public class PortalCreator {
} }
//If the portal is a bungee portal and invalid, abort here //If the portal is a bungee portal and invalid, abort here
if (!PortalHandler.isValidBungeePortal(portalOptions, player, destinationName, network)) { if (!PortalHandler.isValidBungeePortal(portalOptions, player, portalStrings.destination(),
portalStrings.network())) {
Stargate.debug("createPortal", "Portal is an invalid bungee portal"); Stargate.debug("createPortal", "Portal is an invalid bungee portal");
return null; return null;
} }
@@ -114,51 +123,27 @@ public class PortalCreator {
} }
Stargate.debug("createPortal", builder.toString()); Stargate.debug("createPortal", builder.toString());
//Use default network if a proper alternative is not set
if (!portalOptions.get(PortalOption.BUNGEE) && (network.length() < 1 || network.length() >
getMaxNameNetworkLength())) {
network = Stargate.getDefaultNetwork();
}
boolean deny = false; boolean deny = false;
String denyMessage = ""; String denyMessage = "";
//Check if the player can create portals on this network. If not, create a personal portal if (!portalOptions.get(PortalOption.BUNGEE)) {
if (!portalOptions.get(PortalOption.BUNGEE) && !PermissionHelper.canCreateNetworkGate(player, network)) { String networkName = getNetworkName(portalStrings);
Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal"); if (networkName == null) {
if (PermissionHelper.canCreatePersonalPortal(player)) {
network = player.getName();
if (network.length() > getMaxNameNetworkLength()) {
network = network.substring(0, getMaxNameNetworkLength());
}
Stargate.debug("createPortal", "Creating personal portal");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_PERSONAL));
} else {
Stargate.debug("createPortal", "Player does not have access to network");
deny = true; deny = true;
denyMessage = Stargate.getString(Message.CREATION_NETWORK_DENIED); denyMessage = Stargate.getString(Message.CREATION_NETWORK_DENIED);
} else {
portalStrings = new PortalStrings(portalStrings.name(), networkName, portalStrings.destination());
} }
} }
//Check if the player can create this gate layout // Check whether the player can create a portal with the specified gate in the specified world
String gateName = gate.getFilename(); if (!deny) {
gateName = gateName.substring(0, gateName.indexOf('.')); denyMessage = canCreatePortal(portalOptions.get(PortalOption.BUNGEE), portalStrings.network(), gate,
if (!deny && !PermissionHelper.canCreatePortal(player, gateName)) { portalStrings.destination());
Stargate.debug("createPortal", "Player does not have access to gate layout"); if (denyMessage != null) {
deny = true; deny = true;
denyMessage = Stargate.getString(Message.CREATION_GATE_DENIED); } else {
} denyMessage = "";
//Check if the user can create portals to this world.
if (!portalOptions.get(PortalOption.BUNGEE) && !deny && destinationName.length() > 0) {
Portal portal = PortalHandler.getByName(destinationName, network);
if (portal != null && portal.getWorld() != null) {
String world = portal.getWorld().getName();
if (PermissionHelper.cannotAccessWorld(player, world)) {
Stargate.debug("canCreateNetworkGate", "Player does not have access to destination world");
deny = true;
denyMessage = Stargate.getString(Message.CREATION_WORLD_DENIED);
}
} }
} }
@@ -168,11 +153,71 @@ public class PortalCreator {
} }
PortalOwner owner = new PortalOwner(player); PortalOwner owner = new PortalOwner(player);
PortalStrings portalStrings = new PortalStrings(portalName, network, destinationName);
this.portal = new Portal(portalLocation, null, portalStrings, gate, owner, portalOptions); this.portal = new Portal(portalLocation, null, portalStrings, gate, owner, portalOptions);
return validatePortal(denyMessage, event.getLines(), deny); return validatePortal(denyMessage, event.getLines(), deny);
} }
/**
* Gets the network name to use for the new portal
*
* @param portalStrings <p>The string values for the new portal</p>
* @return <p>The new network name, or null if the player does not have the necessary permission for any networks</p>
*/
@Nullable
private String getNetworkName(@NotNull PortalStrings portalStrings) {
String network = portalStrings.network();
//Use default network if a proper alternative is not set
if (portalStrings.network().length() < 1 || portalStrings.network().length() > getMaxNameNetworkLength()) {
network = Stargate.getDefaultNetwork();
}
//Check if the player can create portals on this network. If not, create a personal portal
if (!PermissionHelper.canCreateNetworkGate(player, network)) {
Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal");
if (PermissionHelper.canCreatePersonalPortal(player)) {
network = player.getName();
if (network.length() > getMaxNameNetworkLength()) {
network = network.substring(0, getMaxNameNetworkLength());
}
Stargate.debug("createPortal", "Creating personal portal");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_PERSONAL));
return network;
} else {
Stargate.debug("createPortal", "Player does not have access to network");
return null;
}
}
return network;
}
@Nullable
private String canCreatePortal(boolean bungee, @NotNull String network,
@NotNull Gate gate, @NotNull String destinationName) {
//Check if the player can create this gate layout
String gateName = gate.getFilename();
gateName = gateName.substring(0, gateName.indexOf('.'));
if (!PermissionHelper.canCreatePortal(player, gateName)) {
Stargate.debug("createPortal", "Player does not have access to gate layout");
return Stargate.getString(Message.CREATION_GATE_DENIED);
}
//Check if the user can create portals to this world.
if (!bungee && destinationName.length() > 0) {
Portal portal = PortalHandler.getByName(destinationName, network);
if (portal != null && portal.getWorld() != null) {
String world = portal.getWorld().getName();
if (PermissionHelper.cannotAccessWorld(player, world)) {
Stargate.debug("canCreateNetworkGate", "Player does not have access to destination world");
return Stargate.getString(Message.CREATION_WORLD_DENIED);
}
}
}
return null;
}
/** /**
* Validates the newly created portal assigned to this portal validator * Validates the newly created portal assigned to this portal validator
* *

View File

@@ -80,40 +80,54 @@ public class PortalHandler {
if (portal == null) { if (portal == null) {
continue; continue;
} }
//Check if destination is a random portal
if (portal.getOptions().isRandom()) { if (isDestinationAvailable(entrancePortal, portal, player)) {
continue;
}
//Check if destination is always open (Don't show if so)
if (portal.getOptions().isAlwaysOn() && !portal.getOptions().isShown()) {
continue;
}
//Check if destination is this portal
if (destination.equals(entrancePortal.getCleanName())) {
continue;
}
//Check if destination is a fixed portal not pointing to this portal
if (portal.getOptions().isFixed() &&
!Portal.cleanString(portal.getDestinationName()).equals(entrancePortal.getCleanName())) {
continue;
}
//Allow random use by non-players (Minecarts)
if (player == null) {
destinations.add(portal.getName());
continue;
}
//Check if this player can access the destination world
if (portal.getWorld() != null && PermissionHelper.cannotAccessWorld(player, portal.getWorld().getName())) {
continue;
}
//The portal is visible to the player
if (PermissionHelper.canSeePortal(player, portal)) {
destinations.add(portal.getName()); destinations.add(portal.getName());
} }
} }
return destinations; return destinations;
} }
/**
* Checks whether the given destination is available to the given player
*
* @param entrancePortal <p>The portal the player has activated</p>
* @param destinationPortal <p>The destination portal to check if is valid</p>
* @param player <p>The player trying to attempt the destination</p>
* @return <p>True if the destination is available</p>
*/
private static boolean isDestinationAvailable(@NotNull Portal entrancePortal, @NotNull Portal destinationPortal,
@Nullable Player player) {
//Check if destination is a random portal
if (destinationPortal.getOptions().isRandom()) {
return false;
}
//Check if destination is always open (Don't show if so)
if (destinationPortal.getOptions().isAlwaysOn() && !destinationPortal.getOptions().isShown()) {
return false;
}
//Check if destination is this portal
if (destinationPortal.equals(entrancePortal)) {
return false;
}
//Check if destination is a fixed portal not pointing to this portal
if (destinationPortal.getOptions().isFixed() &&
!Portal.cleanString(destinationPortal.getDestinationName()).equals(entrancePortal.getCleanName())) {
return false;
}
//Allow random use by non-players (Minecarts)
if (player == null) {
return true;
}
//Check if this player can access the destination world
if (destinationPortal.getWorld() != null && PermissionHelper.cannotAccessWorld(player,
destinationPortal.getWorld().getName())) {
return false;
}
//The portal is visible to the player
return PermissionHelper.canSeePortal(player, destinationPortal);
}
/** /**
* Registers a portal * Registers a portal
* *

View File

@@ -178,30 +178,7 @@ public class PortalRegistry {
String portalName = portal.getCleanName(); String portalName = portal.getCleanName();
String networkName = portal.getCleanNetwork(); String networkName = portal.getCleanNetwork();
//Remove portal from lookup blocks clearLookupMaps(portal, removeAll);
for (BlockLocation block : portal.getStructure().getFrame()) {
lookupBlocks.remove(block);
}
//Remove registered info about the lookup controls and blocks
lookupBlocks.remove(portal.getSignLocation());
lookupControls.remove(portal.getSignLocation());
BlockLocation button = portal.getStructure().getButton();
if (button != null) {
lookupBlocks.remove(button);
lookupControls.remove(button);
}
//Remove entrances
for (BlockLocation entrance : portal.getStructure().getEntrances()) {
lookupEntrances.remove(entrance);
}
//Remove the portal from the list of all portals
if (removeAll) {
allPortals.remove(portal);
}
if (portal.getOptions().isBungee()) { if (portal.getOptions().isBungee()) {
//Remove the bungee listing //Remove the bungee listing
@@ -239,6 +216,39 @@ public class PortalRegistry {
DynmapManager.removePortalMarker(portal); DynmapManager.removePortalMarker(portal);
} }
/**
* Clears the given portal's presence from lookup maps
*
* @param portal <p>The portal to clear</p>
* @param removeAll <p>Whether to remove the portal from the list of all portals</p>
*/
private static void clearLookupMaps(@NotNull Portal portal, boolean removeAll) {
//Remove portal from lookup blocks
for (BlockLocation block : portal.getStructure().getFrame()) {
lookupBlocks.remove(block);
}
//Remove registered info about the lookup controls and blocks
lookupBlocks.remove(portal.getSignLocation());
lookupControls.remove(portal.getSignLocation());
BlockLocation button = portal.getStructure().getButton();
if (button != null) {
lookupBlocks.remove(button);
lookupControls.remove(button);
}
//Remove entrances
for (BlockLocation entrance : portal.getStructure().getEntrances()) {
lookupEntrances.remove(entrance);
}
//Remove the portal from the list of all portals
if (removeAll) {
allPortals.remove(portal);
}
}
/** /**
* Registers a portal * Registers a portal
* *

View File

@@ -49,27 +49,23 @@ public class Gate {
* @param portalOpenMaterials <p>The material to set the opening to when the portal is open</p> * @param portalOpenMaterials <p>The material to set the opening to when the portal is open</p>
* @param portalClosedMaterials <p>The material to set the opening to when the portal is closed</p> * @param portalClosedMaterials <p>The material to set the opening to when the portal is closed</p>
* @param portalButtonMaterials <p>The material to use for the portal button</p> * @param portalButtonMaterials <p>The material to use for the portal button</p>
* @param useCost <p>The cost of using a portal with this gate layout (-1 to disable)</p> * @param gateCosts <p>The costs and other economy information for the gate</p>
* @param createCost <p>The cost of creating a portal with this gate layout (-1 to disable)</p>
* @param destroyCost <p>The cost of destroying a portal with this gate layout (-1 to disable)</p>
* @param toOwner <p>Whether any payment should go to the owner of the gate, as opposed to just disappearing</p>
*/ */
public Gate(@NotNull String filename, @NotNull GateLayout layout, public Gate(@NotNull String filename, @NotNull GateLayout layout,
@NotNull Map<Character, List<MaterialSpecifier>> characterMaterialsMap, @NotNull Map<Character, List<MaterialSpecifier>> characterMaterialsMap,
@NotNull List<MaterialSpecifier> portalOpenMaterials, @NotNull List<MaterialSpecifier> portalOpenMaterials,
@NotNull List<MaterialSpecifier> portalClosedMaterials, @NotNull List<MaterialSpecifier> portalClosedMaterials,
@NotNull List<MaterialSpecifier> portalButtonMaterials, int useCost, int createCost, int destroyCost, @NotNull List<MaterialSpecifier> portalButtonMaterials, @NotNull GateCosts gateCosts) {
boolean toOwner) {
this.filename = filename; this.filename = filename;
this.layout = layout; this.layout = layout;
this.characterMaterialMap = characterMaterialsMap; this.characterMaterialMap = characterMaterialsMap;
this.portalOpenMaterials = portalOpenMaterials; this.portalOpenMaterials = portalOpenMaterials;
this.portalClosedMaterials = portalClosedMaterials; this.portalClosedMaterials = portalClosedMaterials;
this.portalButtonMaterials = portalButtonMaterials; this.portalButtonMaterials = portalButtonMaterials;
this.useCost = useCost; this.useCost = gateCosts.useCost();
this.createCost = createCost; this.createCost = gateCosts.createCost();
this.destroyCost = destroyCost; this.destroyCost = gateCosts.destroyCost();
this.toOwner = toOwner; this.toOwner = gateCosts.toOwner();
} }
/** /**
@@ -226,7 +222,6 @@ public class Gate {
* @return <p>True if all border blocks of the gate match the layout</p> * @return <p>True if all border blocks of the gate match the layout</p>
*/ */
private boolean verifyGateBorderMatches(@NotNull BlockLocation topLeft, double yaw) { private boolean verifyGateBorderMatches(@NotNull BlockLocation topLeft, double yaw) {
Map<Character, List<MaterialSpecifier>> characterMaterialMap = new HashMap<>(this.characterMaterialMap);
for (RelativeBlockVector borderVector : layout.getBorder()) { for (RelativeBlockVector borderVector : layout.getBorder()) {
int rowIndex = borderVector.right(); int rowIndex = borderVector.right();
int lineIndex = borderVector.down(); int lineIndex = borderVector.down();
@@ -246,7 +241,7 @@ public class Gate {
* recognized, but still allowed in previous checks, verify the gate as long as all such instances of * recognized, but still allowed in previous checks, verify the gate as long as all such instances of
* the character correspond to the same material in the physical gate. All subsequent gates will also * the character correspond to the same material in the physical gate. All subsequent gates will also
* need to match the first verified gate. */ * need to match the first verified gate. */
characterMaterialMap.put(key, List.of(new BukkitMaterialSpecifier(materialAtLocation))); this.characterMaterialMap.put(key, List.of(new BukkitMaterialSpecifier(materialAtLocation)));
Stargate.debug("Gate::Matches", String.format("Missing layout material in %s. Using %s from the" + Stargate.debug("Gate::Matches", String.format("Missing layout material in %s. Using %s from the" +
" physical portal.", getFilename(), materialAtLocation)); " physical portal.", getFilename(), materialAtLocation));
} }

View File

@@ -0,0 +1,12 @@
package net.knarcraft.stargate.portal.property.gate;
/**
* The costs assigned to a gate
*
* @param useCost <p>The cost for using (entering) the gate</p>
* @param createCost <p>The cost for creating a portal with the gate type</p>
* @param destroyCost <p>The cost for destroying a portal with the gate type</p>
* @param toOwner <p>Whether the use cost is paid to the gate's owner</p>
*/
public record GateCosts(int useCost, int createCost, int destroyCost, boolean toOwner) {
}

View File

@@ -115,11 +115,15 @@ public class GateHandler {
@Nullable @Nullable
private static Gate loadGate(@NotNull File file) { private static Gate loadGate(@NotNull File file) {
try (Scanner scanner = new Scanner(file)) { try (Scanner scanner = new Scanner(file)) {
return loadGate(file.getName(), file.getParent(), scanner); Gate gate = loadGate(file.getName(), file.getParent(), scanner);
if (gate != null) {
return gate;
}
} catch (Exception exception) { } catch (Exception exception) {
Stargate.logSevere(String.format("Could not load Gate %s - %s", file.getName(), exception.getMessage())); Stargate.logSevere(String.format("Could not load Gate %s - %s", file.getName(), exception.getMessage()));
return null;
} }
return null;
} }
/** /**
@@ -184,10 +188,11 @@ public class GateHandler {
int destroyCost = readGateConfig(config, fileName, "destroycost"); int destroyCost = readGateConfig(config, fileName, "destroycost");
boolean toOwner = (config.containsKey("toowner") ? Boolean.parseBoolean(config.get("toowner")) : boolean toOwner = (config.containsKey("toowner") ? Boolean.parseBoolean(config.get("toowner")) :
Stargate.getEconomyConfig().sendPaymentToOwner()); Stargate.getEconomyConfig().sendPaymentToOwner());
GateCosts gateCosts = new GateCosts(useCost, createCost, destroyCost, toOwner);
//Create the new gate //Create the new gate
Gate gate = new Gate(fileName, new GateLayout(layout), characterMaterialMap, portalOpenBlock, Gate gate = new Gate(fileName, new GateLayout(layout), characterMaterialMap, portalOpenBlock, portalClosedBlock,
portalClosedBlock, portalButton, useCost, createCost, destroyCost, toOwner); portalButton, gateCosts);
if (!validateGate(gate, fileName)) { if (!validateGate(gate, fileName)) {
return null; return null;

View File

@@ -57,7 +57,7 @@ public abstract class Teleporter {
* @param portal <p>The portal which is the target of the teleportation</p> * @param portal <p>The portal which is the target of the teleportation</p>
* @param teleportedEntity <p>The entity teleported by this teleporter</p> * @param teleportedEntity <p>The entity teleported by this teleporter</p>
*/ */
public Teleporter(@NotNull Portal portal, @NotNull Entity teleportedEntity) { protected Teleporter(@NotNull Portal portal, @NotNull Entity teleportedEntity) {
this.portal = portal; this.portal = portal;
this.scheduler = Stargate.getInstance().getServer().getScheduler(); this.scheduler = Stargate.getInstance().getServer().getScheduler();
this.teleportedEntity = teleportedEntity; this.teleportedEntity = teleportedEntity;