Reduced the complexity of these commands.

By splitting up the methods, it makes it easier to understand and spot
bugs.
This commit is contained in:
Tastybento 2018-02-11 15:22:03 -08:00
parent 9f43f1e6fa
commit 54dd9e87d4
10 changed files with 238 additions and 315 deletions

View File

@ -11,7 +11,6 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginIdentifiableCommand; import org.bukkit.command.PluginIdentifiableCommand;
@ -31,7 +30,6 @@ import us.tastybento.bskyblock.util.Util;
*/ */
public abstract class CompositeCommand extends Command implements PluginIdentifiableCommand, BSBCommand { public abstract class CompositeCommand extends Command implements PluginIdentifiableCommand, BSBCommand {
private static final boolean DEBUG = false;
/** /**
* True if the command is for the player only (not for the console) * True if the command is for the player only (not for the console)
*/ */
@ -109,9 +107,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
if (!getSubCommand("help").isPresent() && !label.equals("help")) { if (!getSubCommand("help").isPresent() && !label.equals("help")) {
new DefaultHelpCommand(this); new DefaultHelpCommand(this);
} }
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: registering command " + label);
}
} }
/** /**
@ -121,9 +116,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/ */
public CompositeCommand(String label, String... aliases) { public CompositeCommand(String label, String... aliases) {
super(label); super(label);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: top level command registering..." + label);
}
setAliases(new ArrayList<>(Arrays.asList(aliases))); setAliases(new ArrayList<>(Arrays.asList(aliases)));
parent = null; parent = null;
setUsage(""); setUsage("");
@ -147,15 +139,9 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/ */
@Override @Override
public boolean execute(CommandSender sender, String label, String[] args) { public boolean execute(CommandSender sender, String label, String[] args) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: executing command " + label);
}
// Get the User instance for this sender // Get the User instance for this sender
User user = User.getInstance(sender); User user = User.getInstance(sender);
CompositeCommand cmd = getCommandFromArgs(args); CompositeCommand cmd = getCommandFromArgs(args);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: Command = " + cmd.getLabel() + " onlyplayer = " + cmd.isOnlyPlayer() + " permission = " + cmd.getPermission());
}
// Check for console and permissions // Check for console and permissions
if (cmd.onlyPlayer && !(sender instanceof Player)) { if (cmd.onlyPlayer && !(sender instanceof Player)) {
user.sendMessage("general.errors.use-in-game"); user.sendMessage("general.errors.use-in-game");
@ -285,22 +271,13 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
* @return CompositeCommand or null if none found * @return CompositeCommand or null if none found
*/ */
public Optional<CompositeCommand> getSubCommand(String label) { public Optional<CompositeCommand> getSubCommand(String label) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: label = " + label);
}
for (Map.Entry<String, CompositeCommand> entry : subCommands.entrySet()) { for (Map.Entry<String, CompositeCommand> entry : subCommands.entrySet()) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) { if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommands.get(label)); return Optional.of(subCommands.get(label));
} }
} }
// Try aliases // Try aliases
for (Map.Entry<String, CompositeCommand> entry : subCommandAliases.entrySet()) { for (Map.Entry<String, CompositeCommand> entry : subCommandAliases.entrySet()) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: alias " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) { if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommandAliases.get(label)); return Optional.of(subCommandAliases.get(label));
} }
@ -415,20 +392,11 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
List<String> options = new ArrayList<>(); List<String> options = new ArrayList<>();
// Get command object based on args entered so far // Get command object based on args entered so far
CompositeCommand cmd = getCommandFromArgs(args); CompositeCommand cmd = getCommandFromArgs(args);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: subCommand = " + cmd.getLabel() + " onlyplayer = " + cmd.isOnlyPlayer() + " permission = " + cmd.getPermission());
}
// Check for console and permissions // Check for console and permissions
if (cmd.onlyPlayer && !(sender instanceof Player)) { if (cmd.onlyPlayer && !(sender instanceof Player)) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: returning, only for player");
}
return options; return options;
} }
if (!cmd.getPermission().isEmpty() && !sender.hasPermission(cmd.getPermission())) { if (!cmd.getPermission().isEmpty() && !sender.hasPermission(cmd.getPermission())) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: failed perm check");
}
return options; return options;
} }
// Add any tab completion from the subcommand // Add any tab completion from the subcommand
@ -454,14 +422,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
} }
String lastArg = (args.length != 0 ? args[args.length - 1] : ""); String lastArg = (args.length != 0 ? args[args.length - 1] : "");
if (DEBUG) {
String arguments = "";
for (String arg : args) {
arguments += "'" + arg + "' ";
}
Bukkit.getLogger().info("DEBUG: tab complete for " + arguments);
Bukkit.getLogger().info("DEBUG: result = " + Util.tabLimit(options, lastArg));
}
return Util.tabLimit(options, lastArg); return Util.tabLimit(options, lastArg);
} }

View File

@ -14,15 +14,15 @@ import org.apache.commons.lang.math.NumberUtils;
*/ */
public class DefaultHelpCommand extends CompositeCommand { public class DefaultHelpCommand extends CompositeCommand {
// TODO: make this a setting
private static final int MAX_DEPTH = 2; private static final int MAX_DEPTH = 2;
private static final String USAGE_PLACEHOLDER = "[usage]"; private static final String USAGE_PLACEHOLDER = "[usage]";
private static final String PARAMS_PLACEHOLDER = "[parameters]"; private static final String PARAMS_PLACEHOLDER = "[parameters]";
private static final String DESC_PLACEHOLDER = "[description]"; private static final String DESC_PLACEHOLDER = "[description]";
private static final String HELP_SYNTAX_REF = "commands.help.syntax"; private static final String HELP_SYNTAX_REF = "commands.help.syntax";
private static final String HELP = "help";
public DefaultHelpCommand(CompositeCommand parent) { public DefaultHelpCommand(CompositeCommand parent) {
super(parent, "help"); super(parent, HELP);
} }
@Override @Override
@ -51,13 +51,42 @@ public class DefaultHelpCommand extends CompositeCommand {
if (depth == 0) { if (depth == 0) {
user.sendMessage("commands.help.header"); user.sendMessage("commands.help.header");
} }
//if (args.isEmpty()) {
if (depth < MAX_DEPTH) { if (depth < MAX_DEPTH) {
if (!parent.getLabel().equals("help")) { if (!parent.getLabel().equals(HELP)) {
// Get elements // Get elements
String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage()); String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage());
String params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters()); String params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription()); String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription());
if (showPrettyHelp(user, usage, params, desc)) {
// No more to show
return true;
}
}
// Increment the depth and run through any subcommands and get their help too
runSubCommandHelp(user, depth + 1);
}
if (depth == 0) {
user.sendMessage("commands.help.end");
}
return true;
}
private void runSubCommandHelp(User user, int newDepth) {
for (CompositeCommand subCommand : parent.getSubCommands().values()) {
// Ignore the help command
if (!subCommand.getLabel().equals(HELP)) {
// Every command should have help because every command has a default help
Optional<CompositeCommand> sub = subCommand.getSubCommand(HELP);
if (sub.isPresent()) {
sub.get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
}
}
}
private boolean showPrettyHelp(User user, String usage, String params, String desc) {
// Show the help // Show the help
if (user.isPlayer()) { if (user.isPlayer()) {
// Player. Check perms // Player. Check perms
@ -71,26 +100,7 @@ public class DefaultHelpCommand extends CompositeCommand {
// Console. Only show if it is a console command // Console. Only show if it is a console command
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc); user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
} }
} return false;
// Increment the depth
int newDepth = depth + 1;
// Run through any subcommands and get their help
for (CompositeCommand subCommand : parent.getSubCommands().values()) {
// Ignore the help command
if (!subCommand.getLabel().equals("help")) {
// Every command should have help because every command has a default help
Optional<CompositeCommand> sub = subCommand.getSubCommand("help");
if (sub.isPresent()) {
sub.get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
}
}
}
if (depth == 0) {
user.sendMessage("commands.help.end");
}
return true;
} }
} }

View File

@ -38,23 +38,22 @@ public class CustomIslandMultiHomeHelp extends CompositeCommand {
String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage()); String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage());
String params = ""; String params = "";
String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription()); String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription());
showPrettyHelp(user, usage, params, desc);
return true;
}
return false;
}
private void showPrettyHelp(User user, String usage, String params, String desc) {
// Player. Check perms // Player. Check perms
if (user.hasPermission(getPermission())) { if (user.hasPermission(getPermission())) {
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes()); int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (maxHomes > 1) { if (maxHomes > 1) {
params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters()); params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc); }
} else {
// No params
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc); user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
} }
return true;
} else {
return true;
}
}
return false;
} }
} }

View File

@ -6,11 +6,14 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User; import us.tastybento.bskyblock.api.commands.User;
@ -28,9 +31,6 @@ public abstract class AbstractIslandTeamCommand extends CompositeCommand {
protected static Set<UUID> leavingPlayers = new HashSet<>(); protected static Set<UUID> leavingPlayers = new HashSet<>();
protected static Set<UUID> kickingPlayers = new HashSet<>(); protected static Set<UUID> kickingPlayers = new HashSet<>();
// TODO: It would be good if these could be auto-provided
protected User user;
public AbstractIslandTeamCommand(CompositeCommand command, String label, String... aliases) { public AbstractIslandTeamCommand(CompositeCommand command, String label, String... aliases) {
super(command, label,aliases); super(command, label,aliases);
} }
@ -43,4 +43,43 @@ public abstract class AbstractIslandTeamCommand extends CompositeCommand {
protected void setResetWaitTime(final Player player) { protected void setResetWaitTime(final Player player) {
resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + getSettings().getResetWait() * 1000); resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + getSettings().getResetWait() * 1000);
} }
protected int getMaxTeamSize(User user) {
return getMaxPermSize(user, "team.maxsize.", getSettings().getMaxTeamSize());
}
protected int getMaxRangeSize(User user) {
return getMaxPermSize(user, "island.range.", getSettings().getIslandProtectionRange());
}
/**
* Get the max size based on permissions
* @param playerUUID
* @return the max permission for this perm
*/
private int getMaxPermSize(User user, String perm, int maxSize) {
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + perm)) {
if (perms.getPermission().contains(Constants.PERMPREFIX + perm + "*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + perm);
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
}
return maxSize;
}
} }

View File

@ -4,9 +4,6 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants; import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User; import us.tastybento.bskyblock.api.commands.User;
@ -15,8 +12,6 @@ import us.tastybento.bskyblock.api.events.team.TeamEvent;
public class IslandTeamCommand extends AbstractIslandTeamCommand { public class IslandTeamCommand extends AbstractIslandTeamCommand {
private static final boolean DEBUG = false;
public IslandTeamCommand(CompositeCommand islandCommand) { public IslandTeamCommand(CompositeCommand islandCommand) {
super(islandCommand, "team"); super(islandCommand, "team");
} }
@ -36,47 +31,15 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
UUID playerUUID = user.getUniqueId(); UUID playerUUID = user.getUniqueId();
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: executing team command for " + playerUUID);
}
// Fire event so add-ons can run commands, etc. // Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder() if (fireEvent(playerUUID)) {
.island(getIslands() // Cancelled
.getIsland(playerUUID)) return false;
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return true;
} }
UUID teamLeaderUUID = getTeamLeader(user); UUID teamLeaderUUID = getTeamLeader(user);
Set<UUID> teamMembers = getMembers(user); Set<UUID> teamMembers = getMembers(user);
if (teamLeaderUUID.equals(playerUUID)) { if (teamLeaderUUID.equals(playerUUID)) {
int maxSize = getSettings().getMaxTeamSize(); int maxSize = getMaxTeamSize(user);
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
}
if (teamMembers.size() < maxSize) { if (teamMembers.size() < maxSize) {
user.sendMessage("commands.island.team.invite.you-can-invite", "[number]", String.valueOf(maxSize - teamMembers.size())); user.sendMessage("commands.island.team.invite.you-can-invite", "[number]", String.valueOf(maxSize - teamMembers.size()));
} else { } else {
@ -86,4 +49,16 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
return true; return true;
} }
private boolean fireEvent(UUID playerUUID) {
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(playerUUID))
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
return event.isCancelled();
}
} }

View File

@ -7,9 +7,7 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants; import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User; import us.tastybento.bskyblock.api.commands.User;
@ -84,53 +82,35 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
user.sendMessage("commands.island.team.invite.already-on-team"); user.sendMessage("commands.island.team.invite.already-on-team");
return false; return false;
} }
return invite(user,invitedPlayer);
}
}
private boolean invite(User user, User invitedPlayer) {
Set<UUID> teamMembers = getMembers(user); Set<UUID> teamMembers = getMembers(user);
// Check if player has space on their team // Check if player has space on their team
int maxSize = getSettings().getMaxTeamSize(); int maxSize = getMaxTeamSize(user);
// Dynamic team sizes with permissions
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
}
if (teamMembers.size() < maxSize) { if (teamMembers.size() < maxSize) {
// If that player already has an invite out then retract it. // If that player already has an invite out then retract it.
// Players can only have one invite one at a time - interesting // Players can only have one invite one at a time - interesting
if (inviteList.containsValue(playerUUID)) { if (inviteList.containsValue(user.getUniqueId())) {
inviteList.inverse().remove(playerUUID); inviteList.inverse().remove(user.getUniqueId());
user.sendMessage("commands.island.team.invite.removing-invite"); user.sendMessage("commands.island.team.invite.removing-invite");
} }
// Fire event so add-ons can run commands, etc. // Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder() IslandBaseEvent event = TeamEvent.builder()
.island(getIslands().getIsland(playerUUID)) .island(getIslands().getIsland(user.getUniqueId()))
.reason(TeamEvent.Reason.INVITE) .reason(TeamEvent.Reason.INVITE)
.involvedPlayer(invitedPlayerUUID) .involvedPlayer(invitedPlayer.getUniqueId())
.build(); .build();
getPlugin().getServer().getPluginManager().callEvent(event); getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
return true; return false;
} }
// Put the invited player (key) onto the list with inviter (value) // Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the previous invite! // If someone else has invited a player, then this invite will overwrite the previous invite!
inviteList.put(invitedPlayerUUID, playerUUID); inviteList.put(invitedPlayer.getUniqueId(), user.getUniqueId());
user.sendMessage("commands.island.team.invite.invitation-sent", NAME_PLACEHOLDER, args.get(0)); user.sendMessage("commands.island.team.invite.invitation-sent", NAME_PLACEHOLDER, invitedPlayer.getName());
// Send message to online player // Send message to online player
invitedPlayer.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, user.getName()); invitedPlayer.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, user.getName());
invitedPlayer.sendMessage("commands.island.team.invite.to-accept-or-reject", "[label]", getLabel()); invitedPlayer.sendMessage("commands.island.team.invite.to-accept-or-reject", "[label]", getLabel());
@ -143,7 +123,6 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
return false; return false;
} }
} }
}
@Override @Override
public Optional<List<String>> tabComplete(final User user, final String alias, final LinkedList<String> args) { public Optional<List<String>> tabComplete(final User user, final String alias, final LinkedList<String> args) {

View File

@ -6,9 +6,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants; import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User; import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent; import us.tastybento.bskyblock.api.events.IslandBaseEvent;
@ -45,7 +42,6 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
showHelp(this, user); showHelp(this, user);
return false; return false;
} }
//getPlugin().getLogger().info("DEBUG: arg[0] = " + args.get(0));
UUID targetUUID = getPlayers().getUUID(args.get(0)); UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) { if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player"); user.sendMessage("general.errors.unknown-player");
@ -78,9 +74,16 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
if (event.isCancelled()) { if (event.isCancelled()) {
return false; return false;
} }
makeLeader(user, targetUUID);
getIslands().save(true);
return true;
}
private void makeLeader(User user, UUID targetUUID) {
// target is the new leader // target is the new leader
getIslands().getIsland(playerUUID).setOwner(targetUUID); Island island = getIslands().getIsland(user.getUniqueId());
island.setOwner(targetUUID);
user.sendMessage("commands.island.team.setowner.name-is-the-owner", "[name]", getPlayers().getName(targetUUID)); user.sendMessage("commands.island.team.setowner.name-is-the-owner", "[name]", getPlayers().getName(targetUUID));
// Check if online // Check if online
@ -88,55 +91,19 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
target.sendMessage("commands.island.team.setowner.you-are-the-owner"); target.sendMessage("commands.island.team.setowner.you-are-the-owner");
if (target.isOnline()) { if (target.isOnline()) {
// Check if new leader has a lower range permission than the island size // Check if new leader has a lower range permission than the island size
boolean hasARangePerm = false; int range = getMaxRangeSize(user);
int range = getSettings().getIslandProtectionRange();
// Check for zero protection range
Island islandByOwner = getIslands().getIsland(targetUUID);
if (islandByOwner.getProtectionRange() == 0) {
getPlugin().getLogger().warning("Player " + user.getName() + "'s island had a protection range of 0. Setting to default " + range);
islandByOwner.setProtectionRange(range);
}
for (PermissionAttachmentInfo perms : target.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "island.range.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "island.range.*")) {
// Ignore
break;
} else {
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "island.range.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
hasARangePerm = true;
range = Math.max(range, Integer.valueOf(spl[1]));
}
}
}
}
}
// Only set the island range if the player has a perm to override the default
if (hasARangePerm) {
// Do some sanity checking
if (range % 2 != 0) {
range--;
}
// Get island range
// Range can go up or down // Range can go up or down
if (range != islandByOwner.getProtectionRange()) { if (range != island.getProtectionRange()) {
user.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range)); user.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
target.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range)); target.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
getPlugin().getLogger().info( getPlugin().getLogger().info(
"Makeleader: Island protection range changed from " + islandByOwner.getProtectionRange() + " to " "Makeleader: Island protection range changed from " + island.getProtectionRange() + " to "
+ range + " for " + user.getName() + " due to permission."); + range + " for " + user.getName() + " due to permission.");
} }
islandByOwner.setProtectionRange(range); island.setProtectionRange(range);
} }
} }
getIslands().save(true);
return true;
}
@Override @Override
public Optional<List<String>> tabComplete(final User user, final String alias, final LinkedList<String> args) { public Optional<List<String>> tabComplete(final User user, final String alias, final LinkedList<String> args) {

View File

@ -27,20 +27,22 @@ import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.util.teleport.SafeTeleportBuilder; import us.tastybento.bskyblock.util.teleport.SafeTeleportBuilder;
public class NetherPortals implements Listener { public class NetherPortals implements Listener {
private static final String ERROR_NO_PERMISSION = "errors.general.no-permission";
private final BSkyBlock plugin; private final BSkyBlock plugin;
private World world; private World world;
private World nether; private World nether;
private World the_end; private World theEnd;
public NetherPortals(BSkyBlock plugin) { public NetherPortals(BSkyBlock plugin) {
this.plugin = plugin; this.plugin = plugin;
world = plugin.getIslandWorldManager().getIslandWorld(); world = plugin.getIslandWorldManager().getIslandWorld();
nether = plugin.getIslandWorldManager().getNetherWorld(); nether = plugin.getIslandWorldManager().getNetherWorld();
the_end = plugin.getIslandWorldManager().getEndWorld(); theEnd = plugin.getIslandWorldManager().getEndWorld();
} }
/** /**
* Function to check proximity to nether spawn location * Function to check proximity to nether or end spawn location.
* Used when playing with the standard nether or end.
* *
* @param location * @param location
* @return true if in the spawn area, false if not * @return true if in the spawn area, false if not
@ -48,30 +50,30 @@ public class NetherPortals implements Listener {
private boolean awayFromSpawn(Location location) { private boolean awayFromSpawn(Location location) {
Vector p = location.toVector().multiply(new Vector(1, 0, 1)); Vector p = location.toVector().multiply(new Vector(1, 0, 1));
Vector spawn = location.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1)); Vector spawn = location.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1));
if (spawn.distanceSquared(p) < (plugin.getSettings().getNetherSpawnRadius() * plugin.getSettings().getNetherSpawnRadius())) { return (spawn.distanceSquared(p) < (plugin.getSettings().getNetherSpawnRadius() * plugin.getSettings().getNetherSpawnRadius())) ? false : true;
plugin.getLogger().info("not away from spawn");
return false;
} else {
return true;
}
} }
private boolean inWorlds(Location from) { /**
return (from.getWorld().equals(world) || from.getWorld().equals(nether) || from.getWorld().equals(the_end)) ? true : false; * Check if the player is in the island worlds
* @param location
* @return true if the player is
*/
private boolean inWorlds(Location location) {
return (location.getWorld().equals(world) || location.getWorld().equals(nether) || location.getWorld().equals(theEnd)) ? true : false;
} }
/**
* If the player is in the standard nether or standard end or op, do nothing.
* Used to protect the standard spawn for nether or end
* @param player
* @return true if nothing needs to be done
*/
private boolean noAction(Player player) { private boolean noAction(Player player) {
if (player.isOp() return (player.isOp()
|| (!player.getWorld().equals(nether) && !player.getWorld().equals(the_end)) || (!player.getWorld().equals(nether) && !player.getWorld().equals(theEnd))
|| (player.getWorld().equals(nether) && plugin.getSettings().isNetherIslands()) || (player.getWorld().equals(nether) && plugin.getSettings().isNetherIslands())
|| (player.getWorld().equals(the_end) && plugin.getSettings().isEndIslands())) { || (player.getWorld().equals(theEnd) && plugin.getSettings().isEndIslands())) ? true: false;
plugin.getLogger().info("No legacy nether or end");
return true;
} }
plugin.getLogger().info("Action!");
return false;
}
/** /**
* Prevents blocks from being broken * Prevents blocks from being broken
@ -84,20 +86,22 @@ public class NetherPortals implements Listener {
return; return;
} }
if (!awayFromSpawn(event.getBlock().getLocation())) { if (!awayFromSpawn(event.getBlock().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission"); User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true); event.setCancelled(true);
} }
} }
// Nether portal spawn protection /**
* Protects standard nether or end spawn from bucket abuse
* @param event
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBucketEmpty(PlayerBucketEmptyEvent event) { public void onBucketEmpty(PlayerBucketEmptyEvent event) {
if (noAction(event.getPlayer())) { if (noAction(event.getPlayer())) {
return; return;
} }
if (!awayFromSpawn(event.getBlockClicked().getLocation())) { if (!awayFromSpawn(event.getBlockClicked().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission"); User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -108,7 +112,6 @@ public class NetherPortals implements Listener {
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEndIslandPortal(PlayerPortalEvent event) { public void onEndIslandPortal(PlayerPortalEvent event) {
plugin.getLogger().info("End portal event Is end generated? " + plugin.getSettings().isEndGenerate());
if (!event.getCause().equals(TeleportCause.END_PORTAL) || !plugin.getSettings().isEndGenerate()) { if (!event.getCause().equals(TeleportCause.END_PORTAL) || !plugin.getSettings().isEndGenerate()) {
return; return;
} }
@ -116,17 +119,15 @@ public class NetherPortals implements Listener {
return; return;
} }
// If entering a portal in the end, teleport home if you have one, else do nothing // If entering a portal in the end, teleport home if you have one, else do nothing
if (event.getFrom().getWorld().equals(the_end)) { if (event.getFrom().getWorld().equals(theEnd)) {
plugin.getLogger().info("In end world");
if (plugin.getIslands().hasIsland(event.getPlayer().getUniqueId())) { if (plugin.getIslands().hasIsland(event.getPlayer().getUniqueId())) {
event.setCancelled(true); event.setCancelled(true);
plugin.getIslands().homeTeleport(event.getPlayer()); plugin.getIslands().homeTeleport(event.getPlayer());
} }
return; return;
} }
plugin.getLogger().info("In other world going through end portal");
// If this is island end, then go to the same location, otherwise try spawn // If this is island end, then go to the same location, otherwise try spawn
Location to = plugin.getSettings().isEndIslands() ? event.getFrom().toVector().toLocation(the_end) : the_end.getSpawnLocation(); Location to = plugin.getSettings().isEndIslands() ? event.getFrom().toVector().toLocation(theEnd) : theEnd.getSpawnLocation();
// Else other worlds teleport to the end // Else other worlds teleport to the end
event.setCancelled(true); event.setCancelled(true);
new SafeTeleportBuilder(plugin) new SafeTeleportBuilder(plugin)
@ -144,7 +145,6 @@ public class NetherPortals implements Listener {
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityPortal(EntityPortalEvent event) { public void onEntityPortal(EntityPortalEvent event) {
plugin.getLogger().info(event.getEventName());
if (inWorlds(event.getFrom())) { if (inWorlds(event.getFrom())) {
// Disable entity portal transfer due to dupe glitching // Disable entity portal transfer due to dupe glitching
event.setCancelled(true); event.setCancelled(true);
@ -152,7 +152,7 @@ public class NetherPortals implements Listener {
} }
/** /**
* Prevent spawns from being blown up * Prevent standard nether or end spawns from being blown up
* *
* @param e * @param e
*/ */
@ -162,7 +162,7 @@ public class NetherPortals implements Listener {
return; return;
} }
if ((event.getLocation().getWorld().equals(nether) && plugin.getSettings().isNetherIslands()) if ((event.getLocation().getWorld().equals(nether) && plugin.getSettings().isNetherIslands())
|| (event.getLocation().getWorld().equals(the_end) && plugin.getSettings().isEndIslands())) { || (event.getLocation().getWorld().equals(theEnd) && plugin.getSettings().isEndIslands())) {
// Not used in island worlds // Not used in island worlds
return; return;
} }
@ -186,7 +186,6 @@ public class NetherPortals implements Listener {
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onNetherPortal(PlayerPortalEvent event) { public void onNetherPortal(PlayerPortalEvent event) {
plugin.getLogger().info(event.getEventName() + " " + event.getCause() + " nether");
if (!event.getCause().equals(TeleportCause.NETHER_PORTAL)) { if (!event.getCause().equals(TeleportCause.NETHER_PORTAL)) {
return; return;
} }
@ -195,10 +194,8 @@ public class NetherPortals implements Listener {
} }
// If entering a portal in the nether, teleport to portal in overworld if there is one // If entering a portal in the nether, teleport to portal in overworld if there is one
if (event.getFrom().getWorld().equals(nether)) { if (event.getFrom().getWorld().equals(nether)) {
plugin.getLogger().info("Entered portal in nether");
// If this is island nether, then go to the same vector, otherwise try spawn // If this is island nether, then go to the same vector, otherwise try spawn
Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(world) : plugin.getIslands().getIslandLocation(event.getPlayer().getUniqueId()); Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(world) : plugin.getIslands().getIslandLocation(event.getPlayer().getUniqueId());
plugin.getLogger().info("Going to " + to);
event.setCancelled(true); event.setCancelled(true);
// Else other worlds teleport to the nether // Else other worlds teleport to the nether
new SafeTeleportBuilder(plugin) new SafeTeleportBuilder(plugin)
@ -208,10 +205,8 @@ public class NetherPortals implements Listener {
.build(); .build();
return; return;
} }
plugin.getLogger().info("Entering nether portal in overworld");
// If this is island nether, then go to the same vector, otherwise try spawn // If this is island nether, then go to the same vector, otherwise try spawn
Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(nether) : nether.getSpawnLocation(); Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(nether) : nether.getSpawnLocation();
plugin.getLogger().info("Going to " + to);
event.setCancelled(true); event.setCancelled(true);
// Else other worlds teleport to the nether // Else other worlds teleport to the nether
new SafeTeleportBuilder(plugin) new SafeTeleportBuilder(plugin)
@ -223,7 +218,7 @@ public class NetherPortals implements Listener {
} }
/** /**
* Prevents placing of blocks * Prevents placing of blocks at standard nether or end spawns
* *
* @param e * @param e
*/ */
@ -233,7 +228,7 @@ public class NetherPortals implements Listener {
return; return;
} }
if (!awayFromSpawn(event.getBlock().getLocation())) { if (!awayFromSpawn(event.getBlock().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission"); User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true); event.setCancelled(true);
} }
} }

View File

@ -129,9 +129,6 @@ public class Util {
* Credits to mikenon on GitHub! * Credits to mikenon on GitHub!
*/ */
public static String prettifyText(String ugly) { public static String prettifyText(String ugly) {
if (!ugly.contains("_") && (!ugly.equals(ugly.toUpperCase()))) {
return ugly;
}
String fin = ""; String fin = "";
ugly = ugly.toLowerCase(); ugly = ugly.toLowerCase();
if (ugly.contains("_")) { if (ugly.contains("_")) {

View File

@ -5,7 +5,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.bukkit.Bukkit;
import org.bukkit.ChunkSnapshot; import org.bukkit.ChunkSnapshot;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
@ -129,9 +128,15 @@ public class SafeSpotTeleport {
do { do {
for (int i = x - radius; i <= x + radius; i++) { for (int i = x - radius; i <= x + radius; i++) {
for (int j = z - radius; j <= z + radius; j++) { for (int j = z - radius; j <= z + radius; j++) {
addChunk(result, island, new Pair<>(i,j), new Pair<>(i/16, j/16));
}
}
radius++;
} while (radius < maxRadius);
return result;
}
Pair<Integer, Integer> blockCoord = new Pair<>(i,j); private void addChunk(List<Pair<Integer, Integer>> result, Optional<Island> island, Pair<Integer, Integer> blockCoord, Pair<Integer, Integer> chunkCoord) {
Pair<Integer, Integer> chunkCoord = new Pair<>(i/16, j/16);
if (!result.contains(chunkCoord)) { if (!result.contains(chunkCoord)) {
// Add the chunk coord // Add the chunk coord
if (!island.isPresent()) { if (!island.isPresent()) {
@ -146,11 +151,7 @@ public class SafeSpotTeleport {
}); });
} }
} }
}
}
radius++;
} while (radius < maxRadius);
return result;
} }
/** /**
@ -268,7 +269,6 @@ public class SafeSpotTeleport {
break; break;
case PORTAL: case PORTAL:
if (portal) { if (portal) {
Bukkit.getLogger().info("Portal found");
Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D); Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D);
// Teleport as soon as we find a portal // Teleport as soon as we find a portal
teleportEntity(newSpot.toLocation(world)); teleportEntity(newSpot.toLocation(world));
@ -276,27 +276,29 @@ public class SafeSpotTeleport {
} }
break; break;
default: default:
return safe(world, chunk, x, y, z);
}
}
}
return false;
}
private boolean safe(World world, ChunkSnapshot chunk, int x, int y, int z) {
// Safe // Safe
Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D); Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D);
// Check for portal // Check for portal
if (portal) { if (portal) {
if (bestSpot == null) { if (bestSpot == null) {
Bukkit.getLogger().info("Best spot found = " + bestSpot);
// Stash the best spot // Stash the best spot
bestSpot = newSpot.toLocation(world); bestSpot = newSpot.toLocation(world);
return false;
} }
return false;
} else { } else {
// Regular search - teleport as soon as we find something // Regular search - teleport as soon as we find something
Bukkit.getLogger().info("Safe spot found, teleporting to new spot");
teleportEntity(newSpot.toLocation(world)); teleportEntity(newSpot.toLocation(world));
return true; return true;
} }
} }
}
}
return false;
}
} }