Improve command codestyle (#3337)

Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

Fixes #3579 (async `/skull` command)
Fixes #3336 (improve codestyle of commands)
Partially addresses #3339 (`/spawn` and `/setspawn` are now hidden from tabcomplete)
Closes #3087 (`/paytoggle` is now a loop command)
This commit is contained in:
Josh Roy 2020-08-11 14:09:22 -04:00 committed by GitHub
parent 14c6c2a055
commit f6cb9ff470
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
96 changed files with 1123 additions and 1448 deletions

View File

@ -22,8 +22,15 @@ public class CommandSource {
return null; return null;
} }
public final net.ess3.api.IUser getUser(IEssentials ess) {
if (sender instanceof Player) {
return ess.getUser((Player) sender);
}
return null;
}
public final boolean isPlayer() { public final boolean isPlayer() {
return (sender instanceof Player); return sender instanceof Player;
} }
public final CommandSender setSender(final CommandSender base) { public final CommandSender setSender(final CommandSender base) {
@ -36,4 +43,12 @@ public class CommandSource {
sender.sendMessage(message); sender.sendMessage(message);
} }
} }
public boolean isAuthorized(String permission, IEssentials ess) {
return !(sender instanceof Player) || getUser(ess).isAuthorized(permission);
}
public String getSelfSelector() {
return sender instanceof Player ? getPlayer().getName() : "*";
}
} }

View File

@ -33,7 +33,6 @@ import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.base.Throwables;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.ISettings; import net.ess3.api.ISettings;
@ -77,13 +76,10 @@ import org.yaml.snakeyaml.error.YAMLException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -108,7 +104,6 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient MetricsWrapper metrics; private transient MetricsWrapper metrics;
private transient EssentialsTimer timer; private transient EssentialsTimer timer;
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>(); private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private transient Method oldGetOnlinePlayers;
private transient SpawnerItemProvider spawnerItemProvider; private transient SpawnerItemProvider spawnerItemProvider;
private transient SpawnerBlockProvider spawnerBlockProvider; private transient SpawnerBlockProvider spawnerBlockProvider;
private transient SpawnEggProvider spawnEggProvider; private transient SpawnEggProvider spawnEggProvider;
@ -185,13 +180,6 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
} }
} }
for (Method method : Server.class.getDeclaredMethods()) {
if (method.getName().endsWith("getOnlinePlayers") && method.getReturnType() == Player[].class) {
oldGetOnlinePlayers = method;
break;
}
}
try { try {
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings(); upgrade.beforeSettings();
@ -633,6 +621,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
if (!ex.getMessage().isEmpty()) { if (!ex.getMessage().isEmpty()) {
sender.sendMessage(ex.getMessage()); sender.sendMessage(ex.getMessage());
} }
if (ex.getCause() != null && settings.isDebug()) {
ex.getCause().printStackTrace();
}
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
showError(sender, ex, commandLabel); showError(sender, ex, commandLabel);
@ -936,22 +927,16 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override @Override
public Collection<Player> getOnlinePlayers() { public Collection<Player> getOnlinePlayers() {
try { return (Collection<Player>) getServer().getOnlinePlayers();
return (Collection<Player>) getServer().getOnlinePlayers(); // Needed for sanity here, the Bukkit API is a bit broken in the sense it only allows subclasses of Player to this list
} catch (NoSuchMethodError ex) {
try {
return Arrays.asList((Player[]) oldGetOnlinePlayers.invoke(getServer()));
} catch (InvocationTargetException ex1) {
throw Throwables.propagate(ex.getCause());
} catch (IllegalAccessException ex1) {
throw new RuntimeException("Error invoking oldGetOnlinePlayers", ex1);
}
}
} }
@Override @Override
public Iterable<User> getOnlineUsers() { public List<User> getOnlineUsers() {
return getOnlinePlayers().stream().map(this::getUser).collect(Collectors.toList()); List<User> onlineUsers = new ArrayList<>();
for (Player player : getOnlinePlayers()) {
onlineUsers.add(getUser(player));
}
return onlineUsers;
} }
@Override @Override

View File

@ -102,7 +102,7 @@ public interface IEssentials extends Plugin {
Collection<Player> getOnlinePlayers(); Collection<Player> getOnlinePlayers();
Iterable<User> getOnlineUsers(); Collection<User> getOnlineUsers();
SpawnerItemProvider getSpawnerItemProvider(); SpawnerItemProvider getSpawnerItemProvider();

View File

@ -179,6 +179,8 @@ public interface IUser {
String getName(); String getName();
String getDisplayName();
String getAfkMessage(); String getAfkMessage();
void setAfkMessage(final String message); void setAfkMessage(final String message);

View File

@ -15,7 +15,6 @@ import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.JailStatusChangeEvent; import net.ess3.api.events.JailStatusChangeEvent;
import net.ess3.api.events.MuteStatusChangeEvent; import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent; import net.ess3.api.events.UserBalanceUpdateEvent;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -325,11 +324,25 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return teleportLocation; return teleportLocation;
} }
public String getNick(final boolean longnick) { public String getNick() {
return getNick(longnick, true, true); return getNick(true, true);
} }
public String getNick(final boolean longnick, final boolean withPrefix, final boolean withSuffix) { /**
* Needed for backwards compatibility.
*/
public String getNick(final boolean longnick) {
return getNick(true, true);
}
/**
* Needed for backwards compatibility.
*/
public String getNick(boolean longnick, final boolean withPrefix, final boolean withSuffix) {
return getNick(withPrefix, withSuffix);
}
public String getNick(final boolean withPrefix, final boolean withSuffix) {
final StringBuilder prefix = new StringBuilder(); final StringBuilder prefix = new StringBuilder();
String nickname; String nickname;
String suffix = ""; String suffix = "";
@ -377,15 +390,6 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
final String strPrefix = prefix.toString(); final String strPrefix = prefix.toString();
String output = strPrefix + nickname + suffix; String output = strPrefix + nickname + suffix;
if (!longnick && output.length() > 16) {
output = strPrefix + nickname;
}
if (!longnick && output.length() > 16) {
output = FormatUtil.lastCode(strPrefix) + nickname;
}
if (!longnick && output.length() > 16) {
output = FormatUtil.lastCode(strPrefix) + nickname.substring(0, 14);
}
if (output.charAt(output.length() - 1) == '§') { if (output.charAt(output.length() - 1) == '§') {
output = output.substring(0, output.length() - 1); output = output.substring(0, output.length() - 1);
} }
@ -398,10 +402,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (isAfk()) { if (isAfk()) {
updateAfkListName(); updateAfkListName();
} else if (ess.getSettings().changePlayerListName()) { } else if (ess.getSettings().changePlayerListName()) {
// 1.8 enabled player list-names longer than 16 characters. String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
// If the server is on 1.8 or higher, provide that functionality. Otherwise, keep prior functionality.
boolean higherOrEqualTo1_8 = ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_8_R1);
String name = getNick(higherOrEqualTo1_8, ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
try { try {
this.getBase().setPlayerListName(name); this.getBase().setPlayerListName(name);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -413,6 +414,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
} }
@Override
public String getDisplayName() { public String getDisplayName() {
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName(); return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
} }

View File

@ -4,10 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -23,7 +20,7 @@ public class Commandback extends EssentialsCommand {
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
CommandSource sender = user.getSource(); CommandSource sender = user.getSource();
if (args.length > 0 && user.isAuthorized("essentials.back.others")) { if (args.length > 0 && user.isAuthorized("essentials.back.others")) {
this.parseCommand(server, sender, args, true, commandLabel); parseOthers(server, sender, args, commandLabel);
return; return;
} }
@ -32,28 +29,17 @@ public class Commandback extends EssentialsCommand {
@Override @Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
this.parseCommand(server, sender, args, true, commandLabel); parseOthers(server, sender, args, commandLabel);
} }
private void parseCommand(Server server, CommandSource sender, String[] args, boolean allowOthers, String commandLabel) throws Exception { private void parseOthers(Server server, CommandSource sender, String[] args, String commandLabel) throws Exception {
Collection<Player> players = new ArrayList<>(); User player = getPlayer(server, args, 0, true, false);
sender.sendMessage(tl("backOther", player.getName()));
if (allowOthers && args.length > 0 && args[0].trim().length() > 2) { teleportBack(sender, player, commandLabel);
players = server.matchPlayer(args[0].trim());
}
if (players.size() < 1) {
throw new PlayerNotFoundException();
}
for (Player player : players) {
sender.sendMessage(tl("backOther", player.getName()));
teleportBack(sender, ess.getUser(player), commandLabel);
}
} }
private void teleportBack(CommandSource sender, User user, String commandLabel) throws Exception { private void teleportBack(CommandSource sender, User user, String commandLabel) throws Exception {

View File

@ -5,7 +5,6 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server; import org.bukkit.Server;
import java.math.BigDecimal;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -19,7 +18,7 @@ public class Commandbalance extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -31,11 +30,9 @@ public class Commandbalance extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 1 && user.isAuthorized("essentials.balance.others")) { if (args.length == 1 && user.isAuthorized("essentials.balance.others")) {
final User target = getPlayer(server, args, 0, true, true); final User target = getPlayer(server, args, 0, true, true);
final BigDecimal bal = target.getMoney(); user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(bal, ess)));
} else if (args.length < 2) { } else if (args.length < 2) {
final BigDecimal bal = user.getMoney(); user.sendMessage(tl("balance", NumberUtil.displayCurrency(user.getMoney(), ess)));
user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess)));
} else { } else {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -44,7 +44,7 @@ public class Commandbalancetop extends EssentialsCommand {
if (!force && lock.readLock().tryLock()) { if (!force && lock.readLock().tryLock()) {
try { try {
if (cacheage > System.currentTimeMillis() - CACHETIME) { if (cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page); outputCache(sender, page);
return; return;
} }
if (ess.getUserMap().getUniqueUsers() > MINUSERS) { if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
@ -53,17 +53,16 @@ public class Commandbalancetop extends EssentialsCommand {
} finally { } finally {
lock.readLock().unlock(); lock.readLock().unlock();
} }
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
} else { } else {
if (ess.getUserMap().getUniqueUsers() > MINUSERS) { if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers())); sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers()));
} }
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
} }
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
} }
private static void outputCache(final CommandSource sender, String command, int page) { private static void outputCache(final CommandSource sender, int page) {
final Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cacheage); cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
@ -149,7 +148,7 @@ public class Commandbalancetop extends EssentialsCommand {
lock.readLock().lock(); lock.readLock().lock();
try { try {
if (!force && cacheage > System.currentTimeMillis() - CACHETIME) { if (!force && cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page); outputCache(sender, page);
return; return;
} }
} finally { } finally {

View File

@ -17,10 +17,8 @@ public class Commandbreak extends EssentialsCommand {
//TODO: Switch to use util class //TODO: Switch to use util class
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final Block block = user.getBase().getTargetBlock(null, 20); final Block block = user.getBase().getTargetBlock(null, 20);
if (block == null) {
throw new NoChargeException();
}
if (block.getType() == Material.AIR) { if (block.getType() == Material.AIR) {
throw new NoChargeException(); throw new NoChargeException();
} }

View File

@ -1,7 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.IText;
@ -9,7 +7,6 @@ import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -18,6 +15,8 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcastworld extends EssentialsCommand { public class Commandbroadcastworld extends EssentialsCommand {
@ -27,12 +26,13 @@ public class Commandbroadcastworld extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
World world = user.getWorld(); World world = user.getWorld();
String message = getFinalArg(args, 0); String message = getFinalArg(args, 0);
if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
World argWorld = ess.getWorld(args[0]); World argWorld = ess.getWorld(args[0]);
if (argWorld != null) { if (argWorld != null) {
world = argWorld; world = argWorld;
@ -40,12 +40,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
} }
} }
if (world == null) { sendBroadcast(world, user.getDisplayName(), message);
world = user.getWorld();
message = getFinalArg(args, 0);
}
sendBroadcast(world.getName(), user.getDisplayName(), message);
} }
@Override @Override
@ -53,14 +48,15 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (args.length < 2) { if (args.length < 2) {
throw new NotEnoughArgumentsException("world"); throw new NotEnoughArgumentsException("world");
} }
sendBroadcast(args[0], sender.getSender().getName(), getFinalArg(args, 1));
}
private void sendBroadcast(final String worldName, final String name, final String message) throws Exception { World world = ess.getWorld(args[0]);
World world = ess.getWorld(worldName);
if (world == null) { if (world == null) {
throw new Exception(tl("invalidWorld")); throw new Exception(tl("invalidWorld"));
} }
sendBroadcast(world, sender.getSender().getName(), getFinalArg(args, 1));
}
private void sendBroadcast(final World world, final String name, final String message) throws Exception {
if (message.isEmpty()) { if (message.isEmpty()) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -21,10 +21,6 @@ public class Commandburn extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
if (args[0].trim().length() < 2) {
throw new NotEnoughArgumentsException();
}
User user = getPlayer(server, sender, args, 0); User user = getPlayer(server, sender, args, 0);
user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20); user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]))); sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1])));

View File

@ -16,73 +16,56 @@ import java.util.*;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand { public class Commandclearinventory extends EssentialsLoopCommand {
public Commandclearinventory() { public Commandclearinventory() {
super("clearinventory"); super("clearinventory");
} }
private static final int BASE_AMOUNT = 100000; private static final int BASE_AMOUNT = 100000;
private static final int EXTENDED_CAP = 8;
@Override @Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
parseCommand(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.clearinventory.others"), final String previousClearCommand = user.getConfirmingClearCommand();
user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")); user.setConfirmingClearCommand(null);
}
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
parseCommand(server, sender, commandLabel, args, true, true);
}
private void parseCommand(Server server, CommandSource sender, String commandLabel, String[] args, boolean allowOthers, boolean allowAll)
throws Exception {
Collection<Player> players = new ArrayList<>();
User senderUser = ess.getUser(sender.getPlayer());
String previousClearCommand = "";
int offset = 0;
if (sender.isPlayer()) {
players.add(sender.getPlayer());
// Clear previous command execution before potential errors to reset confirmation.
previousClearCommand = senderUser.getConfirmingClearCommand();
senderUser.setConfirmingClearCommand(null);
}
if (allowAll && args.length > 0 && args[0].contentEquals("*")) {
sender.sendMessage(tl("inventoryClearingFromAll"));
offset = 1;
players = ess.getOnlinePlayers();
} else if (allowOthers && args.length > 0 && args[0].trim().length() > 2) {
offset = 1;
players = server.matchPlayer(args[0].trim());
}
if (players.size() < 1) {
throw new PlayerNotFoundException();
}
// Confirm
String formattedCommand = formatCommand(commandLabel, args); String formattedCommand = formatCommand(commandLabel, args);
if (senderUser != null && senderUser.isPromptingClearConfirm()) { if (user.isPromptingClearConfirm()) {
if (!formattedCommand.equals(previousClearCommand)) { if (!formattedCommand.equals(previousClearCommand)) {
senderUser.setConfirmingClearCommand(formattedCommand); user.setConfirmingClearCommand(formattedCommand);
senderUser.sendMessage(tl("confirmClear", formattedCommand)); user.sendMessage(tl("confirmClear", formattedCommand));
return; return;
} }
} }
for (Player player : players) { if (args.length == 0 || (!args[0].contains("*") && server.matchPlayer(args[0]).isEmpty())) {
clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP); clearHandler(user.getSource(), user.getBase(), args, 0);
return;
} }
if (user.isAuthorized("essentials.clearinventory.others")) {
loopOnlinePlayers(server, user.getSource(), false, true, args[0], args);
return;
}
throw new PlayerNotFoundException();
}
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
loopOnlinePlayers(server, sender, false, true, args[0], args);
}
@Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) {
clearHandler(sender, player.getBase(), args, 1);
} }
private static class Item { private static class Item {
private Material material; private final Material material;
private short data; private final short data;
public Item(Material material, short data) { public Item(Material material, short data) {
this.material = material; this.material = material;
@ -102,7 +85,7 @@ public class Commandclearinventory extends EssentialsCommand {
ALL_EXCEPT_ARMOR, ALL_INCLUDING_ARMOR, SPECIFIC_ITEM ALL_EXCEPT_ARMOR, ALL_INCLUDING_ARMOR, SPECIFIC_ITEM
} }
protected void clearHandler(CommandSource sender, Player player, String[] args, int offset, boolean showExtended) { protected void clearHandler(CommandSource sender, Player player, String[] args, int offset) {
ClearHandlerType type = ClearHandlerType.ALL_EXCEPT_ARMOR; ClearHandlerType type = ClearHandlerType.ALL_EXCEPT_ARMOR;
final Set<Item> items = new HashSet<>(); final Set<Item> items = new HashSet<>();
int amount = -1; int amount = -1;
@ -131,18 +114,12 @@ public class Commandclearinventory extends EssentialsCommand {
} }
} }
if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) {
{ sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
}
InventoryWorkaround.clearInventoryNoArmor(player.getInventory()); InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null); InventoryWorkaround.setItemInOffHand(player, null);
} else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) } else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) {
{ sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
}
InventoryWorkaround.clearInventoryNoArmor(player.getInventory()); InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null); InventoryWorkaround.setItemInOffHand(player, null);
player.getInventory().setArmorContents(null); player.getInventory().setArmorContents(null);
@ -157,7 +134,7 @@ public class Commandclearinventory extends EssentialsCommand {
stack.setAmount(BASE_AMOUNT); stack.setAmount(BASE_AMOUNT);
ItemStack removedStack = player.getInventory().removeItem(stack).get(0); ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
final int removedAmount = (BASE_AMOUNT - removedStack.getAmount()); final int removedAmount = (BASE_AMOUNT - removedStack.getAmount());
if (removedAmount > 0 || showExtended) { if (removedAmount > 0) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
} }
} else { } else {
@ -165,10 +142,6 @@ public class Commandclearinventory extends EssentialsCommand {
if (player.getInventory().containsAtLeast(stack, amount)) { if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack); player.getInventory().removeItem(stack);
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
}
} }
} }
} }

View File

@ -15,7 +15,7 @@ public class Commanddeljail extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -18,7 +18,7 @@ public class Commanddelkit extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
final String kitList = ess.getKits().listKits(ess, null); final String kitList = ess.getKits().listKits(ess, null);
sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException(); throw new NoChargeException();

View File

@ -17,7 +17,7 @@ public class Commanddelwarp extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -18,9 +18,6 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandeco extends EssentialsLoopCommand { public class Commandeco extends EssentialsLoopCommand {
Commandeco.EcoCommands cmd;
BigDecimal amount;
boolean isPercent;
public Commandeco() { public Commandeco() {
super("eco"); super("eco");
@ -32,75 +29,49 @@ public class Commandeco extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
BigDecimal startingBalance = ess.getSettings().getStartingBalance(); EcoCommands cmd;
boolean isPercent;
BigDecimal amount;
try { try {
cmd = Commandeco.EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); cmd = EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH));
isPercent = cmd != EcoCommands.RESET && args[2].endsWith("%"); isPercent = cmd != EcoCommands.RESET && args[2].endsWith("%");
amount = (cmd == Commandeco.EcoCommands.RESET) ? startingBalance : new BigDecimal(args[2].replaceAll("[^0-9\\.]", "")); amount = (cmd == EcoCommands.RESET) ? ess.getSettings().getStartingBalance() : new BigDecimal(args[2].replaceAll("[^0-9\\.]", ""));
} catch (Exception ex) { } catch (Exception ex) {
throw new NotEnoughArgumentsException(ex); throw new NotEnoughArgumentsException(ex);
} }
loopOfflinePlayers(server, sender, false, true, args[1], args); loopOfflinePlayersConsumer(server, sender, false, true, args[1], player -> {
BigDecimal userAmount = amount;
if (cmd == Commandeco.EcoCommands.RESET || cmd == Commandeco.EcoCommands.SET) { if (isPercent) {
if (args[1].contentEquals("**")) { userAmount = player.getMoney().multiply(userAmount).scaleByPowerOfTen(-2);
server.broadcastMessage(tl("resetBalAll", NumberUtil.displayCurrency(amount, ess)));
} else if (args[1].contentEquals("*")) {
server.broadcastMessage(tl("resetBal", NumberUtil.displayCurrency(amount, ess)));
} }
}
}
@Override switch (cmd) {
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException { case GIVE: {
if (isPercent && cmd != EcoCommands.RESET) { player.giveMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
amount = player.getMoney().multiply(amount).scaleByPowerOfTen(-2); break;
} }
switch (cmd) { case TAKE: {
case GIVE: if (player.getMoney().subtract(userAmount).compareTo(ess.getSettings().getMinMoney()) >= 0) {
player.giveMoney(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.takeMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
break; } else {
ess.showError(sender, new Exception(tl("minimumBalanceError", NumberUtil.displayCurrency(ess.getSettings().getMinMoney(), ess))), commandLabel);
case TAKE: }
take(amount, player, sender); break;
break; }
case RESET:
case RESET: case SET: {
case SET: BigDecimal minBal = ess.getSettings().getMinMoney();
set(amount, player, sender); BigDecimal maxBal = ess.getSettings().getMaxMoney();
break; boolean underMin = (userAmount.compareTo(minBal) < 0);
} boolean aboveMax = (userAmount.compareTo(maxBal) > 0);
} player.setMoney(underMin ? minBal : aboveMax ? maxBal : userAmount, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess)));
private void take(BigDecimal amount, final User player, final CommandSource sender) throws ChargeException { sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
BigDecimal money = player.getMoney(); break;
BigDecimal minBalance = ess.getSettings().getMinMoney(); }
if (money.subtract(amount).compareTo(minBalance) >= 0) {
player.takeMoney(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
} else if (sender == null) {
try {
player.setMoney(minBalance, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
} catch (MaxMoneyException ex) {
// Take shouldn't be able to throw a max money exception
} }
player.sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(player.getMoney(), ess))); });
} else {
throw new ChargeException(tl("insufficientFunds"));
}
}
private void set(BigDecimal amount, final User player, final CommandSource sender) throws MaxMoneyException {
BigDecimal minBalance = ess.getSettings().getMinMoney();
BigDecimal maxBalance = ess.getSettings().getMaxMoney();
boolean underMinimum = (amount.compareTo(minBalance) < 0);
boolean aboveMax = (amount.compareTo(maxBalance) > 0);
player.setMoney(underMinimum ? minBalance : aboveMax ? maxBalance : amount, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess)));
if (sender != null) {
sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
}
} }
@ -108,6 +79,11 @@ public class Commandeco extends EssentialsLoopCommand {
GIVE, TAKE, SET, RESET GIVE, TAKE, SET, RESET
} }
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
}
@Override @Override
protected List<String> getTabCompleteOptions(Server server, final CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, final CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) { if (args.length == 1) {

View File

@ -11,13 +11,7 @@ import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.Collections; import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -34,16 +28,16 @@ public class Commandenchant extends EssentialsCommand {
if (stack == null || stack.getType() == Material.AIR) { if (stack == null || stack.getType() == Material.AIR) {
throw new Exception(tl("nothingInHand")); throw new Exception(tl("nothingInHand"));
} }
if (args.length == 0) { if (args.length == 0) {
final Set<String> enchantmentslist = new TreeSet<>(); final Set<String> usableEnchants = new TreeSet<>();
for (Map.Entry<String, Enchantment> entry : Enchantments.entrySet()) { for (Map.Entry<String, Enchantment> entry : Enchantments.entrySet()) {
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); final String name = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || (user.isAuthorized("essentials.enchantments." + enchantmentName) && entry.getValue().canEnchantItem(stack))) { if (usableEnchants.contains(name) || (user.isAuthorized("essentials.enchantments." + name) && entry.getValue().canEnchantItem(stack))) {
enchantmentslist.add(entry.getKey()); usableEnchants.add(entry.getKey());
//enchantmentslist.add(enchantmentName);
} }
} }
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray()))); throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(usableEnchants.toArray())));
} }
int level = 1; int level = 1;
@ -51,23 +45,20 @@ public class Commandenchant extends EssentialsCommand {
try { try {
level = Integer.parseInt(args[1]); level = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
level = -1; throw new NotEnoughArgumentsException();
} }
} }
final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe");
final MetaItemStack metaStack = new MetaItemStack(stack); final MetaItemStack metaStack = new MetaItemStack(stack);
final Enchantment enchantment = metaStack.getEnchantment(user, args[0]); final Enchantment enchantment = metaStack.getEnchantment(user, args[0]);
metaStack.addEnchantment(user.getSource(), allowUnsafe, enchantment, level); metaStack.addEnchantment(user.getSource(), ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe"), enchantment, level);
InventoryWorkaround.setItemInMainHand(user.getBase(), metaStack.getItemStack()); InventoryWorkaround.setItemInMainHand(user.getBase(), metaStack.getItemStack());
user.getBase().updateInventory(); user.getBase().updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); final String enchantName = enchantment.getName().toLowerCase(Locale.ENGLISH).replace('_', ' ');
if (level == 0) { if (level == 0) {
user.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' '))); user.sendMessage(tl("enchantmentRemoved", enchantName));
} else { } else {
user.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' '))); user.sendMessage(tl("enchantmentApplied", enchantName));
} }
} }

View File

@ -13,17 +13,14 @@ public class Commandenderchest extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
User target = user;
if (args.length > 0 && user.isAuthorized("essentials.enderchest.others")) { if (args.length > 0 && user.isAuthorized("essentials.enderchest.others")) {
final User invUser = getPlayer(server, user, args, 0); target = getPlayer(server, user, args, 0);
user.getBase().closeInventory();
user.getBase().openInventory(invUser.getBase().getEnderChest());
user.setEnderSee(true);
} else {
user.getBase().closeInventory();
user.getBase().openInventory(user.getBase().getEnderChest());
user.setEnderSee(false);
} }
user.getBase().closeInventory();
user.getBase().openInventory(target.getBase().getEnderChest());
user.setEnderSee(!target.equals(user));
} }
@Override @Override

View File

@ -1,13 +1,14 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix; import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -15,126 +16,121 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsCommand { public class Commandexp extends EssentialsLoopCommand {
public Commandexp() { public Commandexp() {
super("exp"); super("exp");
} }
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
showExp(user.getSource(), user);
} else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) {
expMatch(server, user.getSource(), args[1], args[2], false);
} else {
setExp(user.getSource(), user, args[1], false);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[2], true);
} else {
setExp(user.getSource(), user, args[1], true);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.take.others")) {
expMatch(server, user.getSource(), args[1], "-" + args[2], true);
} else {
setExp(user.getSource(), user, "-" + args[1], true);
}
} else if (args.length < 3 && args[0].equalsIgnoreCase("reset") && user.isAuthorized("essentials.exp.reset")) {
if (args.length == 2 && user.isAuthorized("essentials.exp.reset.others")) {
expMatch(server, user.getSource(), args[1], "0", false);
} else {
setExp(user.getSource(), user, "0", false);
}
} else if (args[0].equalsIgnoreCase("show")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) {
String match = args[1].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
} else {
if (args.length >= 1 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[0], true);
} else {
setExp(user.getSource(), user, args[0], true);
}
} else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) {
String match = args[0].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
}
}
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { IUser user = sender.getUser(ess);
throw new NotEnoughArgumentsException(); if (args.length == 0 || (args.length < 2 && user == null)) {
} else if (args.length > 2 && args[0].equalsIgnoreCase("set")) { if (user == null) {
expMatch(server, sender, args[1], args[2], false); throw new NotEnoughArgumentsException();
} else if (args.length > 2 && args[0].equalsIgnoreCase("give")) {
expMatch(server, sender, args[1], args[2], true);
} else if (args.length > 2 && args[0].equalsIgnoreCase("take")) {
expMatch(server, sender, args[1], "-" + args[2], true);
} else if (args.length > 2 && args[0].equalsIgnoreCase("reset")) {
expMatch(server, sender, args[1], "0", false);
} else {
String match = args[0].trim();
if (args.length >= 2 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", ""))) {
match = args[1].trim();
expMatch(server, sender, match, args[0], true);
} else if (args.length == 1) {
match = args[0].trim();
} }
showMatch(server, sender, match); showExp(sender, user);
return;
}
ExpCommands cmd;
try {
cmd = ExpCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH));
} catch (Exception ex) {
throw new NotEnoughArgumentsException(ex);
}
if (!cmd.hasPermission(user)) {
user.sendMessage(tl("noAccessSubCommand", "/" + commandLabel + " " + cmd.name().toLowerCase(Locale.ENGLISH)));
return;
}
switch (cmd) {
case SET: {
if (args.length == 3 && cmd.hasOtherPermission(user)) {
loopOnlinePlayersConsumer(server,sender, false, true, args[1], player -> setExp(sender, player, args[2], false));
} else if (args.length == 2 && user != null) {
setExp(sender, user, args[1], false);
} else {
throw new NotEnoughArgumentsException();
}
return;
}
case GIVE: {
if (args.length == 3 && cmd.hasOtherPermission(user)) {
loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> setExp(sender, player, args[2], true));
} else if (args.length == 2 && user != null) {
setExp(sender, user, args[1], true);
} else {
throw new NotEnoughArgumentsException();
}
return;
}
case TAKE: {
if (args.length == 3 && cmd.hasOtherPermission(user)) {
loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> setExp(sender, player, "-" + args[2], true));
} else if (args.length == 2) {
setExp(sender, user, "-" + args[1], true);
} else {
throw new NotEnoughArgumentsException();
}
return;
}
case RESET: {
if (args.length == 2 && cmd.hasOtherPermission(user)) {
loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> setExp(sender, player, "0", false));
} else if (user != null) {
setExp(sender, user, "0", false);
} else {
throw new NotEnoughArgumentsException();
}
return;
}
case SHOW: {
if (args.length == 2 && (user == null || user.isAuthorized("essentials.exp.others"))) {
showExp(sender, getPlayer(server, sender, args[1]));
} else if (user != null) {
showExp(sender, user);
} else {
throw new NotEnoughArgumentsException();
}
return;
}
}
throw new NotEnoughArgumentsException(); //Should never happen but in the impossible chance it does...
}
private enum ExpCommands {
SET,
GIVE,
TAKE,
RESET,
SHOW(false);
private final boolean permCheck;
ExpCommands() {
permCheck = true;
}
ExpCommands(boolean perm) {
permCheck = perm;
}
boolean hasPermission(IUser user) {
return user == null || !permCheck || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH));
}
boolean hasOtherPermission(IUser user) {
return user == null || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH) + ".others");
} }
} }
private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException { private void showExp(final CommandSource sender, final IUser target) {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
showExp(sender, player);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void expMatch(final Server server, final CommandSource sender, final String match, String amount, final boolean give) throws NotEnoughArgumentsException, PlayerNotFoundException {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
setExp(sender, player, amount, give);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void showExp(final CommandSource sender, final User target) {
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()))); sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
} }
//TODO: Limit who can give negative exp? //TODO: Limit who can give negative exp?
private void setExp(final CommandSource sender, final User target, String strAmount, final boolean give) throws NotEnoughArgumentsException { private void setExp(final CommandSource sender, final IUser target, String strAmount, final boolean give) throws NotEnoughArgumentsException {
long amount; long amount;
strAmount = strAmount.toLowerCase(Locale.ENGLISH); strAmount = strAmount.toLowerCase(Locale.ENGLISH);
if (strAmount.contains("l")) { if (strAmount.contains("l")) {
@ -165,21 +161,18 @@ public class Commandexp extends EssentialsCommand {
sender.sendMessage(tl("expSet", target.getDisplayName(), amount)); sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
} }
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) { if (args.length == 1) {
List<String> options = Lists.newArrayList("show"); List<String> options = Lists.newArrayList("show");
if (user.isAuthorized("essentials.exp.set")) { for (ExpCommands cmd : ExpCommands.values()) {
options.add("set"); if (cmd.hasPermission(user)) {
} options.add(cmd.name().toLowerCase(Locale.ENGLISH));
if (user.isAuthorized("essentials.exp.give")) { }
options.add("give");
}
if (user.isAuthorized("essentials.exp.take")) {
options.add("take");
}
if (user.isAuthorized("essentials.exp.reset")) {
options.add("reset");
} }
return options; return options;
} else if (args.length == 2) { } else if (args.length == 2) {
@ -204,8 +197,11 @@ public class Commandexp extends EssentialsCommand {
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) { if (args.length == 1) {
// TODO: This seems somewhat buggy, both setting and showing - right now, ignoring that List<String> list = new ArrayList<>();
return Lists.newArrayList("set", "give", "show", "take", "reset"); for (ExpCommands cmd : ExpCommands.values()) {
list.add(cmd.name().toLowerCase(Locale.ENGLISH));
}
return list;
} else if (args.length == 2) { } else if (args.length == 2) {
if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) { if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", ""); String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", "");

View File

@ -18,7 +18,7 @@ public class Commandext extends EssentialsLoopCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -53,13 +53,9 @@ public class Commandfireball extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
String type = "fireball"; String type = args.length > 0 && types.containsKey(args[0]) ? args[0] : "fireball";
double speed = 2; double speed = 2;
boolean ride = false; boolean ride = args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride");
if (args.length > 0 && types.containsKey(args[0])) {
type = args[0];
}
if (args.length > 1) { if (args.length > 1) {
try { try {
@ -69,10 +65,6 @@ public class Commandfireball extends EssentialsCommand {
} }
} }
if (args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride")) {
ride = true;
}
if (!user.isAuthorized("essentials.fireball." + type)) { if (!user.isAuthorized("essentials.fireball." + type)) {
throw new Exception(tl("noPerm", "essentials.fireball." + type)); throw new Exception(tl("noPerm", "essentials.fireball." + type));
} }

View File

@ -43,79 +43,79 @@ public class Commandfirework extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
final ItemStack stack = user.getItemInHand(); final ItemStack stack = user.getItemInHand();
if (MaterialUtil.isFirework(stack.getType())) { if (!MaterialUtil.isFirework(stack.getType())) {
if (args.length > 0) { throw new Exception(tl("holdFirework"));
if (args[0].equalsIgnoreCase("clear")) { }
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects(); if (args[0].equalsIgnoreCase("clear")) {
stack.setItemMeta(fmeta); FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
user.sendMessage(tl("fireworkEffectsCleared")); fmeta.clearEffects();
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) { stack.setItemMeta(fmeta);
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); user.sendMessage(tl("fireworkEffectsCleared"));
try { } else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) {
int power = Integer.parseInt(args[1]); FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.setPower(power > 3 ? 4 : power); try {
} catch (NumberFormatException e) { int power = Integer.parseInt(args[1]);
throw new Exception(tl("invalidFireworkFormat", args[1], args[0])); fmeta.setPower(power > 3 ? 4 : power);
} } catch (NumberFormatException e) {
stack.setItemMeta(fmeta); throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
} else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) { }
int amount = 1; stack.setItemMeta(fmeta);
boolean direction = false; } else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) {
if (args.length > 1) { int amount = 1;
if (NumberUtil.isInt(args[1])) { boolean direction = false;
final int serverLimit = ess.getSettings().getSpawnMobLimit(); if (args.length > 1) {
amount = Integer.parseInt(args[1]); if (NumberUtil.isInt(args[1])) {
if (amount > serverLimit) { final int serverLimit = ess.getSettings().getSpawnMobLimit();
amount = serverLimit; amount = Integer.parseInt(args[1]);
user.sendMessage(tl("mobSpawnLimit")); if (amount > serverLimit) {
} amount = serverLimit;
} else { user.sendMessage(tl("mobSpawnLimit"));
direction = true;
}
}
for (int i = 0; i < amount; i++) {
Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK);
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
if (direction) {
final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070);
if (fmeta.getPower() > 1) {
fmeta.setPower(1);
}
firework.setVelocity(vector);
}
firework.setFireworkMeta(fmeta);
} }
} else { } else {
final MetaItemStack mStack = new MetaItemStack(stack); direction = true;
for (String arg : args) {
try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (Exception e) {
user.sendMessage(tl("fireworkSyntax"));
throw e;
}
}
if (mStack.isValidFirework()) {
FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges"));
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
} else {
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
}
} }
} else { }
throw new NotEnoughArgumentsException(); for (int i = 0; i < amount; i++) {
Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK);
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
if (direction) {
final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070);
if (fmeta.getPower() > 1) {
fmeta.setPower(1);
}
firework.setVelocity(vector);
}
firework.setFireworkMeta(fmeta);
} }
} else { } else {
throw new Exception(tl("holdFirework")); final MetaItemStack mStack = new MetaItemStack(stack);
for (String arg : args) {
try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (Exception e) {
user.sendMessage(tl("fireworkSyntax"));
throw e;
}
}
if (mStack.isValidFirework()) {
FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges"));
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
} else {
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
}
} }
} }

View File

@ -27,9 +27,8 @@ public class Commandfly extends EssentialsToggleCommand {
if (enabled == null) { if (enabled == null) {
enabled = !user.getBase().getAllowFlight(); enabled = !user.getBase().getAllowFlight();
} }
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled);
FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, controller, enabled);
ess.getServer().getPluginManager().callEvent(event); ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {

View File

@ -1,11 +1,11 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -14,22 +14,19 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandgamemode extends EssentialsCommand { public class Commandgamemode extends EssentialsLoopCommand {
public Commandgamemode() { public Commandgamemode() {
super("gamemode"); super("gamemode");
} }
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
GameMode gameMode;
if (args.length == 0) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} else if (args.length == 1) { } else if (args.length == 1) {
gameMode = matchGameMode(commandLabel); loopOnlinePlayersConsumer(server, sender, false, true, args[0], user -> setUserGamemode(sender, matchGameMode(commandLabel), user));
gamemodeOtherPlayers(server, sender, gameMode, args[0]);
} else if (args.length == 2) { } else if (args.length == 2) {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); loopOnlinePlayersConsumer(server, sender, false, true, args[1], user -> setUserGamemode(sender, matchGameMode(commandLabel), user));
gamemodeOtherPlayers(server, sender, gameMode, args[1]);
} }
} }
@ -40,16 +37,14 @@ public class Commandgamemode extends EssentialsCommand {
if (args.length == 0) { if (args.length == 0) {
gameMode = matchGameMode(commandLabel); gameMode = matchGameMode(commandLabel);
} else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) { } else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); loopOnlinePlayersConsumer(server, user.getSource(), false, true, args[1], player -> setUserGamemode(user.getSource(), matchGameMode(args[0].toLowerCase(Locale.ENGLISH)), player));
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[1]);
return; return;
} else { } else {
try { try {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
} catch (NotEnoughArgumentsException e) { } catch (NotEnoughArgumentsException e) {
if (user.isAuthorized("essentials.gamemode.others")) { if (user.isAuthorized("essentials.gamemode.others")) {
gameMode = matchGameMode(commandLabel); loopOnlinePlayersConsumer(server, user.getSource(), false, true, args[0], player -> setUserGamemode(user.getSource(), matchGameMode(commandLabel), player));
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[0]);
return; return;
} }
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
@ -60,7 +55,7 @@ public class Commandgamemode extends EssentialsCommand {
gameMode = user.getBase().getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getBase().getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL; gameMode = user.getBase().getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getBase().getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL;
} }
if (!canChangeToMode(user, gameMode)) { if (isProhibitedChange(user, gameMode)) {
user.sendMessage(tl("cantGamemode", gameMode.name())); user.sendMessage(tl("cantGamemode", gameMode.name()));
return; return;
} }
@ -69,36 +64,23 @@ public class Commandgamemode extends EssentialsCommand {
user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName()));
} }
private void gamemodeOtherPlayers(final Server server, final CommandSource sender, final GameMode gameMode, final String name) throws NotEnoughArgumentsException, PlayerNotFoundException { private void setUserGamemode(final CommandSource sender, final GameMode gameMode, final User user) throws NotEnoughArgumentsException {
if (name.trim().length() < 2 || gameMode == null) { if (gameMode == null) {
throw new NotEnoughArgumentsException(tl("gameModeInvalid")); throw new NotEnoughArgumentsException(tl("gameModeInvalid"));
} }
if (sender.isPlayer() && !canChangeToMode(ess.getUser(sender.getPlayer()), gameMode)) { if (sender.isPlayer() && isProhibitedChange(sender.getUser(ess), gameMode)) {
sender.sendMessage(tl("cantGamemode", gameMode.name())); sender.sendMessage(tl("cantGamemode", gameMode.name()));
return; return;
} }
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); user.getBase().setGameMode(gameMode);
boolean foundUser = false; sender.sendMessage(tl("gameMode", tl(gameMode.toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName()));
final List<Player> matchedPlayers = server.matchPlayer(name);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
player.getBase().setGameMode(gameMode);
sender.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName()));
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
} }
// essentials.gamemode will let them change to any but essentials.gamemode.survival would only let them change to survival. // essentials.gamemode will let them change to any but essentials.gamemode.survival would only let them change to survival.
private boolean canChangeToMode(User user, GameMode to) { private boolean isProhibitedChange(IUser user, GameMode to) {
return user.isAuthorized("essentials.gamemode.all") || user.isAuthorized("essentials.gamemode." + to.name().toLowerCase()); return user != null && !user.isAuthorized("essentials.gamemode.all") && !user.isAuthorized("essentials.gamemode." + to.name().toLowerCase());
} }
private GameMode matchGameMode(String modeString) throws NotEnoughArgumentsException { private GameMode matchGameMode(String modeString) throws NotEnoughArgumentsException {
@ -109,11 +91,9 @@ public class Commandgamemode extends EssentialsCommand {
mode = GameMode.SURVIVAL; mode = GameMode.SURVIVAL;
} else if (modeString.equalsIgnoreCase("gma") || modeString.equalsIgnoreCase("egma") || modeString.contains("advent") || modeString.equalsIgnoreCase("2") || modeString.equalsIgnoreCase("a")) { } else if (modeString.equalsIgnoreCase("gma") || modeString.equalsIgnoreCase("egma") || modeString.contains("advent") || modeString.equalsIgnoreCase("2") || modeString.equalsIgnoreCase("a")) {
mode = GameMode.ADVENTURE; mode = GameMode.ADVENTURE;
} else if (modeString.equalsIgnoreCase("gmt") || modeString.equalsIgnoreCase("egmt") || modeString.contains("toggle") || modeString.contains("cycle") || modeString.equalsIgnoreCase("t")) {
mode = null;
} else if (modeString.equalsIgnoreCase("gmsp") || modeString.equalsIgnoreCase("egmsp") || modeString.contains("spec") || modeString.equalsIgnoreCase("3") || modeString.equalsIgnoreCase("sp")) { } else if (modeString.equalsIgnoreCase("gmsp") || modeString.equalsIgnoreCase("egmsp") || modeString.contains("spec") || modeString.equalsIgnoreCase("3") || modeString.equalsIgnoreCase("sp")) {
mode = GameMode.SPECTATOR; mode = GameMode.SPECTATOR;
} else { } else if (!modeString.equalsIgnoreCase("gmt") && !modeString.equalsIgnoreCase("egmt") && !modeString.contains("toggle") && !modeString.contains("cycle") && !modeString.equalsIgnoreCase("t")) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
return mode; return mode;
@ -159,4 +139,9 @@ public class Commandgamemode extends EssentialsCommand {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
} }

View File

@ -19,7 +19,7 @@ import java.util.Map;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandgive extends EssentialsCommand { public class Commandgive extends EssentialsLoopCommand {
public Commandgive() { public Commandgive() {
super("give"); super("give");
} }
@ -37,8 +37,6 @@ public class Commandgive extends EssentialsCommand {
throw new Exception(tl("cantSpawnItem", itemname)); throw new Exception(tl("cantSpawnItem", itemname));
} }
final User giveTo = getPlayer(server, sender, args, 0);
try { try {
if (args.length > 3 && NumberUtil.isInt(args[2]) && NumberUtil.isInt(args[3])) { if (args.length > 3 && NumberUtil.isInt(args[2]) && NumberUtil.isInt(args[3])) {
stack.setAmount(Integer.parseInt(args[2])); stack.setAmount(Integer.parseInt(args[2]));
@ -47,7 +45,7 @@ public class Commandgive extends EssentialsCommand {
stack.setAmount(Integer.parseInt(args[2])); stack.setAmount(Integer.parseInt(args[2]));
} else if (ess.getSettings().getDefaultStackSize() > 0) { } else if (ess.getSettings().getDefaultStackSize() > 0) {
stack.setAmount(ess.getSettings().getDefaultStackSize()); stack.setAmount(ess.getSettings().getDefaultStackSize());
} else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) { } else if (ess.getSettings().getOversizedStackSize() > 0 && sender.isAuthorized("essentials.oversizedstacks", ess)) {
stack.setAmount(ess.getSettings().getOversizedStackSize()); stack.setAmount(ess.getSettings().getOversizedStackSize());
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@ -79,28 +77,29 @@ public class Commandgive extends EssentialsCommand {
} }
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
sender.sendMessage(tl("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName()));
Map<Integer, ItemStack> leftovers;
if (giveTo.isAuthorized("essentials.oversizedstacks")) {
leftovers = InventoryWorkaround.addOversizedItems(giveTo.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack);
} else {
leftovers = InventoryWorkaround.addItems(giveTo.getBase().getInventory(), stack);
}
boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull(); boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull();
final ItemStack finalStack = stack;
loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> {
sender.sendMessage(tl("giveSpawn", finalStack.getAmount(), itemName, player.getDisplayName()));
Map<Integer, ItemStack> leftovers;
for (ItemStack item : leftovers.values()) { if (player.isAuthorized("essentials.oversizedstacks")) {
if (isDropItemsIfFull) { leftovers = InventoryWorkaround.addOversizedItems(player.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), finalStack);
World w = giveTo.getWorld();
w.dropItemNaturally(giveTo.getLocation(), item);
} else { } else {
sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, giveTo.getDisplayName())); leftovers = InventoryWorkaround.addItems(player.getBase().getInventory(), finalStack);
} }
}
giveTo.getBase().updateInventory(); for (ItemStack item : leftovers.values()) {
if (isDropItemsIfFull) {
World w = player.getWorld();
w.dropItemNaturally(player.getLocation(), item);
} else {
sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, player.getDisplayName()));
}
}
player.getBase().updateInventory();
});
} }
@Override @Override
@ -117,4 +116,9 @@ public class Commandgive extends EssentialsCommand {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
} }

View File

@ -29,8 +29,7 @@ public class Commandgod extends EssentialsToggleCommand {
enabled = !user.isGodModeEnabled(); enabled = !user.isGodModeEnabled();
} }
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled);
final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(user, controller, enabled);
ess.getServer().getPluginManager().callEvent(godEvent); ess.getServer().getPluginManager().callEvent(godEvent);
if (!godEvent.isCancelled()) { if (!godEvent.isCancelled()) {
user.setGodModeEnabled(enabled); user.setGodModeEnabled(enabled);

View File

@ -52,42 +52,46 @@ public class Commandhat extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0"))) { if (args.length == 0 || (!args[0].contains("rem") && !args[0].contains("off") && !args[0].equalsIgnoreCase("0"))) {
final ItemStack hand = user.getItemInHand();
if (hand == null || hand.getType() == Material.AIR) {
user.sendMessage(tl("hatFail"));
return;
}
if (user.isAuthorized("essentials.hat.prevent-type." + hand.getType().name().toLowerCase())) {
user.sendMessage(tl("hatFail"));
return;
}
if (hand.getType().getMaxDurability() != 0) {
user.sendMessage(tl("hatArmor"));
return;
}
final PlayerInventory inv = user.getBase().getInventory(); final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet(); final ItemStack head = inv.getHelmet();
if (head == null || head.getType() == Material.AIR) { if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head != null && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatEmpty"));
} else if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatCurse")); user.sendMessage(tl("hatCurse"));
} else { return;
final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air);
InventoryWorkaround.addItems(user.getBase().getInventory(), head);
user.sendMessage(tl("hatRemoved"));
} }
inv.setHelmet(hand);
inv.setItemInHand(head);
user.sendMessage(tl("hatPlaced"));
return;
}
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();
if (head == null || head.getType() == Material.AIR) {
user.sendMessage(tl("hatEmpty"));
} else if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatCurse"));
} else { } else {
final ItemStack hand = user.getItemInHand(); final ItemStack air = new ItemStack(Material.AIR);
if (hand != null && hand.getType() != Material.AIR) { inv.setHelmet(air);
if (user.isAuthorized("essentials.hat.prevent-type." + hand.getType().name().toLowerCase())) { InventoryWorkaround.addItems(user.getBase().getInventory(), head);
user.sendMessage(tl("hatFail")); user.sendMessage(tl("hatRemoved"));
return;
}
if (hand.getType().getMaxDurability() == 0) {
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();
if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head != null && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatCurse"));
return;
}
inv.setHelmet(hand);
inv.setItemInHand(head);
user.sendMessage(tl("hatPlaced"));
} else {
user.sendMessage(tl("hatArmor"));
}
} else {
user.sendMessage(tl("hatFail"));
}
} }
} }

View File

@ -30,7 +30,7 @@ public class Commandheal extends EssentialsLoopCommand {
return; return;
} }
healPlayer(user); updatePlayer(server, user.getSource(), user, args);
} }
@Override @Override
@ -43,45 +43,41 @@ public class Commandheal extends EssentialsLoopCommand {
} }
@Override @Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException { protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws PlayerExemptException {
try { try {
healPlayer(player); final Player player = user.getBase();
sender.sendMessage(tl("healOther", player.getDisplayName()));
if (player.getHealth() == 0) {
throw new PlayerExemptException(tl("healDead"));
}
final double amount = player.getMaxHealth() - player.getHealth();
final EntityRegainHealthEvent erhe = new EntityRegainHealthEvent(player, amount, RegainReason.CUSTOM);
ess.getServer().getPluginManager().callEvent(erhe);
if (erhe.isCancelled()) {
throw new QuietAbortException();
}
double newAmount = player.getHealth() + erhe.getAmount();
if (newAmount > player.getMaxHealth()) {
newAmount = player.getMaxHealth();
}
player.setHealth(newAmount);
player.setFoodLevel(20);
player.setFireTicks(0);
user.sendMessage(tl("heal"));
if (ess.getSettings().isRemovingEffectsOnHeal()) {
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
}
sender.sendMessage(tl("healOther", user.getDisplayName()));
} catch (QuietAbortException e) { } catch (QuietAbortException e) {
//Handle Quietly //Handle Quietly
} }
} }
private void healPlayer(final User user) throws PlayerExemptException, QuietAbortException {
final Player player = user.getBase();
if (player.getHealth() == 0) {
throw new PlayerExemptException(tl("healDead"));
}
final double amount = player.getMaxHealth() - player.getHealth();
final EntityRegainHealthEvent erhe = new EntityRegainHealthEvent(player, amount, RegainReason.CUSTOM);
ess.getServer().getPluginManager().callEvent(erhe);
if (erhe.isCancelled()) {
throw new QuietAbortException();
}
double newAmount = player.getHealth() + erhe.getAmount();
if (newAmount > player.getMaxHealth()) {
newAmount = player.getMaxHealth();
}
player.setHealth(newAmount);
player.setFoodLevel(20);
player.setFireTicks(0);
user.sendMessage(tl("heal"));
if (ess.getSettings().isRemovingEffectsOnHeal()) {
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
}
}
@Override @Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.heal.others")) { if (args.length == 1 && user.isAuthorized("essentials.heal.others")) {

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
@ -20,7 +21,7 @@ public class Commandhelpop extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
user.setDisplayNick(); user.setDisplayNick();
final String message = sendMessage(server, user.getSource(), user.getDisplayName(), args); final String message = sendMessage(server, user.getDisplayName(), args);
if (!user.isAuthorized("essentials.helpop.receive")) { if (!user.isAuthorized("essentials.helpop.receive")) {
user.sendMessage(message); user.sendMessage(message);
} }
@ -28,10 +29,10 @@ public class Commandhelpop extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
sendMessage(server, sender, Console.NAME, args); sendMessage(server, Console.NAME, args);
} }
private String sendMessage(final Server server, final CommandSource sender, final String from, final String[] args) throws Exception { private String sendMessage(final Server server, final String from, final String[] args) throws Exception {
if (args.length < 1) { if (args.length < 1) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -43,6 +44,6 @@ public class Commandhelpop extends EssentialsCommand {
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
return null; // Use vanilla handler for message return Collections.emptyList();
} }
} }

View File

@ -17,7 +17,7 @@ public class Commandignore extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (UUID uuid : user._getIgnoredPlayers()) { for (UUID uuid : user._getIgnoredPlayers()) {
User curUser = ess.getUser(uuid); User curUser = ess.getUser(uuid);
@ -27,25 +27,27 @@ public class Commandignore extends EssentialsCommand {
} }
String ignoredList = sb.toString().trim(); String ignoredList = sb.toString().trim();
user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored")); user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored"));
return;
}
User player;
try {
player = getPlayer(server, args, 0, true, true);
} catch (PlayerNotFoundException ex) {
player = ess.getOfflineUser(args[0]);
}
if (player == null) {
throw new PlayerNotFoundException();
}
if (player.isIgnoreExempt()) {
user.sendMessage(tl("ignoreExempt"));
} else if (user.isIgnoredPlayer(player)) {
user.setIgnoredPlayer(player, false);
user.sendMessage(tl("unignorePlayer", player.getName()));
} else { } else {
User player; user.setIgnoredPlayer(player, true);
try { user.sendMessage(tl("ignorePlayer", player.getName()));
player = getPlayer(server, args, 0, true, true);
} catch (PlayerNotFoundException ex) {
player = ess.getOfflineUser(args[0]);
}
if (player == null) {
throw new PlayerNotFoundException();
}
if (player.isIgnoreExempt()) {
user.sendMessage(tl("ignoreExempt"));
} else if (user.isIgnoredPlayer(player)) {
user.setIgnoredPlayer(player, false);
user.sendMessage(tl("unignorePlayer", player.getName()));
} else {
user.setIgnoredPlayer(player, true);
user.sendMessage(tl("ignorePlayer", player.getName()));
}
} }
} }

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
@ -19,9 +18,7 @@ public class Commandinfo extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick(); ess.getUser(sender.getPlayer()).setDisplayNick();
} }
final IText input = new TextInput(sender, "info", true, ess); final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "info", true, ess), sender, ess));
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
} }
} }

View File

@ -22,7 +22,7 @@ public class Commanditem extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -21,7 +21,7 @@ public class Commanditemdb extends EssentialsCommand {
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
ItemStack itemStack = null; ItemStack itemStack = null;
boolean itemHeld = false; boolean itemHeld = false;
if (args.length < 1) { if (args.length == 0) {
if (sender.isPlayer() && sender.getPlayer() != null) { if (sender.isPlayer() && sender.getPlayer() != null) {
itemHeld = true; itemHeld = true;
itemStack = ess.getUser(sender.getPlayer()).getItemInHand(); itemStack = ess.getUser(sender.getPlayer()).getItemInHand();

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
@ -19,13 +20,15 @@ public class Commanditemname extends EssentialsCommand {
@Override @Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
ItemStack item = user.getBase().getItemInHand(); ItemStack item = user.getBase().getItemInHand();
if (item.getType().name().contains("AIR")) { if (item.getType() == Material.AIR) {
user.sendMessage(tl("itemnameInvalidItem", item.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '))); user.sendMessage(tl("itemnameInvalidItem", item.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ')));
return; return;
} }
String name = FormatUtil.formatString(user, "essentials.itemname", getFinalArg(args, 0)).trim(); String name = FormatUtil.formatString(user, "essentials.itemname", getFinalArg(args, 0)).trim();
if (name.isEmpty()) name = null; if (name.isEmpty()) {
name = null;
}
ItemMeta im = item.getItemMeta(); ItemMeta im = item.getItemMeta();
im.setDisplayName(name); im.setDisplayName(name);

View File

@ -14,7 +14,7 @@ public class Commandjails extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (ess.getJails().getCount() < 1) { if (ess.getJails().getCount() == 0) {
sender.sendMessage(tl("noJailsDefined")); sender.sendMessage(tl("noJailsDefined"));
} else { } else {
sender.sendMessage(tl("jailList", StringUtil.joinList(" ", ess.getJails().getList()))); sender.sendMessage(tl("jailList", StringUtil.joinList(" ", ess.getJails().getList())));

View File

@ -24,10 +24,10 @@ public class Commandjump extends EssentialsCommand {
if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) {
if (user.isFlyClickJump()) { if (user.isFlyClickJump()) {
user.setRightClickJump(false); user.setRightClickJump(false);
user.sendMessage("Flying wizard mode disabled"); user.sendMessage(tl("jumpEasterDisable"));
} else { } else {
user.setRightClickJump(true); user.setRightClickJump(true);
user.sendMessage("Enabling flying wizard mode"); user.sendMessage(tl("jumpEasterEnable"));
} }
return; return;
} }

View File

@ -19,7 +19,7 @@ public class Commandkill extends EssentialsLoopCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -27,12 +27,9 @@ public class Commandkit extends EssentialsCommand {
user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException(); throw new NoChargeException();
} else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) { } else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) {
final User userTo = getPlayer(server, user, args, 1); giveKits(getPlayer(server, user, args, 1), user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim());
final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKits(userTo, user, kitNames);
} else { } else {
final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim(); giveKits(user, user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim());
giveKits(user, user, kitNames);
} }
} }
@ -44,11 +41,9 @@ public class Commandkit extends EssentialsCommand {
throw new NoChargeException(); throw new NoChargeException();
} else { } else {
final User userTo = getPlayer(server, args, 1, true, false); final User userTo = getPlayer(server, args, 1, true, false);
final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(",");
for (final String kitName : kits) { for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) {
final Kit kit = new Kit(kitName, ess); new Kit(kitName, ess).expandItems(userTo);
kit.expandItems(userTo);
sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName())); sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName()));
userTo.sendMessage(tl("kitReceive", kitName)); userTo.sendMessage(tl("kitReceive", kitName));
@ -60,11 +55,10 @@ public class Commandkit extends EssentialsCommand {
if (kitNames.isEmpty()) { if (kitNames.isEmpty()) {
throw new Exception(tl("kitNotFound")); throw new Exception(tl("kitNotFound"));
} }
String[] kitList = kitNames.split(",");
List<Kit> kits = new ArrayList<>(); List<Kit> kits = new ArrayList<>();
for (final String kitName : kitList) { for (final String kitName : kitNames.split(",")) {
if (kitName.isEmpty()) { if (kitName.isEmpty()) {
throw new Exception(tl("kitNotFound")); throw new Exception(tl("kitNotFound"));
} }

View File

@ -4,7 +4,6 @@ import com.earth2me.essentials.Mob;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Cat; import org.bukkit.entity.Cat;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Ocelot; import org.bukkit.entity.Ocelot;
@ -22,45 +21,32 @@ public class Commandkittycannon extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final Entity ocelot = Mob.CAT.getType() == null ? spawnOcelot(user.getWorld(), server, user) : spawnCat(user.getWorld(), server, user); final Entity ocelot = Mob.CAT.getType() == null ? spawnOcelot(server, user) : spawnCat(server, user);
ess.scheduleSyncDelayedTask(() -> {
class KittyCannonExplodeTask implements Runnable { final Location loc = ocelot.getLocation();
@Override ocelot.remove();
public void run() { loc.getWorld().createExplosion(loc, 0F);
final Location loc = ocelot.getLocation(); }, 20);
ocelot.remove();
loc.getWorld().createExplosion(loc, 0F);
}
}
ess.scheduleSyncDelayedTask(new KittyCannonExplodeTask(), 20);
} }
private static Ocelot spawnOcelot(World world, Server server, User user) throws Mob.MobException { private static Ocelot spawnOcelot(Server server, User user) throws Mob.MobException {
final Ocelot ocelot = (Ocelot) Mob.OCELOT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); final Ocelot ocelot = (Ocelot) Mob.OCELOT.spawn(user.getWorld(), server, user.getBase().getEyeLocation());
if (ocelot == null) {
return null;
}
final int i = random.nextInt(Ocelot.Type.values().length); final int i = random.nextInt(Ocelot.Type.values().length);
ocelot.setCatType(Ocelot.Type.values()[i]); ocelot.setCatType(Ocelot.Type.values()[i]);
((Tameable) ocelot).setTamed(true); ((Tameable) ocelot).setTamed(true);
ocelot.setBaby(); ocelot.setBaby();
ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
return ocelot; return ocelot;
} }
private static Entity spawnCat(World world, Server server, User user) throws Mob.MobException { private static Entity spawnCat(Server server, User user) throws Mob.MobException {
final Cat cat = (Cat) Mob.CAT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); final Cat cat = (Cat) Mob.CAT.spawn(user.getWorld(), server, user.getBase().getEyeLocation());
if (cat == null) {
return null;
}
final int i = random.nextInt(Cat.Type.values().length); final int i = random.nextInt(Cat.Type.values().length);
cat.setCatType(Cat.Type.values()[i]); cat.setCatType(Cat.Type.values()[i]);
cat.setTamed(true); cat.setTamed(true);
cat.setBaby(); cat.setBaby();
cat.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); cat.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
return cat; return cat;
} }
} }

View File

@ -3,55 +3,54 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.LightningStrike; import org.bukkit.entity.LightningStrike;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandlightning extends EssentialsLoopCommand { public class Commandlightning extends EssentialsLoopCommand {
int power = 5;
public Commandlightning() { public Commandlightning() {
super("lightning"); super("lightning");
} }
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (sender.isPlayer()) { if (args.length == 0) {
User user = ess.getUser(sender.getPlayer()); if (sender.isPlayer() || !sender.isAuthorized("essentials.lightning.others", ess)) {
if ((args.length < 1 || !user.isAuthorized("essentials.lightning.others"))) { sender.getPlayer().getWorld().strikeLightning(sender.getPlayer().getTargetBlock(null, 600).getLocation());
user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation());
return; return;
} }
throw new NotEnoughArgumentsException();
} }
int power = 5;
if (args.length > 1) { if (args.length > 1) {
try { try {
power = Integer.parseInt(args[1]); power = Integer.parseInt(args[1]);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
} }
} }
final int finalPower = power;
loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> {
sender.sendMessage(tl("lightningUse", player.getDisplayName()));
final LightningStrike strike = player.getBase().getWorld().strikeLightningEffect(player.getBase().getLocation());
if (!player.isGodModeEnabled()) {
player.getBase().damage(finalPower, strike);
}
if (ess.getSettings().warnOnSmite()) {
player.sendMessage(tl("lightningSmited"));
}
});
loopOnlinePlayers(server, sender, true, true, args[0], null); loopOnlinePlayers(server, sender, true, true, args[0], null);
} }
@Override @Override
protected void updatePlayer(final Server server, final CommandSource sender, final User matchUser, final String[] args) { protected void updatePlayer(final Server server, final CommandSource sender, final User matchUser, final String[] args) {
sender.sendMessage(tl("lightningUse", matchUser.getDisplayName()));
final LightningStrike strike = matchUser.getBase().getWorld().strikeLightningEffect(matchUser.getBase().getLocation());
if (!matchUser.isGodModeEnabled()) {
matchUser.getBase().damage(power, strike);
}
if (ess.getSettings().warnOnSmite()) {
matchUser.sendMessage(tl("lightningSmited"));
}
} }
@Override @Override
@ -69,7 +68,7 @@ public class Commandlightning extends EssentialsLoopCommand {
if (args.length == 1) { if (args.length == 1) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else if (args.length == 2) { } else if (args.length == 2) {
return Lists.newArrayList(Integer.toString(this.power)); return Lists.newArrayList("5");
} else { } else {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -78,7 +78,7 @@ public class Commandlist extends EssentialsCommand {
outputUserList = PlayerList.getMergedList(ess, playerList, configGroup); outputUserList = PlayerList.getMergedList(ess, playerList, configGroup);
// If we have no users, than we don't need to continue parsing this group // If we have no users, than we don't need to continue parsing this group
if (outputUserList == null || outputUserList.isEmpty()) { if (outputUserList.isEmpty()) {
continue; continue;
} }

View File

@ -26,7 +26,6 @@ public class Commandmail extends EssentialsCommand {
super("mail"); super("mail");
} }
//TODO: Tidy this up / TL these errors.
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) {

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
@ -19,9 +18,7 @@ public class Commandmotd extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick(); ess.getUser(sender.getPlayer()).setDisplayNick();
} }
final IText input = new TextInput(sender, "motd", true, ess); final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "motd", true, ess), sender, ess));
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
} }
} }

View File

@ -13,19 +13,18 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandmsg extends EssentialsLoopCommand { public class Commandmsg extends EssentialsLoopCommand {
public Commandmsg() { public Commandmsg() {
super("msg"); super("msg");
} }
@Override @Override
public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty()) { if (args.length < 2) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
String message = getFinalArg(args, 1); String message = getFinalArg(args, 1);
boolean canWildcard; boolean canWildcard = sender.isAuthorized("essentials.msg.multiple", ess);
if (sender.isPlayer()) { if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer()); User user = ess.getUser(sender.getPlayer());
if (user.isMuted()) { if (user.isMuted()) {
@ -36,10 +35,8 @@ public class Commandmsg extends EssentialsLoopCommand {
throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
} }
message = FormatUtil.formatMessage(user, "essentials.msg", message); message = FormatUtil.formatMessage(user, "essentials.msg", message);
canWildcard = user.isAuthorized("essentials.msg.multiple");
} else { } else {
message = FormatUtil.replaceFormat(message); message = FormatUtil.replaceFormat(message);
canWildcard = true;
} }
// Sending messages to console // Sending messages to console
@ -49,7 +46,7 @@ public class Commandmsg extends EssentialsLoopCommand {
return; return;
} }
loopOnlinePlayers(server, sender, canWildcard, canWildcard, args[0], new String[]{message}); loopOnlinePlayers(server, sender, false, canWildcard, args[0], new String[]{message});
} }
@Override @Override

View File

@ -32,14 +32,12 @@ public class Commandmute extends EssentialsCommand {
nomatch = true; nomatch = true;
user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); user = ess.getUser(new OfflinePlayer(args[0], ess.getServer()));
} }
if (!user.getBase().isOnline()) { if (!user.getBase().isOnline() && sender.isPlayer()) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.offline")) { if (!sender.isAuthorized("essentials.mute.offline", ess)) {
throw new Exception(tl("muteExemptOffline")); throw new Exception(tl("muteExemptOffline"));
} }
} else { } else if (user.isAuthorized("essentials.mute.exempt")) {
if (user.isAuthorized("essentials.mute.exempt") && sender.isPlayer()) {
throw new Exception(tl("muteExempt")); throw new Exception(tl("muteExempt"));
}
} }
long muteTimestamp = 0; long muteTimestamp = 0;

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
@ -59,7 +60,7 @@ public class Commandnear extends EssentialsCommand {
if (otherUser == null || !user.isAuthorized("essentials.near.others")) { if (otherUser == null || !user.isAuthorized("essentials.near.others")) {
otherUser = user; otherUser = user;
} }
user.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); user.sendMessage(tl("nearbyPlayers", getLocal(otherUser, radius)));
} }
@Override @Override
@ -75,10 +76,10 @@ public class Commandnear extends EssentialsCommand {
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
} }
} }
sender.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); sender.sendMessage(tl("nearbyPlayers", getLocal(otherUser, radius)));
} }
private String getLocal(final Server server, final User user, final long radius) { private String getLocal(final User user, final long radius) {
final Location loc = user.getLocation(); final Location loc = user.getLocation();
final World world = loc.getWorld(); final World world = loc.getWorld();
final StringBuilder output = new StringBuilder(); final StringBuilder output = new StringBuilder();
@ -106,7 +107,10 @@ public class Commandnear extends EssentialsCommand {
output.append(", "); output.append(", ");
} }
User nearbyPlayer = nearbyPlayers.poll(); User nearbyPlayer = nearbyPlayers.poll();
output.append(nearbyPlayer.getDisplayName()).append("§f(§4").append((long) nearbyPlayer.getLocation().distance(loc)).append("m§f)"); if (nearbyPlayer == null) {
continue;
}
output.append(nearbyPlayer.getDisplayName()).append(ChatColor.WHITE + "(" + ChatColor.RED).append((long) nearbyPlayer.getLocation().distance(loc)).append("m" + ChatColor.WHITE + ")");
} }
return output.length() > 1 ? output.toString() : tl("none"); return output.length() > 1 ? output.toString() : tl("none");

View File

@ -11,6 +11,7 @@ import org.bukkit.entity.Player;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.function.Predicate;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -30,12 +31,10 @@ public class Commandnick extends EssentialsLoopCommand {
} }
if (args.length > 1 && user.isAuthorized("essentials.nick.others")) { if (args.length > 1 && user.isAuthorized("essentials.nick.others")) {
final String[] nickname = formatNickname(user, args[1]).split(" "); loopOfflinePlayers(server, user.getSource(), false, true, args[0], formatNickname(user, args[1]).split(" "));
loopOfflinePlayers(server, user.getSource(), false, true, args[0], nickname);
user.sendMessage(tl("nickChanged")); user.sendMessage(tl("nickChanged"));
} else { } else {
final String[] nickname = formatNickname(user, args[0]).split(" "); updatePlayer(server, user.getSource(), user, formatNickname(user, args[0]).split(" "));
updatePlayer(server, user.getSource(), user, nickname);
} }
} }
@ -47,8 +46,7 @@ public class Commandnick extends EssentialsLoopCommand {
if (!ess.getSettings().changeDisplayName()) { if (!ess.getSettings().changeDisplayName()) {
throw new Exception(tl("nickDisplayName")); throw new Exception(tl("nickDisplayName"));
} }
final String[] nickname = formatNickname(null, args[1]).split(" "); loopOfflinePlayers(server, sender, false, true, args[0], formatNickname(null, args[1]).split(" "));
loopOfflinePlayers(server, sender, false, true, args[0], nickname);
sender.sendMessage(tl("nickChanged")); sender.sendMessage(tl("nickChanged"));
} }
@ -59,13 +57,12 @@ public class Commandnick extends EssentialsLoopCommand {
setNickname(server, sender, target, null); setNickname(server, sender, target, null);
target.sendMessage(tl("nickNoMore")); target.sendMessage(tl("nickNoMore"));
} else if (target.getName().equalsIgnoreCase(nick)) { } else if (target.getName().equalsIgnoreCase(nick)) {
String oldName = target.getDisplayName();
setNickname(server, sender, target, nick); setNickname(server, sender, target, nick);
if (!target.getDisplayName().equalsIgnoreCase(oldName)) { if (!target.getDisplayName().equalsIgnoreCase(target.getDisplayName())) {
target.sendMessage(tl("nickNoMore")); target.sendMessage(tl("nickNoMore"));
} }
target.sendMessage(tl("nickSet", target.getDisplayName())); target.sendMessage(tl("nickSet", target.getDisplayName()));
} else if (nickInUse(server, target, nick)) { } else if (nickInUse(target, nick)) {
throw new NotEnoughArgumentsException(tl("nickInUse")); throw new NotEnoughArgumentsException(tl("nickInUse"));
} else { } else {
setNickname(server, sender, target, nick); setNickname(server, sender, target, nick);
@ -90,15 +87,19 @@ public class Commandnick extends EssentialsLoopCommand {
} }
private boolean isNickBanned(String newNick) { private boolean isNickBanned(String newNick) {
return ess.getSettings().getNickBlacklist().stream() for (Predicate<String> predicate : ess.getSettings().getNickBlacklist()) {
.anyMatch(entry -> entry.test(newNick)); if (predicate.test(newNick)) {
return true;
}
}
return false;
} }
private int getNickLength(final String nick) { private int getNickLength(final String nick) {
return ess.getSettings().ignoreColorsInMaxLength() ? ChatColor.stripColor(nick).length() : nick.length(); return ess.getSettings().ignoreColorsInMaxLength() ? ChatColor.stripColor(nick).length() : nick.length();
} }
private boolean nickInUse(final Server server, final User target, String nick) { private boolean nickInUse(final User target, String nick) {
final String lowerNick = FormatUtil.stripFormat(nick.toLowerCase(Locale.ENGLISH)); final String lowerNick = FormatUtil.stripFormat(nick.toLowerCase(Locale.ENGLISH));
for (final Player onlinePlayer : ess.getOnlinePlayers()) { for (final Player onlinePlayer : ess.getOnlinePlayers()) {
if (target.getBase().getName().equals(onlinePlayer.getName())) { if (target.getBase().getName().equals(onlinePlayer.getName())) {
@ -113,8 +114,7 @@ public class Commandnick extends EssentialsLoopCommand {
} }
private void setNickname(final Server server, final CommandSource sender, final User target, final String nickname) { private void setNickname(final Server server, final CommandSource sender, final User target, final String nickname) {
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; final NickChangeEvent nickEvent = new NickChangeEvent(sender.getUser(ess), target, nickname);
final NickChangeEvent nickEvent = new NickChangeEvent(controller, target, nickname);
server.getPluginManager().callEvent(nickEvent); server.getPluginManager().callEvent(nickEvent);
if (!nickEvent.isCancelled()) { if (!nickEvent.isCancelled()) {
target.setNickname(nickname); target.setNickname(nickname);

View File

@ -25,10 +25,8 @@ public class Commandnuke extends EssentialsCommand {
Collection<Player> targets; Collection<Player> targets;
if (args.length > 0) { if (args.length > 0) {
targets = new ArrayList<>(); targets = new ArrayList<>();
int pos = 0; for (int i = 0; i < args.length; ++i) {
for (String arg : args) { targets.add(getPlayer(server, sender, args, i).getBase());
targets.add(getPlayer(server, sender, args, pos).getBase());
pos++;
} }
} else { } else {
targets = ess.getOnlinePlayers(); targets = ess.getOnlinePlayers();
@ -43,8 +41,7 @@ public class Commandnuke extends EssentialsCommand {
final World world = loc.getWorld(); final World world = loc.getWorld();
for (int x = -10; x <= 10; x += 5) { for (int x = -10; x <= 10; x += 5) {
for (int z = -10; z <= 10; z += 5) { for (int z = -10; z <= 10; z += 5) {
final Location tntloc = new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z); world.spawn(new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z), TNTPrimed.class);
final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class);
} }
} }
} }

View File

@ -1,12 +1,10 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.MaxMoneyException; import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.UserBalanceUpdateEvent; import net.ess3.api.events.UserBalanceUpdateEvent;
@ -15,21 +13,18 @@ import org.bukkit.Server;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandpay extends EssentialsLoopCommand { public class Commandpay extends EssentialsLoopCommand {
BigDecimal amount;
boolean informToConfirm;
public Commandpay() { public Commandpay() {
super("pay"); super("pay");
} }
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
informToConfirm = false;
if (args.length < 2) { if (args.length < 2) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -44,49 +39,50 @@ public class Commandpay extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
amount = new BigDecimal(stringAmount); final BigDecimal amount = new BigDecimal(stringAmount);
if (amount.compareTo(ess.getSettings().getMinimumPayAmount()) < 0) { // Check if amount is less than minimum-pay-amount if (amount.compareTo(ess.getSettings().getMinimumPayAmount()) < 0) { // Check if amount is less than minimum-pay-amount
throw new Exception(tl("minimumPayAmount", NumberUtil.displayCurrencyExactly(ess.getSettings().getMinimumPayAmount(), ess))); throw new Exception(tl("minimumPayAmount", NumberUtil.displayCurrencyExactly(ess.getSettings().getMinimumPayAmount(), ess)));
} }
loopOnlinePlayers(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], args); final AtomicBoolean informToConfirm = new AtomicBoolean(false);
if (informToConfirm) { loopOnlinePlayersConsumer(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], player -> {
try {
if (!player.isAcceptingPay() || (ess.getSettings().isPayExcludesIgnoreList() && player.isIgnoredPlayer(user))) {
user.sendMessage(tl("notAcceptingPay", player.getDisplayName()));
return;
}
if (user.isPromptingPayConfirm() && !amount.equals(user.getConfirmingPayments().get(player))) { // checks if exists and if command needs to be repeated.
// Used to reset confirmations and inform to confirm when a new pay command has been inserted.
if (!informToConfirm.get()) {
// User hasnt been asked to confirm payment to this player, reset all confirmed payments and ask to confirm again.
// Clear previous confirmations to ensure that a new confirmation message is brought up.
user.getConfirmingPayments().clear();
informToConfirm.set(true);
}
user.getConfirmingPayments().put(player, amount);
return;
}
user.payUser(player, amount, UserBalanceUpdateEvent.Cause.COMMAND_PAY);
user.getConfirmingPayments().remove(player);
Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), player.getName(), new Trade(amount, ess), user.getLocation(), ess);
} catch (MaxMoneyException ex) {
user.sendMessage(tl("maxMoney"));
try {
user.setMoney(user.getMoney().add(amount));
} catch (MaxMoneyException ignored) {
}
} catch (Exception e) {
user.sendMessage(e.getMessage());
}
});
if (informToConfirm.get()) {
String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", args); String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", args);
user.sendMessage(tl("confirmPayment", NumberUtil.displayCurrency(amount, ess), cmd)); user.sendMessage(tl("confirmPayment", NumberUtil.displayCurrency(amount, ess), cmd));
} }
} }
@Override @Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws ChargeException { protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) {
User user = ess.getUser(sender.getPlayer());
try {
if (!player.isAcceptingPay() || (ess.getSettings().isPayExcludesIgnoreList() && player.isIgnoredPlayer(user))) {
sender.sendMessage(tl("notAcceptingPay", player.getDisplayName()));
return;
}
if (user.isPromptingPayConfirm() && !amount.equals(user.getConfirmingPayments().get(player))) { // checks if exists and if command needs to be repeated.
// Used to reset confirmations and inform to confirm when a new pay command has been inserted.
if (!informToConfirm) {
// User hasnt been asked to confirm payment to this player, reset all confirmed payments and ask to confirm again.
// Clear previous confirmations to ensure that a new confirmation message is brought up.
user.getConfirmingPayments().clear();
this.informToConfirm = true;
}
user.getConfirmingPayments().put(player, amount);
return;
}
user.payUser(player, amount, UserBalanceUpdateEvent.Cause.COMMAND_PAY);
user.getConfirmingPayments().remove(player);
Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), player.getName(), new Trade(amount, ess), user.getLocation(), ess);
} catch (MaxMoneyException ex) {
sender.sendMessage(tl("maxMoney"));
try {
user.setMoney(user.getMoney().add(amount));
} catch (MaxMoneyException ignored) {
// this should never happen
}
} catch (Exception e) {
sender.sendMessage(e.getMessage());
}
} }
@Override @Override

View File

@ -1,11 +1,10 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandpayconfirmtoggle extends EssentialsCommand { public class Commandpayconfirmtoggle extends EssentialsCommand {
public Commandpayconfirmtoggle() { public Commandpayconfirmtoggle() {
@ -21,11 +20,7 @@ public class Commandpayconfirmtoggle extends EssentialsCommand {
confirmingPay = false; confirmingPay = false;
} }
user.setPromptingPayConfirm(confirmingPay); user.setPromptingPayConfirm(confirmingPay);
if (confirmingPay) { user.sendMessage(confirmingPay ? tl("payConfirmToggleOn") : tl("payConfirmToggleOff"));
user.sendMessage(tl("payConfirmToggleOn"));
} else {
user.sendMessage(tl("payConfirmToggleOff"));
}
user.getConfirmingPayments().clear(); // Clear any outstanding confirmations. user.getConfirmingPayments().clear(); // Clear any outstanding confirmations.
} }
} }

View File

@ -1,29 +1,44 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandpaytoggle extends EssentialsCommand { public class Commandpaytoggle extends EssentialsToggleCommand {
public Commandpaytoggle() { public Commandpaytoggle() {
super("paytoggle"); super("paytoggle", "essentials.paytoggle.others");
}
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
toggleOtherPlayers(server, sender, args);
} }
@Override @Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
boolean acceptingPay = !user.isAcceptingPay();
if (commandLabel.contains("payon")) { if (commandLabel.contains("payon")) {
acceptingPay = true; togglePlayer(user.getSource(), user, true);
} else if (commandLabel.contains("payoff")) { } else if (commandLabel.contains("payoff")) {
acceptingPay = false; togglePlayer(user.getSource(), user, false);
}
user.setAcceptingPay(acceptingPay);
if (acceptingPay) {
user.sendMessage(tl("payToggleOn"));
} else { } else {
user.sendMessage(tl("payToggleOff")); handleToggleWithArgs(server, user, args);
}
}
@Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) {
enabled = !user.isAcceptingPay();
}
user.setAcceptingPay(enabled);
user.sendMessage(!enabled ? tl("payToggleOn") : tl("payToggleOff"));
if (!sender.isPlayer() || !user.getBase().equals(sender.getPlayer())) {
sender.sendMessage(!enabled ? tl("payEnabledFor", user.getDisplayName()) : tl("payDisabledFor", user.getDisplayName()));
} }
} }
} }

View File

@ -14,8 +14,7 @@ public class Commandping extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
sender.sendMessage(tl("pong")); sender.sendMessage(tl("pong"));
} else { } else {
sender.sendMessage(FormatUtil.replaceFormat(getFinalArg(args, 0))); sender.sendMessage(FormatUtil.replaceFormat(getFinalArg(args, 0)));

View File

@ -26,7 +26,6 @@ public class Commandpotion extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getItemInHand(); final ItemStack stack = user.getItemInHand();
if (args.length == 0) { if (args.length == 0) {
final Set<String> potionslist = new TreeSet<>(); final Set<String> potionslist = new TreeSet<>();
for (Map.Entry<String, PotionEffectType> entry : Potions.entrySet()) { for (Map.Entry<String, PotionEffectType> entry : Potions.entrySet()) {
@ -44,31 +43,28 @@ public class Commandpotion extends EssentialsCommand {
} }
if (holdingPotion) { if (holdingPotion) {
PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); PotionMeta pmeta = (PotionMeta) stack.getItemMeta();
if (args.length > 0) { if (args[0].equalsIgnoreCase("clear")) {
if (args[0].equalsIgnoreCase("clear")) { pmeta.clearCustomEffects();
pmeta.clearCustomEffects(); stack.setItemMeta(pmeta);
} else if (args[0].equalsIgnoreCase("apply") && user.isAuthorized("essentials.potion.apply")) {
for (PotionEffect effect : pmeta.getCustomEffects()) {
effect.apply(user.getBase());
}
} else if (args.length < 3) {
throw new NotEnoughArgumentsException();
} else {
final MetaItemStack mStack = new MetaItemStack(stack);
for (String arg : args) {
mStack.addPotionMeta(user.getSource(), true, arg, ess);
}
if (mStack.completePotion()) {
pmeta = (PotionMeta) mStack.getItemStack().getItemMeta();
stack.setItemMeta(pmeta); stack.setItemMeta(pmeta);
} else if (args[0].equalsIgnoreCase("apply") && user.isAuthorized("essentials.potion.apply")) {
for (PotionEffect effect : pmeta.getCustomEffects()) {
effect.apply(user.getBase());
}
} else if (args.length < 3) {
throw new NotEnoughArgumentsException();
} else { } else {
final MetaItemStack mStack = new MetaItemStack(stack); user.sendMessage(tl("invalidPotion"));
for (String arg : args) { throw new NotEnoughArgumentsException();
mStack.addPotionMeta(user.getSource(), true, arg, ess);
}
if (mStack.completePotion()) {
pmeta = (PotionMeta) mStack.getItemStack().getItemMeta();
stack.setItemMeta(pmeta);
} else {
user.sendMessage(tl("invalidPotion"));
throw new NotEnoughArgumentsException();
}
} }
} }
} else { } else {
throw new Exception(tl("holdPotion")); throw new Exception(tl("holdPotion"));
} }

View File

@ -25,23 +25,22 @@ public class Commandpowertool extends EssentialsCommand {
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final String command = getFinalArg(args, 0); final String command = getFinalArg(args, 0);
final ItemStack itemStack = user.getBase().getItemInHand(); final ItemStack itemStack = user.getBase().getItemInHand();
powertool(server, user.getSource(), user, commandLabel, itemStack, command); powertool(user.getSource(), user, itemStack, command);
} }
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 3) //running from console means inserting a player and item before the standard syntax if (args.length < 3) {
{
throw new Exception("When running from console, usage is: /" + commandLabel + " <player> <itemid> <command>"); throw new Exception("When running from console, usage is: /" + commandLabel + " <player> <itemid> <command>");
} }
final User user = getPlayer(server, args, 0, true, true); final User user = getPlayer(server, args, 0, true, true);
final ItemStack itemStack = ess.getItemDb().get(args[1]); final ItemStack itemStack = ess.getItemDb().get(args[1]);
final String command = getFinalArg(args, 2); final String command = getFinalArg(args, 2);
powertool(server, sender, user, commandLabel, itemStack, command); powertool(sender, user, itemStack, command);
} }
protected void powertool(final Server server, final CommandSource sender, final User user, final String commandLabel, final ItemStack itemStack, String command) throws Exception { protected void powertool(final CommandSource sender, final User user, final ItemStack itemStack, String command) throws Exception {
// check to see if this is a clear all command // check to see if this is a clear all command
if (command != null && command.equalsIgnoreCase("d:")) { if (command != null && command.equalsIgnoreCase("d:")) {
user.clearAllPowertools(); user.clearAllPowertools();

View File

@ -1,28 +1,20 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.google.common.collect.Lists;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DescParseTickFormat; import com.earth2me.essentials.utils.DescParseTickFormat;
import com.google.common.collect.Lists;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.*; import java.util.*;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandptime extends EssentialsCommand { public class Commandptime extends EssentialsLoopCommand {
private static final Set<String> getAliases = new HashSet<>(); private static final List<String> getAliases = Arrays.asList("get", "list", "show", "display");
static {
getAliases.add("get");
getAliases.add("list");
getAliases.add("show");
getAliases.add("display");
}
public Commandptime() { public Commandptime() {
super("ptime"); super("ptime");
@ -30,160 +22,96 @@ public class Commandptime extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
// Which Players(s) / Users(s) are we interested in? if (args.length == 0 || getAliases.contains(args[0].toLowerCase())) {
String userSelector = null; if (args.length > 1) { // /ptime get md_5 || /ptime get *
if (args.length == 2) { if (args[1].equals("*") || args[1].equals("**")) {
userSelector = args[1]; sender.sendMessage(tl("pTimePlayers"));
} }
Set<User> users = getUsers(server, sender, userSelector); loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> getUserTime(sender, player));
// If no arguments we are reading the time
if (args.length == 0) {
getUsersTime(sender, users);
return;
}
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.ptime.others")) {
user.sendMessage(tl("pTimeOthersPermission"));
return; return;
} }
if (args.length == 1 || sender.isPlayer()) { // /ptime get
if (sender.isPlayer()) {
getUserTime(sender, sender.getUser(ess));
return;
}
throw new NotEnoughArgumentsException(); // We cannot imply the target for console
}
// Default to showing the player times of all online users for console when no arguments are provided
if (ess.getOnlinePlayers().size() > 1) {
sender.sendMessage(tl("pTimePlayers"));
}
for (User player : ess.getOnlineUsers()) {
getUserTime(sender, player);
}
} }
Long ticks; if (args.length > 1 && !sender.isAuthorized("essentials.ptime.others", ess) && !args[1].equalsIgnoreCase(sender.getSelfSelector())) {
// Parse the target time int ticks from args[0] sender.sendMessage(tl("pTimeOthersPermission"));
String timeParam = args[0]; return;
boolean relative = true;
if (timeParam.startsWith("@")) {
relative = false;
timeParam = timeParam.substring(1);
} }
if (getAliases.contains(timeParam)) { String time = args[0];
getUsersTime(sender, users); boolean fixed = time.startsWith("@");
return; if (fixed) {
} else if (DescParseTickFormat.meansReset(timeParam)) { time = time.substring(1);
}
final Long ticks;
if (DescParseTickFormat.meansReset(time)) {
ticks = null; ticks = null;
} else { } else {
try { try {
ticks = DescParseTickFormat.parse(timeParam); ticks = DescParseTickFormat.parse(time);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new NotEnoughArgumentsException(e); throw new NotEnoughArgumentsException(e);
} }
} }
setUsersTime(sender, users, ticks, relative); StringJoiner joiner = new StringJoiner(",");
} loopOnlinePlayersConsumer(server, sender, false, true, args.length > 1 ? args[1] : sender.getSelfSelector(), player -> {
setUserTime(player, ticks, !fixed);
joiner.add(player.getName());
});
/**
* Used to get the time and inform
*/
private void getUsersTime(final CommandSource sender, final Collection<User> users) {
if (users.size() > 1) {
sender.sendMessage(tl("pTimePlayers"));
}
for (User user : users) {
if (user.getBase().getPlayerTimeOffset() == 0) {
sender.sendMessage(tl("pTimeNormal", user.getName()));
} else {
String time = DescParseTickFormat.format(user.getBase().getPlayerTime());
if (!user.getBase().isPlayerTimeRelative()) {
sender.sendMessage(tl("pTimeCurrentFixed", user.getName(), time));
} else {
sender.sendMessage(tl("pTimeCurrent", user.getName(), time));
}
}
}
}
/**
* Used to set the time and inform of the change
*/
private void setUsersTime(final CommandSource sender, final Collection<User> users, final Long ticks, Boolean relative) {
// Update the time
if (ticks == null) { if (ticks == null) {
// Reset sender.sendMessage(tl("pTimeReset", joiner.toString()));
for (User user : users) { return;
user.getBase().resetPlayerTime();
}
} else {
// Set
for (User user : users) {
final World world = user.getWorld();
long time = user.getBase().getPlayerTime();
time -= time % 24000;
time += 24000 + ticks;
if (relative) {
time -= world.getTime();
}
user.getBase().setPlayerTime(time, relative);
}
} }
final StringBuilder msg = new StringBuilder(); String formattedTime = DescParseTickFormat.format(ticks);
for (User user : users) { sender.sendMessage(fixed ? tl("pTimeSetFixed", formattedTime, joiner.toString()) : tl("pTimeSet", formattedTime, joiner.toString()));
if (msg.length() > 0) {
msg.append(", ");
}
msg.append(user.getName());
}
// Inform the sender of the change
if (ticks == null) {
sender.sendMessage(tl("pTimeReset", msg.toString()));
} else {
String time = DescParseTickFormat.format(ticks);
if (!relative) {
sender.sendMessage(tl("pTimeSetFixed", time, msg.toString()));
} else {
sender.sendMessage(tl("pTimeSet", time, msg.toString()));
}
}
} }
/** public void getUserTime(final CommandSource sender, IUser user) {
* Used to parse an argument of the type "users(s) selector" if (user == null) {
*/ return;
private Set<User> getUsers(final Server server, final CommandSource sender, final String selector) throws Exception { }
final Set<User> users = new TreeSet<>(new UserNameComparator());
// If there is no selector we want the sender itself. Or all users if sender isn't a user. if (user.getBase().getPlayerTimeOffset() == 0) {
if (selector == null) { sender.sendMessage(tl("pTimeNormal", user.getName()));
if (sender.isPlayer()) { return;
final User user = ess.getUser(sender.getPlayer()); }
users.add(user);
} else { String time = DescParseTickFormat.format(user.getBase().getPlayerTime());
for (User user : ess.getOnlineUsers()) { sender.sendMessage(user.getBase().isPlayerTimeRelative() ? tl("pTimeCurrent", user.getName(), time) : tl("pTimeCurrentFixed", user.getName(), time));
users.add(user); }
}
private void setUserTime(final User user, final Long ticks, Boolean relative) {
if (ticks == null) {
user.getBase().resetPlayerTime();
} else {
final World world = user.getWorld();
long time = user.getBase().getPlayerTime();
time -= time % 24000;
time += 24000 + ticks;
if (relative) {
time -= world.getTime();
} }
return users; user.getBase().setPlayerTime(time, relative);
} }
// Try to find the user with name = selector
User user = null;
final List<Player> matchedPlayers = server.matchPlayer(selector);
if (!matchedPlayers.isEmpty()) {
user = ess.getUser(matchedPlayers.get(0));
}
if (user != null) {
users.add(user);
}
// If that fails, Is the argument something like "*" or "all"?
else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) {
for (User u : ess.getOnlineUsers()) {
users.add(u);
}
}
// We failed to understand the world target...
else {
throw new PlayerNotFoundException();
}
return users;
} }
@Override @Override
@ -198,12 +126,8 @@ public class Commandptime extends EssentialsCommand {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
}
class UserNameComparator implements Comparator<User> {
@Override @Override
public int compare(User a, User b) { protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
return a.getName().compareTo(b.getName());
} }
} }

View File

@ -1,27 +1,21 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.google.common.collect.Lists;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.google.common.collect.Lists;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.WeatherType; import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import java.util.*; import java.util.*;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandpweather extends EssentialsLoopCommand {
public class Commandpweather extends EssentialsCommand { private static final List<String> getAliases = Arrays.asList("get", "list", "show", "display");
public static final Set<String> getAliases = new HashSet<>(); private static final Map<String, WeatherType> weatherAliases = new HashMap<>();
public static final Map<String, WeatherType> weatherAliases = new HashMap<>();
static { static {
getAliases.add("get");
getAliases.add("list");
getAliases.add("show");
getAliases.add("display");
weatherAliases.put("sun", WeatherType.CLEAR); weatherAliases.put("sun", WeatherType.CLEAR);
weatherAliases.put("clear", WeatherType.CLEAR); weatherAliases.put("clear", WeatherType.CLEAR);
weatherAliases.put("storm", WeatherType.DOWNFALL); weatherAliases.put("storm", WeatherType.DOWNFALL);
@ -34,123 +28,74 @@ public class Commandpweather extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
// Which Players(s) / Users(s) are we interested in? if (args.length == 0 || getAliases.contains(args[0].toLowerCase())) {
String userSelector = null; if (args.length > 1) { // /pweather get md_5 || /pweather get *
if (args.length == 2) { if (args[1].equals("*") || args[1].equals("**")) {
userSelector = args[1]; sender.sendMessage(tl("pWeatherPlayers"));
} }
Set<User> users = getUsers(server, sender, userSelector); loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> getUserWeather(sender, player));
if (args.length == 0) {
getUsersWeather(sender, users);
return;
}
if (getAliases.contains(args[0])) {
getUsersWeather(sender, users);
return;
}
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.pweather.others")) {
user.sendMessage(tl("pWeatherOthersPermission"));
return; return;
} }
}
setUsersWeather(sender, users, args[0].toLowerCase()); if (args.length == 1 || sender.isPlayer()) { // /pweather get
} if (sender.isPlayer()) {
getUserWeather(sender, sender.getUser(ess));
/** return;
* Used to get the time and inform
*/
private void getUsersWeather(final CommandSource sender, final Collection<User> users) {
if (users.size() > 1) {
sender.sendMessage(tl("pWeatherPlayers"));
}
for (User user : users) {
if (user.getBase().getPlayerWeather() == null) {
sender.sendMessage(tl("pWeatherNormal", user.getName()));
} else {
sender.sendMessage(tl("pWeatherCurrent", user.getName(), user.getBase().getPlayerWeather().toString().toLowerCase(Locale.ENGLISH)));
}
}
}
/**
* Used to set the time and inform of the change
*/
private void setUsersWeather(final CommandSource sender, final Collection<User> users, final String weatherType) throws Exception {
final StringBuilder msg = new StringBuilder();
for (User user : users) {
if (msg.length() > 0) {
msg.append(", ");
}
msg.append(user.getName());
}
if (weatherType.equalsIgnoreCase("reset")) {
for (User user : users) {
user.getBase().resetPlayerWeather();
}
sender.sendMessage(tl("pWeatherReset", msg));
} else {
if (!weatherAliases.containsKey(weatherType)) {
throw new NotEnoughArgumentsException(tl("pWeatherInvalidAlias"));
}
for (User user : users) {
user.getBase().setPlayerWeather(weatherAliases.get(weatherType));
}
sender.sendMessage(tl("pWeatherSet", weatherType, msg.toString()));
}
}
/**
* Used to parse an argument of the type "users(s) selector"
*/
private Set<User> getUsers(final Server server, final CommandSource sender, final String selector) throws Exception {
final Set<User> users = new TreeSet<>(new UserNameComparator());
// If there is no selector we want the sender itself. Or all users if sender isn't a user.
if (selector == null) {
if (sender.isPlayer()) {
final User user = ess.getUser(sender.getPlayer());
users.add(user);
} else {
for (User user : ess.getOnlineUsers()) {
users.add(user);
} }
throw new NotEnoughArgumentsException(); // We cannot imply the target for console
} }
return users;
}
// Try to find the user with name = selector // Default to showing the weather of all online users for console when no arguments are provided
User user = null; if (ess.getOnlinePlayers().size() > 1) {
final List<Player> matchedPlayers = server.matchPlayer(selector); sender.sendMessage(tl("pWeatherPlayers"));
if (!matchedPlayers.isEmpty()) { }
user = ess.getUser(matchedPlayers.get(0)); for (User player : ess.getOnlineUsers()) {
} getUserWeather(sender, player);
if (user != null) {
users.add(user);
}
// If that fails, Is the argument something like "*" or "all"?
else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) {
for (User u : ess.getOnlineUsers()) {
users.add(u);
} }
} }
// We failed to understand the world target...
else { if (args.length > 1 && !sender.isAuthorized("essentials.pweather.others", ess) && !args[1].equalsIgnoreCase(sender.getSelfSelector())) {
throw new PlayerNotFoundException(); sender.sendMessage(tl("pWeatherOthersPermission"));
return;
} }
return users; String weather = args[0].toLowerCase();
if (!weatherAliases.containsKey(weather) && !weather.equalsIgnoreCase("reset")) {
throw new NotEnoughArgumentsException(tl("pWeatherInvalidAlias"));
}
StringJoiner joiner = new StringJoiner(",");
loopOnlinePlayersConsumer(server, sender, false, true, args.length > 1 ? args[1] : sender.getSelfSelector(), player -> {
setUserWeather(player, weather);
joiner.add(player.getName());
});
if (weather.equalsIgnoreCase("reset")) {
sender.sendMessage(tl("pWeatherReset", joiner.toString()));
return;
}
sender.sendMessage(tl("pWeatherSet", weather, joiner.toString()));
}
private void getUserWeather(CommandSource sender, IUser user) {
if (user == null) {
return;
}
if (user.getBase().getPlayerWeather() == null) {
sender.sendMessage(tl("pWeatherNormal", user.getName()));
return;
}
sender.sendMessage(tl("pWeatherCurrent", user.getName(), user.getBase().getPlayerWeather().toString().toLowerCase(Locale.ENGLISH)));
}
private void setUserWeather(User user, String weatherType) {
if (weatherType.equalsIgnoreCase("reset")) {
user.getBase().resetPlayerWeather();
return;
}
user.getBase().setPlayerWeather(weatherAliases.get(weatherType));
} }
@Override @Override
@ -163,4 +108,8 @@ public class Commandpweather extends EssentialsCommand {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
} }

View File

@ -24,10 +24,8 @@ public class Commandr extends EssentialsCommand {
String message = getFinalArg(args, 0); String message = getFinalArg(args, 0);
IMessageRecipient messageSender; IMessageRecipient messageSender;
if (sender.isPlayer()) { if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer()); User user = ess.getUser(sender.getPlayer());
if (user.isMuted()) { if (user.isMuted()) {
String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) { if (dateDiff == null) {

View File

@ -17,10 +17,12 @@ public class Commandrealname extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final String whois = args[0].toLowerCase(Locale.ENGLISH);
final String lookup = args[0].toLowerCase(Locale.ENGLISH);
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false; boolean foundUser = false;
for (User u : ess.getOnlineUsers()) { for (User u : ess.getOnlineUsers()) {
@ -28,8 +30,7 @@ public class Commandrealname extends EssentialsCommand {
continue; continue;
} }
u.setDisplayNick(); u.setDisplayNick();
final String displayName = FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); if (FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH).contains(lookup)) {
if (displayName.contains(whois)) {
foundUser = true; foundUser = true;
sender.sendMessage(tl("realName", u.getDisplayName(), u.getName())); sender.sendMessage(tl("realName", u.getDisplayName(), u.getName()));
} }

View File

@ -226,10 +226,8 @@ public class Commandremove extends EssentialsCommand {
break; break;
case ENTITIES: case ENTITIES:
case ALL: case ALL:
if (e instanceof Entity) { e.remove();
e.remove(); removed++;
removed++;
}
break; break;
case CUSTOM: case CUSTOM:
for (Mob type : customRemoveTypes) { for (Mob type : customRemoveTypes) {

View File

@ -26,7 +26,7 @@ public class Commandrepair extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1 || args[0].equalsIgnoreCase("hand") || !user.isAuthorized("essentials.repair.all")) { if (args.length == 0 || args[0].equalsIgnoreCase("hand") || !user.isAuthorized("essentials.repair.all")) {
repairHand(user); repairHand(user);
} else if (args[0].equalsIgnoreCase("all")) { } else if (args[0].equalsIgnoreCase("all")) {
final Trade charge = new Trade("repair-all", ess); final Trade charge = new Trade("repair-all", ess);

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Server; import org.bukkit.Server;
@ -16,29 +17,20 @@ public class Commandrest extends EssentialsLoopCommand {
super("rest"); super("rest");
} }
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
user.sendMessage(tl("unsupportedFeature"));
return;
}
if (args.length > 0 && user.isAuthorized("essentials.rest.others")) {
loopOnlinePlayers(server, user.getSource(), true, true, args[0], null);
return;
}
restPlayer(user);
}
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) { if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
sender.sendMessage(tl("unsupportedFeature")); sender.sendMessage(tl("unsupportedFeature"));
return; return;
} }
if (args.length < 1) { if (args.length == 0 && !sender.isPlayer()) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
loopOnlinePlayers(server, sender, true, true, args[0], null); if (args.length > 0 && sender.isAuthorized("essentials.rest.others", ess)) {
loopOnlinePlayers(server, sender, false, true, args[0], null);
return;
}
restPlayer(sender.getUser(ess));
} }
@Override @Override
@ -47,23 +39,14 @@ public class Commandrest extends EssentialsLoopCommand {
sender.sendMessage(tl("restOther", player.getDisplayName())); sender.sendMessage(tl("restOther", player.getDisplayName()));
} }
private void restPlayer(final User user) { private void restPlayer(final IUser user) {
user.getBase().setStatistic(Statistic.TIME_SINCE_REST, 0); user.getBase().setStatistic(Statistic.TIME_SINCE_REST, 0);
user.sendMessage(tl("rest")); user.sendMessage(tl("rest"));
} }
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.rest.others")) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
}
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) { if (args.length == 1 && sender.isAuthorized("essentials.rest.others", ess)) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -22,7 +22,7 @@ public class Commandrtoggle extends EssentialsToggleCommand {
} }
@Override @Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException { void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) { if (enabled == null) {
enabled = !user.isLastMessageReplyRecipient(); enabled = !user.isLastMessageReplyRecipient();
} }

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
@ -19,9 +18,7 @@ public class Commandrules extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick(); ess.getUser(sender.getPlayer()).setDisplayNick();
} }
final IText input = new TextInput(sender, "rules", true, ess); final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "rules", true, ess), sender, ess));
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
} }
} }

View File

@ -28,16 +28,9 @@ public class Commandseen extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
seen(server, sender, commandLabel, args, true, true, true, true); boolean showBan = sender.isAuthorized("essentials.seen.banreason", ess);
} boolean showIp = sender.isAuthorized("essentials.seen.ip", ess);
boolean showLocation = sender.isAuthorized("essentials.seen.location", ess);
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
seen(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.ip"), user.isAuthorized("essentials.seen.location"), user.isAuthorized("essentials.seen.ipsearch"));
}
protected void seen(final Server server, final CommandSource sender, final String commandLabel, final String[] args,
final boolean showBan, final boolean showIp, final boolean showLocation, final boolean ipLookup) throws Exception {
if (args.length < 1) { if (args.length < 1) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -46,13 +39,13 @@ public class Commandseen extends EssentialsCommand {
try { try {
UUID uuid = UUID.fromString(args[0]); UUID uuid = UUID.fromString(args[0]);
player = ess.getUser(uuid); player = ess.getUser(uuid);
}catch (IllegalArgumentException ignored) { // Thrown if invalid UUID from string, check by name. } catch (IllegalArgumentException ignored) { // Thrown if invalid UUID from string, check by name.
player = ess.getOfflineUser(args[0]); player = ess.getOfflineUser(args[0]);
} }
if (player == null) { if (player == null) {
if (ipLookup && FormatUtil.validIP(args[0])) { if (sender.isAuthorized("essentials.seen.ipsearch", ess) && FormatUtil.validIP(args[0])) {
seenIP(server, sender, args[0]); seenIP(sender, args[0]);
return; return;
} else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) { } else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) {
sender.sendMessage(tl("isIpBanned", args[0])); sender.sendMessage(tl("isIpBanned", args[0]));
@ -81,23 +74,23 @@ public class Commandseen extends EssentialsCommand {
} }
private void showUserSeen(User user) throws Exception { private void showUserSeen(User user) throws Exception {
showSeenMessage(server, sender, user, showBan, showIp, showLocation); showSeenMessage(sender, user, showBan, showIp, showLocation);
} }
}); });
} else { } else {
showSeenMessage(server, sender, player, showBan, showIp, showLocation); showSeenMessage(sender, player, showBan, showIp, showLocation);
} }
} }
private void showSeenMessage(Server server, CommandSource sender, User player, boolean showBan, boolean showIp, boolean showLocation) throws Exception { private void showSeenMessage(CommandSource sender, User player, boolean showBan, boolean showIp, boolean showLocation) {
if (player.getBase().isOnline() && canInteractWith(sender, player)) { if (player.getBase().isOnline() && canInteractWith(sender, player)) {
seenOnline(server, sender, player, showBan, showIp, showLocation); seenOnline(sender, player, showIp);
} else { } else {
seenOffline(server, sender, player, showBan, showIp, showLocation); seenOffline(sender, player, showBan, showIp, showLocation);
} }
} }
private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean showIp, final boolean showLocation) throws Exception { private void seenOnline(final CommandSource sender, final User user, final boolean showIp) {
user.setDisplayNick(); user.setDisplayNick();
sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin()))); sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin())));
@ -134,7 +127,7 @@ public class Commandseen extends EssentialsCommand {
} }
} }
private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean showIp, final boolean showLocation) throws Exception { private void seenOffline(final CommandSource sender, User user, final boolean showBan, final boolean showIp, final boolean showLocation) {
user.setDisplayNick(); user.setDisplayNick();
if (user.getLastLogout() > 0) { if (user.getLastLogout() > 0) {
sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout()))); sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout())));
@ -191,7 +184,7 @@ public class Commandseen extends EssentialsCommand {
} }
} }
private void seenIP(final Server server, final CommandSource sender, final String ipAddress) throws Exception { private void seenIP(final CommandSource sender, final String ipAddress) {
final UserMap userMap = ess.getUserMap(); final UserMap userMap = ess.getUserMap();
if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) { if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) {

View File

@ -27,7 +27,6 @@ public class Commandsell extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
BigDecimal totalWorth = BigDecimal.ZERO; BigDecimal totalWorth = BigDecimal.ZERO;
String type = "";
if (args.length < 1) { if (args.length < 1) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -82,9 +81,9 @@ public class Commandsell extends EssentialsCommand {
} }
if (count != 1) { if (count != 1) {
if (args[0].equalsIgnoreCase("blocks")) { if (args[0].equalsIgnoreCase("blocks")) {
user.sendMessage(tl("totalWorthBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); user.sendMessage(tl("totalWorthBlocks", NumberUtil.displayCurrency(totalWorth, ess)));
} else { } else {
user.sendMessage(tl("totalWorthAll", type, NumberUtil.displayCurrency(totalWorth, ess))); user.sendMessage(tl("totalWorthAll", NumberUtil.displayCurrency(totalWorth, ess)));
} }
} }
} }

View File

@ -24,7 +24,6 @@ public class Commandsethome extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception {
User usersHome = user; User usersHome = user;
String name = "home"; String name = "home";
final Location location = user.getLocation();
if (args.length > 0) { if (args.length > 0) {
//Allowing both formats /sethome khobbits house | /sethome khobbits:house //Allowing both formats /sethome khobbits house | /sethome khobbits:house
@ -52,6 +51,7 @@ public class Commandsethome extends EssentialsCommand {
throw new NoSuchFieldException(tl("invalidHomeName")); throw new NoSuchFieldException(tl("invalidHomeName"));
} }
final Location location = user.getLocation();
if (!ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockUnsafeForUser(usersHome, location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ())) { if (!ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockUnsafeForUser(usersHome, location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
throw new Exception(tl("unsafeTeleportDestination", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); throw new Exception(tl("unsafeTeleportDestination", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()));
} }

View File

@ -19,6 +19,5 @@ public class Commandsetjail extends EssentialsCommand {
} }
ess.getJails().setJail(args[0], user.getLocation()); ess.getJails().setJail(args[0], user.getLocation());
user.sendMessage(tl("jailSet", StringUtil.sanitizeString(args[0]))); user.sendMessage(tl("jailSet", StringUtil.sanitizeString(args[0])));
} }
} }

View File

@ -18,15 +18,14 @@ public class Commandsetwarp extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
if (NumberUtil.isInt(args[0]) || args[0].isEmpty()) { if (NumberUtil.isInt(args[0]) || args[0].isEmpty()) {
throw new NoSuchFieldException(tl("invalidWarpName")); throw new Exception(tl("invalidWarpName"));
} }
final Location loc = user.getLocation();
final IWarps warps = ess.getWarps(); final IWarps warps = ess.getWarps();
Location warpLoc = null; Location warpLoc = null;
@ -36,7 +35,7 @@ public class Commandsetwarp extends EssentialsCommand {
} }
if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) { if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) {
warps.setWarp(user, args[0], loc); warps.setWarp(user, args[0], user.getLocation());
} else { } else {
throw new Exception(tl("warpOverwrite")); throw new Exception(tl("warpOverwrite"));
} }

View File

@ -22,7 +22,6 @@ public class Commandsetworth extends EssentialsCommand {
ItemStack stack; ItemStack stack;
String price; String price;
if (args.length == 1) { if (args.length == 1) {
stack = user.getBase().getInventory().getItemInHand(); stack = user.getBase().getInventory().getItemInHand();
price = args[0]; price = args[0];
@ -41,8 +40,7 @@ public class Commandsetworth extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
ItemStack stack = ess.getItemDb().get(args[0]); ess.getWorth().setPrice(ess, ess.getItemDb().get(args[0]), FloatUtil.parseDouble(args[1]));
ess.getWorth().setPrice(ess, stack, FloatUtil.parseDouble(args[1]));
sender.sendMessage(tl("worthSet")); sender.sendMessage(tl("worthSet"));
} }
} }

View File

@ -12,7 +12,6 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandshowkit extends EssentialsCommand { public class Commandshowkit extends EssentialsCommand {
public Commandshowkit() { public Commandshowkit() {
super("showkit"); super("showkit");
} }
@ -23,11 +22,9 @@ public class Commandshowkit extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(","); for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) {
for (final String kitName : kits) {
Kit kit = new Kit(kitName, ess);
user.sendMessage(tl("kitContains", kitName)); user.sendMessage(tl("kitContains", kitName));
for (String s : kit.getItems()) { for (String s : new Kit(kitName, ess).getItems()) {
user.sendMessage(tl("kitItem", s)); user.sendMessage(tl("kitItem", s));
} }
} }

View File

@ -9,14 +9,17 @@ import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
public class Commandskull extends EssentialsCommand { public class Commandskull extends EssentialsCommand {
private static final Pattern NAME_PATTERN = Pattern.compile("^[A-Za-z0-9_]+$");
private static final Material SKULL_ITEM = EnumUtil.getMaterial("PLAYER_HEAD", "SKULL_ITEM"); private static final Material SKULL_ITEM = EnumUtil.getMaterial("PLAYER_HEAD", "SKULL_ITEM");
public Commandskull() { public Commandskull() {
@ -26,9 +29,8 @@ public class Commandskull extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
String owner; String owner;
if (args.length > 0 && user.isAuthorized("essentials.skull.others")) { if (args.length > 0 && user.isAuthorized("essentials.skull.others")) {
if (!args[0].matches("^[A-Za-z0-9_]+$")) { if (!NAME_PATTERN.matcher(args[0]).matches()) {
throw new IllegalArgumentException(tl("alphaNames")); throw new IllegalArgumentException(tl("alphaNames"));
} }
owner = args[0]; owner = args[0];
@ -37,7 +39,7 @@ public class Commandskull extends EssentialsCommand {
} }
ItemStack itemSkull = user.getItemInHand(); ItemStack itemSkull = user.getItemInHand();
SkullMeta metaSkull = null; SkullMeta metaSkull;
boolean spawn = false; boolean spawn = false;
if (itemSkull != null && MaterialUtil.isPlayerHead(itemSkull.getType(), itemSkull.getDurability())) { if (itemSkull != null && MaterialUtil.isPlayerHead(itemSkull.getType(), itemSkull.getDurability())) {
@ -54,17 +56,30 @@ public class Commandskull extends EssentialsCommand {
throw new Exception(tl("noPermissionSkull")); throw new Exception(tl("noPermissionSkull"));
} }
metaSkull.setDisplayName("§fSkull of " + owner); editSkull(user, itemSkull, metaSkull, owner, spawn);
metaSkull.setOwner(owner); }
itemSkull.setItemMeta(metaSkull); private void editSkull(User user, ItemStack stack, SkullMeta skullMeta, String owner, boolean spawn) {
new BukkitRunnable() {
if (spawn) { @Override
InventoryWorkaround.addItems(user.getBase().getInventory(), itemSkull); public void run() {
user.sendMessage(tl("givenSkull", owner)); //Run this stuff async because SkullMeta#setOwner causes a http request.
} else { skullMeta.setDisplayName("§fSkull of " + owner);
user.sendMessage(tl("skullChanged", owner)); skullMeta.setOwner(owner);
} new BukkitRunnable() {
@Override
public void run() {
stack.setItemMeta(skullMeta);
if (spawn) {
InventoryWorkaround.addItems(user.getBase().getInventory(), stack);
user.sendMessage(tl("givenSkull", owner));
return;
}
user.sendMessage(tl("skullChanged", owner));
}
}.runTask(ess);
}
}.runTaskAsynchronously(ess);
} }
@Override @Override

View File

@ -23,14 +23,13 @@ public class Commandsocialspy extends EssentialsToggleCommand {
} }
@Override @Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException { protected void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) { if (enabled == null) {
enabled = !user.isSocialSpyEnabled(); enabled = !user.isSocialSpyEnabled();
} }
user.setSocialSpyEnabled(enabled); user.setSocialSpyEnabled(enabled);
user.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); user.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled")));
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) {
sender.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); sender.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled")));

View File

@ -19,6 +19,9 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandspawner extends EssentialsCommand { public class Commandspawner extends EssentialsCommand {
private static final Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER");
public Commandspawner() { public Commandspawner() {
super("spawner"); super("spawner");
} }
@ -30,30 +33,28 @@ public class Commandspawner extends EssentialsCommand {
} }
final Location target = LocationUtil.getTarget(user.getBase()); final Location target = LocationUtil.getTarget(user.getBase());
Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER");
if (target == null || target.getBlock().getType() != MOB_SPAWNER) { if (target.getBlock().getType() != MOB_SPAWNER) {
throw new Exception(tl("mobSpawnTarget")); throw new Exception(tl("mobSpawnTarget"));
} }
String name = args[0]; String name = args[0];
int delay = 0; int delay = 0;
Mob mob = null; Mob mob = Mob.fromName(name);
mob = Mob.fromName(name);
if (mob == null) { if (mob == null) {
throw new Exception(tl("invalidMob")); throw new Exception(tl("invalidMob"));
} }
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) { if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("disabledToSpawnMob")); throw new Exception(tl("disabledToSpawnMob"));
} }
if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase(Locale.ENGLISH))) { if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("noPermToSpawnMob")); throw new Exception(tl("noPermToSpawnMob"));
} }
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) { if (args.length > 1 && NumberUtil.isInt(args[1])) {
delay = Integer.parseInt(args[1]); delay = Integer.parseInt(args[1]);
}
} }
final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess);
charge.isAffordableFor(user); charge.isAffordableFor(user);

View File

@ -21,9 +21,8 @@ public class Commandspawnmob extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
final String mobList = SpawnMob.mobList(user); throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList())));
throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList));
} }
List<String> mobParts = SpawnMob.mobParts(args[0]); List<String> mobParts = SpawnMob.mobParts(args[0]);
@ -39,8 +38,7 @@ public class Commandspawnmob extends EssentialsCommand {
} }
if (args.length >= 3) { if (args.length >= 3) {
final User target = getPlayer(ess.getServer(), user, args, 2); SpawnMob.spawnmob(ess, server, user.getSource(), getPlayer(ess.getServer(), user, args, 2), mobParts, mobData, mobCount);
SpawnMob.spawnmob(ess, server, user.getSource(), target, mobParts, mobData, mobCount);
return; return;
} }
@ -50,16 +48,13 @@ public class Commandspawnmob extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 3) { if (args.length < 3) {
final String mobList = StringUtil.joinList(Mob.getMobList()); throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList())));
throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList));
} }
List<String> mobParts = SpawnMob.mobParts(args[0]); List<String> mobParts = SpawnMob.mobParts(args[0]);
List<String> mobData = SpawnMob.mobData(args[0]); List<String> mobData = SpawnMob.mobData(args[0]);
int mobCount = Integer.parseInt(args[1]);
final User target = getPlayer(ess.getServer(), args, 2, true, false); SpawnMob.spawnmob(ess, server, sender, getPlayer(ess.getServer(), args, 2, true, false), mobParts, mobData, Integer.parseInt(args[1]));
SpawnMob.spawnmob(ess, server, sender, target, mobParts, mobData, mobCount);
} }
@Override @Override

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.utils.FloatUtil;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -13,6 +14,9 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandspeed extends EssentialsCommand { public class Commandspeed extends EssentialsCommand {
private static final List<String> types = Arrays.asList("walk", "fly", "1", "1.5", "1.75", "2");
private static final List<String> speeds = Arrays.asList("1", "1.5", "1.75", "2");
public Commandspeed() { public Commandspeed() {
super("speed"); super("speed");
} }
@ -22,9 +26,7 @@ public class Commandspeed extends EssentialsCommand {
if (args.length < 2) { if (args.length < 2) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final boolean isFly = isFlyMode(args[0]); speedOtherPlayers(server, sender, isFlyMode(args[0]), true, getMoveSpeed(args[1]), args[2]);
final float speed = getMoveSpeed(args[1]);
speedOtherPlayers(server, sender, isFly, true, speed, args[2]);
} }
@Override @Override
@ -52,12 +54,12 @@ public class Commandspeed extends EssentialsCommand {
} }
if (isFly) { if (isFly) {
user.getBase().setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); user.getBase().setFlySpeed(getRealMoveSpeed(speed, true, isBypass));
user.sendMessage(tl("moveSpeed", tl("flying"), speed, user.getDisplayName())); user.sendMessage(tl("moveSpeed", tl("flying"), speed, user.getDisplayName()));
} else { return;
user.getBase().setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass));
user.sendMessage(tl("moveSpeed", tl("walking"), speed, user.getDisplayName()));
} }
user.getBase().setWalkSpeed(getRealMoveSpeed(speed, false, isBypass));
user.sendMessage(tl("moveSpeed", tl("walking"), speed, user.getDisplayName()));
} }
private void speedOtherPlayers(final Server server, final CommandSource sender, final boolean isFly, final boolean isBypass, final float speed, final String name) throws PlayerNotFoundException { private void speedOtherPlayers(final Server server, final CommandSource sender, final boolean isFly, final boolean isBypass, final float speed, final String name) throws PlayerNotFoundException {
@ -71,10 +73,10 @@ public class Commandspeed extends EssentialsCommand {
} }
foundUser = true; foundUser = true;
if (isFly) { if (isFly) {
matchPlayer.setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); matchPlayer.setFlySpeed(getRealMoveSpeed(speed, true, isBypass));
sender.sendMessage(tl("moveSpeed", tl("flying"), speed, matchPlayer.getDisplayName())); sender.sendMessage(tl("moveSpeed", tl("flying"), speed, matchPlayer.getDisplayName()));
} else { } else {
matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass)); matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, false, isBypass));
sender.sendMessage(tl("moveSpeed", tl("walking"), speed, matchPlayer.getDisplayName())); sender.sendMessage(tl("moveSpeed", tl("walking"), speed, matchPlayer.getDisplayName()));
} }
} }
@ -83,7 +85,7 @@ public class Commandspeed extends EssentialsCommand {
} }
} }
private Boolean flyPermCheck(User user, boolean input) throws Exception { private Boolean flyPermCheck(User user, boolean input) {
boolean canFly = user.isAuthorized("essentials.speed.fly"); boolean canFly = user.isAuthorized("essentials.speed.fly");
boolean canWalk = user.isAuthorized("essentials.speed.walk"); boolean canWalk = user.isAuthorized("essentials.speed.walk");
if (input && canFly || !input && canWalk || !canFly && !canWalk) { if (input && canFly || !input && canWalk || !canFly && !canWalk) {
@ -133,18 +135,13 @@ public class Commandspeed extends EssentialsCommand {
} }
} }
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 3 && user.isAuthorized("essentials.speed.others")) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
}
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 3) { if (args.length == 1) {
return types;
} else if (args.length == 2) {
return speeds;
} else if (args.length == 3 && sender.isAuthorized("essentials.speed.others", ess)) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -1,9 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.Locale; import java.util.Locale;
@ -22,20 +20,15 @@ public class Commandsudo extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final String[] arguments = new String[args.length - 1]; final String command = getFinalArg(args, 1);
if (arguments.length > 0) {
System.arraycopy(args, 1, arguments, 0, args.length - 1);
}
final String command = getFinalArg(arguments, 0);
boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple"); boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple");
sender.sendMessage(tl("sudoRun", args[0], command, "")); sender.sendMessage(tl("sudoRun", args[0], command, ""));
loopOnlinePlayers(server, sender, multiple, multiple, args[0], new String[]{command}); loopOnlinePlayers(server, sender, false, multiple, args[0], new String[]{command});
} }
@Override @Override
protected void updatePlayer(final Server server, final CommandSource sender, final User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { protected void updatePlayer(final Server server, final CommandSource sender, final User user, String[] args) {
if (user.getName().equals(sender.getSender().getName())) { if (user.getName().equals(sender.getSender().getName())) {
return; // Silently don't do anything. return; // Silently don't do anything.
} }
@ -51,7 +44,7 @@ public class Commandsudo extends EssentialsLoopCommand {
} }
final String command = getFinalArg(args, 0); final String command = getFinalArg(args, 0);
if (command != null && command.length() > 0) { if (command.length() > 0) {
class SudoCommandTask implements Runnable { class SudoCommandTask implements Runnable {
@Override @Override
public void run() { public void run() {

View File

@ -26,16 +26,12 @@ public class Commandtempban extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final User user = getPlayer(server, args, 0, true, true); final User user = getPlayer(server, args, 0, true, true);
if (!user.getBase().isOnline()) { if (!user.getBase().isOnline() && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) { sender.sendMessage(tl("tempbanExemptOffline"));
sender.sendMessage(tl("tempbanExemptOffline")); return;
return; } else if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) {
} sender.sendMessage(tl("tempbanExempt"));
} else { return;
if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) {
sender.sendMessage(tl("tempbanExempt"));
return;
}
} }
final String time = getFinalArg(args, 1); final String time = getFinalArg(args, 1);
final long banTimestamp = DateUtil.parseDateDiff(time, true); final long banTimestamp = DateUtil.parseDateDiff(time, true);
@ -44,7 +40,7 @@ public class Commandtempban extends EssentialsCommand {
final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; final long maxBanLength = ess.getSettings().getMaxTempban() * 1000;
if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) { if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) {
sender.sendMessage(tl("oversizedTempban")); sender.sendMessage(tl("oversizedTempban"));
throw new NoChargeException(); return;
} }
if (banReason.length() < 2) { if (banReason.length() < 2) {
@ -55,8 +51,7 @@ public class Commandtempban extends EssentialsCommand {
ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, new Date(banTimestamp), senderName); ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, new Date(banTimestamp), senderName);
final String expiry = DateUtil.formatDateDiff(banTimestamp); final String expiry = DateUtil.formatDateDiff(banTimestamp);
final String banDisplay = tl("tempBanned", expiry, senderName, banReason); user.getBase().kickPlayer(tl("tempBanned", expiry, senderName, banReason));
user.getBase().kickPlayer(banDisplay);
final String message = tl("playerTempBanned", senderName, user.getName(), expiry, banReason); final String message = tl("playerTempBanned", senderName, user.getName(), expiry, banReason);
server.getLogger().log(Level.INFO, message); server.getLogger().log(Level.INFO, message);

View File

@ -52,24 +52,23 @@ public class Commandtempbanip extends EssentialsCommand {
final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; final long maxBanLength = ess.getSettings().getMaxTempban() * 1000;
if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) { if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) {
sender.sendMessage(tl("oversizedTempban")); sender.sendMessage(tl("oversizedTempban"));
throw new NoChargeException(); return;
} }
if (banReason.length() < 2) { if (banReason.length() < 2) {
banReason = tl("defaultBanReason"); banReason = tl("defaultBanReason");
} }
String banDisplay = tl("banFormat", banReason, senderName);
ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, new Date(banTimestamp), senderName); ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, new Date(banTimestamp), senderName);
final String message = tl("playerTempBanIpAddress", senderName, ipAddress, DateUtil.formatDateDiff(banTimestamp), banReason);
String banDisplay = tl("banFormat", banReason, senderName);
for (Player player : ess.getServer().getOnlinePlayers()) { for (Player player : ess.getServer().getOnlinePlayers()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) { if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
player.kickPlayer(banDisplay); player.kickPlayer(banDisplay);
} }
} }
String message = tl("playerTempBanIpAddress", senderName, ipAddress, DateUtil.formatDateDiff(banTimestamp), banReason);
server.getLogger().log(Level.INFO, message); server.getLogger().log(Level.INFO, message);
ess.broadcastMessage("essentials.banip.notify", message); ess.broadcastMessage("essentials.banip.notify", message);
} }

View File

@ -18,22 +18,21 @@ public class Commandthunder extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final World world = user.getWorld(); final World world = user.getWorld();
final boolean setThunder = args[0].equalsIgnoreCase("true"); final boolean setThunder = args[0].equalsIgnoreCase("true");
if (args.length > 1) { if (args.length == 1) {
world.setThundering(setThunder);
world.setThunderDuration(Integer.parseInt(args[1]) * 20);
user.sendMessage(tl("thunderDuration", (setThunder ? tl("enabled") : tl("disabled")), Integer.parseInt(args[1])));
} else {
world.setThundering(setThunder); world.setThundering(setThunder);
user.sendMessage(tl("thunder", setThunder ? tl("enabled") : tl("disabled"))); user.sendMessage(tl("thunder", setThunder ? tl("enabled") : tl("disabled")));
return;
} }
world.setThundering(setThunder);
world.setThunderDuration(Integer.parseInt(args[1]) * 20);
user.sendMessage(tl("thunderDuration", (setThunder ? tl("enabled") : tl("disabled")), Integer.parseInt(args[1])));
} }
@Override @Override

View File

@ -14,64 +14,75 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandtime extends EssentialsCommand { public class Commandtime extends EssentialsCommand {
private final List<String> subCommands = Arrays.asList("add", "set");
private final List<String> timeNames = Arrays.asList("sunrise", "day", "morning", "noon", "afternoon", "sunset", "night", "midnight");
private final List<String> timeNumbers = Arrays.asList("1000", "2000", "3000", "4000", "5000");
public Commandtime() { public Commandtime() {
super("time"); super("time");
} }
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
long timeTick;
Set<World> worlds;
boolean add = false; boolean add = false;
final List<String> argList = new ArrayList<>(Arrays.asList(args)); if (args.length == 0) {
if (argList.remove("set") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) { worlds = getWorlds(server, sender, null);
argList.set(0, argList.get(0) + "t"); if (commandLabel.endsWith("day") || commandLabel.endsWith("night")) {
} timeTick = DescParseTickFormat.parse(commandLabel.toLowerCase(Locale.ENGLISH).replace("e", "")); // These are 100% safe things to parse, no need for catching
if (argList.remove("add") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) {
add = true;
argList.set(0, argList.get(0) + "t");
}
final String[] validArgs = argList.toArray(new String[0]);
// Which World(s) are we interested in?
String worldSelector = null;
if (validArgs.length == 2) {
worldSelector = validArgs[1];
}
final Set<World> worlds = getWorlds(server, sender, worldSelector);
final String setTime;
// If no arguments we are reading the time
if (validArgs.length == 0) {
if (commandLabel.equalsIgnoreCase("day") || commandLabel.equalsIgnoreCase("eday")) {
setTime = "day";
} else if (commandLabel.equalsIgnoreCase("night") || commandLabel.equalsIgnoreCase("enight")) {
setTime = "night";
} else { } else {
getWorldsTime(sender, worlds); getWorldsTime(sender, worlds);
throw new NoChargeException(); return;
}
} else if (args.length == 1) {
worlds = getWorlds(server, sender, null);
try {
timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[0]) ? (args[0] + "t") : args[0]);
} catch (NumberFormatException e) {
throw new NotEnoughArgumentsException(e);
} }
} else { } else {
setTime = validArgs[0]; if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add")) {
try {
add = args[0].equalsIgnoreCase("add");
timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[1]) ? (args[1] + "t") : args[1]);
worlds = getWorlds(server, sender, args.length > 2 ? args[2] : null);
} catch (NumberFormatException e) {
throw new NotEnoughArgumentsException(e);
}
} else {
try {
timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[0]) ? (args[0] + "t") : args[0]);
worlds = getWorlds(server, sender, args[1]);
} catch (NumberFormatException e) {
throw new NotEnoughArgumentsException(e);
}
}
} }
final User user = ess.getUser(sender.getPlayer()); // Start updating world times, we have what we need
if (user != null && !user.isAuthorized("essentials.time.set")) { User user = ess.getUser(sender.getPlayer());
throw new Exception(tl("timeSetPermission")); for (World world : worlds) {
if (!canUpdateWorld(user, world)) {
throw new Exception(tl("timeSetWorldPermission", user.getWorld().getName()));
}
} }
// Parse the target time int ticks from args[0] final StringJoiner joiner = new StringJoiner(",");
long ticks; for (World world : worlds) {
try { long time = world.getTime();
ticks = DescParseTickFormat.parse(setTime); if (!add) {
} catch (NumberFormatException e) { time -= time % 24000;
throw new NotEnoughArgumentsException(e); }
world.setTime(time + (add ? 0 : 24000) + timeTick);
joiner.add(world.getName());
} }
setWorldsTime(sender, worlds, ticks, add); sender.sendMessage(tl(add ? "timeWorldAdd" : "timeWorldSet", DescParseTickFormat.formatTicks(timeTick), joiner.toString()));
} }
/**
* Used to get the time and inform
*/
private void getWorldsTime(final CommandSource sender, final Collection<World> worlds) { private void getWorldsTime(final CommandSource sender, final Collection<World> worlds) {
if (worlds.size() == 1) { if (worlds.size() == 1) {
final Iterator<World> iter = worlds.iterator(); final Iterator<World> iter = worlds.iterator();
@ -85,39 +96,7 @@ public class Commandtime extends EssentialsCommand {
} }
/** /**
* Used to set the time and inform of the change * Parses worlds from command args, otherwise returns all worlds.
*/
private void setWorldsTime(final CommandSource sender, final Collection<World> worlds, final long ticks, final boolean add) throws Exception {
User user = ess.getUser(sender.getPlayer());
for (World world : worlds) {
if (!canUpdateWorld(user, world)) {
throw new Exception(tl("timeSetWorldPermission", user.getWorld().getName()));
}
}
// Update the time
for (World world : worlds) {
long time = world.getTime();
if (!add) {
time -= time % 24000;
}
world.setTime(time + (add ? 0 : 24000) + ticks);
}
final StringBuilder output = new StringBuilder();
for (World world : worlds) {
if (output.length() > 0) {
output.append(", ");
}
output.append(world.getName());
}
sender.sendMessage(tl("timeWorldSet", DescParseTickFormat.format(ticks), output.toString()));
}
/**
* Used to parse an argument of the type "world(s) selector"
*/ */
private Set<World> getWorlds(final Server server, final CommandSource sender, final String selector) throws Exception { private Set<World> getWorlds(final Server server, final CommandSource sender, final String selector) throws Exception {
final Set<World> worlds = new TreeSet<>(new WorldNameComparator()); final Set<World> worlds = new TreeSet<>(new WorldNameComparator());
@ -125,9 +104,7 @@ public class Commandtime extends EssentialsCommand {
// If there is no selector we want the world the user is currently in. Or all worlds if it isn't a user. // If there is no selector we want the world the user is currently in. Or all worlds if it isn't a user.
if (selector == null) { if (selector == null) {
if (sender.isPlayer()) { if (sender.isPlayer()) {
worlds.add(sender.getPlayer().getWorld());
final User user = ess.getUser(sender.getPlayer());
worlds.add(user.getWorld());
} else { } else {
worlds.addAll(server.getWorlds()); worlds.addAll(server.getWorlds());
} }
@ -138,16 +115,11 @@ public class Commandtime extends EssentialsCommand {
final World world = server.getWorld(selector); final World world = server.getWorld(selector);
if (world != null) { if (world != null) {
worlds.add(world); worlds.add(world);
} } else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) { // If that fails, Is the argument something like "*" or "all"?
// If that fails, Is the argument something like "*" or "all"?
else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) {
worlds.addAll(server.getWorlds()); worlds.addAll(server.getWorlds());
} } else { // We failed to understand the world target...
// We failed to understand the world target...
else {
throw new Exception(tl("invalidWorld")); throw new Exception(tl("invalidWorld"));
} }
return worlds; return worlds;
} }
@ -166,25 +138,28 @@ public class Commandtime extends EssentialsCommand {
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
final User user = ess.getUser(sender.getPlayer());
if (args.length == 1) { if (args.length == 1) {
if (user == null || user.isAuthorized("essentials.time.set")) { if (sender.isAuthorized("essentials.time.set", ess)) {
return Lists.newArrayList("set", "add"); return subCommands;
} else {
return Collections.emptyList();
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("set")) {
return timeNames;
} else if (args[0].equalsIgnoreCase("add")) {
return timeNumbers;
} else { } else {
return Collections.emptyList(); return Collections.emptyList();
} }
} else if (args.length == 2 && args[0].equalsIgnoreCase("set")) {
return Lists.newArrayList("sunrise", "day", "morning", "noon", "afternoon", "sunset", "night", "midnight");
// TODO: handle tab completion for add
} else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add"))) { } else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add"))) {
List<String> worlds = Lists.newArrayList(); List<String> worlds = Lists.newArrayList();
for (World world : server.getWorlds()) { for (World world : server.getWorlds()) {
if (user == null || user.isAuthorized("essentials.time.world." + normalizeWorldName(world))) { if (sender.isAuthorized("essentials.time.world." + normalizeWorldName(world), ess)) {
worlds.add(world.getName()); worlds.add(world.getName());
} }
} }
if (user == null || user.isAuthorized("essentials.time.world.all")) { if (sender.isAuthorized("essentials.time.world.all", ess)) {
worlds.add("*"); worlds.add("*");
} }
return worlds; return worlds;

View File

@ -22,7 +22,7 @@ public class Commandtogglejail extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -34,14 +34,14 @@ public class Commandtogglejail extends EssentialsCommand {
sender.sendMessage(tl("mayNotJailOffline")); sender.sendMessage(tl("mayNotJailOffline"));
return; return;
} }
} else {
if (player.isAuthorized("essentials.jail.exempt")) {
sender.sendMessage(tl("mayNotJail"));
return;
}
} }
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
final JailStatusChangeEvent event = new JailStatusChangeEvent(player, controller, true); if (player.isAuthorized("essentials.jail.exempt")) {
sender.sendMessage(tl("mayNotJail"));
return;
}
final JailStatusChangeEvent event = new JailStatusChangeEvent(player, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, true);
ess.getServer().getPluginManager().callEvent(event); ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
@ -82,8 +82,7 @@ public class Commandtogglejail extends EssentialsCommand {
} }
if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) { if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) {
final String time = getFinalArg(args, 2); final long timeDiff = DateUtil.parseDateDiff(getFinalArg(args, 2), true);
final long timeDiff = DateUtil.parseDateDiff(time, true);
player.setJailTimeout(timeDiff); player.setJailTimeout(timeDiff);
sender.sendMessage(tl("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); sender.sendMessage(tl("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff)));
return; return;
@ -93,8 +92,8 @@ public class Commandtogglejail extends EssentialsCommand {
if (!player.isJailed()) { if (!player.isJailed()) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
final JailStatusChangeEvent event = new JailStatusChangeEvent(player, controller, false); final JailStatusChangeEvent event = new JailStatusChangeEvent(player, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, false);
ess.getServer().getPluginManager().callEvent(event); ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {

View File

@ -46,12 +46,12 @@ public class Commandtree extends EssentialsCommand {
if (!user.getWorld().getBlockAt(loc).isPassable()) { if (!user.getWorld().getBlockAt(loc).isPassable()) {
throw new Exception(tl("treeFailure")); throw new Exception(tl("treeFailure"));
} }
final boolean success = user.getWorld().generateTree(loc, tree);
if (success) { if (user.getWorld().generateTree(loc, tree)) {
user.sendMessage(tl("treeSpawned")); user.sendMessage(tl("treeSpawned"));
} else { return;
user.sendMessage(tl("treeFailure"));
} }
user.sendMessage(tl("treeFailure"));
} }
@Override @Override

View File

@ -8,6 +8,7 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashSet; import java.util.HashSet;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.StringJoiner;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -19,23 +20,19 @@ public class Commandunlimited extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
User target = user; User target = user;
if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) { if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) {
target = getPlayer(server, user, args, 1); target = getPlayer(server, user, args, 1);
} }
if (args[0].equalsIgnoreCase("list")) { if (args[0].equalsIgnoreCase("list")) {
final String list = getList(target); user.sendMessage(getList(target));
user.sendMessage(list);
} else if (args[0].equalsIgnoreCase("clear")) { } else if (args[0].equalsIgnoreCase("clear")) {
final Set<Material> itemList = new HashSet<>(target.getUnlimited()); for (Material m : new HashSet<>(target.getUnlimited())) {
for (Material m : itemList) {
toggleUnlimited(user, target, m.toString()); toggleUnlimited(user, target, m.toString());
} }
} else { } else {
@ -46,24 +43,20 @@ public class Commandunlimited extends EssentialsCommand {
private String getList(final User target) { private String getList(final User target) {
final StringBuilder output = new StringBuilder(); final StringBuilder output = new StringBuilder();
output.append(tl("unlimitedItems")).append(" "); output.append(tl("unlimitedItems")).append(" ");
boolean first = true;
final Set<Material> items = target.getUnlimited(); final Set<Material> items = target.getUnlimited();
if (items.isEmpty()) { if (items.isEmpty()) {
output.append(tl("none")); output.append(tl("none"));
} }
StringJoiner joiner = new StringJoiner(",");
for (Material material : items) { for (Material material : items) {
if (!first) { joiner.add(material.toString().toLowerCase(Locale.ENGLISH).replace("_", ""));
output.append(", ");
}
first = false;
final String matname = material.toString().toLowerCase(Locale.ENGLISH).replace("_", "");
output.append(matname);
} }
output.append(joiner.toString());
return output.toString(); return output.toString();
} }
private Boolean toggleUnlimited(final User user, final User target, final String item) throws Exception { private void toggleUnlimited(final User user, final User target, final String item) throws Exception {
final ItemStack stack = ess.getItemDb().get(item, 1); final ItemStack stack = ess.getItemDb().get(item, 1);
stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2));
@ -87,7 +80,5 @@ public class Commandunlimited extends EssentialsCommand {
} }
target.sendMessage(tl(message, itemname, target.getDisplayName())); target.sendMessage(tl(message, itemname, target.getDisplayName()));
target.setUnlimited(stack, enableUnlimited); target.setUnlimited(stack, enableUnlimited);
return true;
} }
} }

View File

@ -2,12 +2,11 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.events.VanishStatusChangeEvent;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
import net.ess3.api.events.VanishStatusChangeEvent;
public class Commandvanish extends EssentialsToggleCommand { public class Commandvanish extends EssentialsToggleCommand {
public Commandvanish() { public Commandvanish() {
@ -25,13 +24,12 @@ public class Commandvanish extends EssentialsToggleCommand {
} }
@Override @Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException { void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) { if (enabled == null) {
enabled = !user.isVanished(); enabled = !user.isVanished();
} }
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; VanishStatusChangeEvent vanishEvent = new VanishStatusChangeEvent(sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, user, enabled);
VanishStatusChangeEvent vanishEvent = new VanishStatusChangeEvent(controller, user, enabled);
ess.getServer().getPluginManager().callEvent(vanishEvent); ess.getServer().getPluginManager().callEvent(vanishEvent);
if (vanishEvent.isCancelled()) { if (vanishEvent.isCancelled()) {
return; return;

View File

@ -17,14 +17,13 @@ public class Commandweather extends EssentialsCommand {
super("weather"); super("weather");
} }
//TODO: Remove duplication
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final boolean isStorm; final boolean isStorm;
if (args.length < 1) { if (args.length == 0) {
if (commandLabel.equalsIgnoreCase("sun") || commandLabel.equalsIgnoreCase("esun")) { if (commandLabel.endsWith("sun")) {
isStorm = false; isStorm = false;
} else if (commandLabel.equalsIgnoreCase("storm") || commandLabel.equalsIgnoreCase("estorm") || commandLabel.equalsIgnoreCase("rain") || commandLabel.equalsIgnoreCase("erain")) { } else if (commandLabel.endsWith("storm") || commandLabel.endsWith("rain")) {
isStorm = true; isStorm = true;
} else { } else {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
@ -32,22 +31,22 @@ public class Commandweather extends EssentialsCommand {
} else { } else {
isStorm = args[0].equalsIgnoreCase("storm"); isStorm = args[0].equalsIgnoreCase("storm");
} }
final World world = user.getWorld();
if (args.length > 1) {
final World world = user.getWorld();
if (args.length > 1) {
world.setStorm(isStorm); world.setStorm(isStorm);
world.setWeatherDuration(Integer.parseInt(args[1]) * 20); world.setWeatherDuration(Integer.parseInt(args[1]) * 20);
user.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[1]) : tl("weatherSunFor", world.getName(), args[1])); user.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[1]) : tl("weatherSunFor", world.getName(), args[1]));
} else { return;
world.setStorm(isStorm);
user.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName()));
} }
world.setStorm(isStorm);
user.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName()));
} }
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 2) //running from console means inserting a world arg before other args if (args.length < 2) { //running from console means inserting a world arg before other args
{
throw new Exception("When running from console, usage is: /" + commandLabel + " <world> <storm/sun> [duration]"); throw new Exception("When running from console, usage is: /" + commandLabel + " <world> <storm/sun> [duration]");
} }
@ -56,15 +55,15 @@ public class Commandweather extends EssentialsCommand {
if (world == null) { if (world == null) {
throw new Exception(tl("weatherInvalidWorld", args[0])); throw new Exception(tl("weatherInvalidWorld", args[0]));
} }
if (args.length > 2) {
if (args.length > 2) {
world.setStorm(isStorm); world.setStorm(isStorm);
world.setWeatherDuration(Integer.parseInt(args[2]) * 20); world.setWeatherDuration(Integer.parseInt(args[2]) * 20);
sender.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[2]) : tl("weatherSunFor", world.getName(), args[2])); sender.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[2]) : tl("weatherSunFor", world.getName(), args[2]));
} else { return;
world.setStorm(isStorm);
sender.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName()));
} }
world.setStorm(isStorm);
sender.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName()));
} }
@Override @Override

View File

@ -9,7 +9,6 @@ public class Commandworkbench extends EssentialsCommand {
super("workbench"); super("workbench");
} }
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
user.getBase().openWorkbench(null, true); user.getBase().openWorkbench(null, true);

View File

@ -22,14 +22,10 @@ public class Commandworth extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
BigDecimal totalWorth = BigDecimal.ZERO;
String type = "";
List<ItemStack> is = ess.getItemDb().getMatching(user, args); List<ItemStack> is = ess.getItemDb().getMatching(user, args);
int count = 0; int count = 0;
boolean isBulk = is.size() > 1; boolean isBulk = is.size() > 1;
BigDecimal totalWorth = BigDecimal.ZERO;
for (ItemStack stack : is) { for (ItemStack stack : is) {
try { try {
if (stack.getAmount() > 0) { if (stack.getAmount() > 0) {
@ -51,22 +47,19 @@ public class Commandworth extends EssentialsCommand {
} }
if (count > 1) { if (count > 1) {
if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) { if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) {
user.sendMessage(tl("totalSellableBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); user.sendMessage(tl("totalSellableBlocks", NumberUtil.displayCurrency(totalWorth, ess)));
} else { return;
user.sendMessage(tl("totalSellableAll", type, NumberUtil.displayCurrency(totalWorth, ess)));
} }
user.sendMessage(tl("totalSellableAll", NumberUtil.displayCurrency(totalWorth, ess)));
} }
} }
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
itemWorth(sender, null, ess.getItemDb().get(args[0]), args);
ItemStack stack = ess.getItemDb().get(args[0]);
itemWorth(sender, null, stack, args);
} }
private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception { private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception {
@ -85,7 +78,6 @@ public class Commandworth extends EssentialsCommand {
} }
BigDecimal worth = ess.getWorth().getPrice(ess, is); BigDecimal worth = ess.getWorth().getPrice(ess, is);
if (worth == null) { if (worth == null) {
throw new Exception(tl("itemCannotBeSold")); throw new Exception(tl("itemCannotBeSold"));
} }
@ -95,9 +87,7 @@ public class Commandworth extends EssentialsCommand {
} }
BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); BigDecimal result = worth.multiply(BigDecimal.valueOf(amount));
sender.sendMessage(is.getDurability() != 0 ? tl("worthMeta", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), is.getDurability(), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)) : tl("worth", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); sender.sendMessage(is.getDurability() != 0 ? tl("worthMeta", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), is.getDurability(), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)) : tl("worth", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)));
return result; return result;
} }

View File

@ -20,6 +20,10 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
} }
protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
loopOfflinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs));
}
protected void loopOfflinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
if (searchTerm.isEmpty()) { if (searchTerm.isEmpty()) {
throw new PlayerNotFoundException(); throw new PlayerNotFoundException();
} }
@ -27,11 +31,11 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
final UUID uuid = StringUtil.toUUID(searchTerm); final UUID uuid = StringUtil.toUUID(searchTerm);
if (uuid != null) { if (uuid != null) {
final User matchedUser = ess.getUser(uuid); final User matchedUser = ess.getUser(uuid);
updatePlayer(server, sender, matchedUser, commandArgs); userConsumer.accept(matchedUser);
} else if (matchWildcards && searchTerm.contentEquals("**")) { } else if (matchWildcards && searchTerm.contentEquals("**")) {
for (UUID sUser : ess.getUserMap().getAllUniqueUsers()) { for (UUID sUser : ess.getUserMap().getAllUniqueUsers()) {
final User matchedUser = ess.getUser(sUser); final User matchedUser = ess.getUser(sUser);
updatePlayer(server, sender, matchedUser, commandArgs); userConsumer.accept(matchedUser);
} }
} else if (matchWildcards && searchTerm.contentEquals("*")) { } else if (matchWildcards && searchTerm.contentEquals("*")) {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
@ -39,7 +43,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) {
continue; continue;
} }
updatePlayer(server, sender, onlineUser, commandArgs); userConsumer.accept(onlineUser);
} }
} else if (multipleStringMatches) { } else if (multipleStringMatches) {
if (searchTerm.trim().length() < 3) { if (searchTerm.trim().length() < 3) {
@ -48,19 +52,23 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
final List<Player> matchedPlayers = server.matchPlayer(searchTerm); final List<Player> matchedPlayers = server.matchPlayer(searchTerm);
if (matchedPlayers.isEmpty()) { if (matchedPlayers.isEmpty()) {
final User matchedUser = getPlayer(server, searchTerm, true, true); final User matchedUser = getPlayer(server, searchTerm, true, true);
updatePlayer(server, sender, matchedUser, commandArgs); userConsumer.accept(matchedUser);
} }
for (Player matchPlayer : matchedPlayers) { for (Player matchPlayer : matchedPlayers) {
final User matchedUser = ess.getUser(matchPlayer); final User matchedUser = ess.getUser(matchPlayer);
updatePlayer(server, sender, matchedUser, commandArgs); userConsumer.accept(matchedUser);
} }
} else { } else {
final User user = getPlayer(server, searchTerm, true, true); final User user = getPlayer(server, searchTerm, true, true);
updatePlayer(server, sender, user, commandArgs); userConsumer.accept(user);
} }
} }
protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
loopOnlinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs));
}
protected void loopOnlinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
if (searchTerm.isEmpty()) { if (searchTerm.isEmpty()) {
throw new PlayerNotFoundException(); throw new PlayerNotFoundException();
} }
@ -72,7 +80,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) {
continue; continue;
} }
updatePlayer(server, sender, onlineUser, commandArgs); userConsumer.accept(onlineUser);
} }
} else if (multipleStringMatches) { } else if (multipleStringMatches) {
if (searchTerm.trim().length() < 2) { if (searchTerm.trim().length() < 2) {
@ -90,7 +98,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
final String displayName = FormatUtil.stripFormat(player.getDisplayName()).toLowerCase(Locale.ENGLISH); final String displayName = FormatUtil.stripFormat(player.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (displayName.contains(matchText)) { if (displayName.contains(matchText)) {
foundUser = true; foundUser = true;
updatePlayer(server, sender, player, commandArgs); userConsumer.accept(player);
} }
} }
} else { } else {
@ -100,7 +108,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
continue; continue;
} }
foundUser = true; foundUser = true;
updatePlayer(server, sender, player, commandArgs); userConsumer.accept(player);
} }
} }
if (!foundUser) { if (!foundUser) {
@ -108,7 +116,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
} }
} else { } else {
final User player = getPlayer(server, sender, searchTerm); final User player = getPlayer(server, sender, searchTerm);
updatePlayer(server, sender, player, commandArgs); userConsumer.accept(player);
} }
} }
@ -129,4 +137,8 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand {
players.add("*"); players.add("*");
return players; return players;
} }
public interface UserConsumer {
void accept(User user) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException;
}
} }

View File

@ -189,7 +189,7 @@ public final class DescParseTickFormat {
} }
public static String formatTicks(final long ticks) { public static String formatTicks(final long ticks) {
return (ticks % ticksPerDay) + "ticks"; return (ticks % ticksPerDay) + " ticks";
} }
public static String format24(final long ticks) { public static String format24(final long ticks) {

View File

@ -191,8 +191,8 @@ essentialsHelp1=The file is broken and Essentials can''t open it. Essentials is
essentialsHelp2=The file is broken and Essentials can''t open it. Essentials is now disabled. If you can''t fix the file yourself, either type /essentialshelp in game or go to http\://tiny.cc/EssentialsChat essentialsHelp2=The file is broken and Essentials can''t open it. Essentials is now disabled. If you can''t fix the file yourself, either type /essentialshelp in game or go to http\://tiny.cc/EssentialsChat
essentialsReload=\u00a76Essentials reloaded\u00a7c {0}. essentialsReload=\u00a76Essentials reloaded\u00a7c {0}.
exp=\u00a7c{0} \u00a76has\u00a7c {1} \u00a76exp (level\u00a7c {2}\u00a76) and needs\u00a7c {3} \u00a76more exp to level up. exp=\u00a7c{0} \u00a76has\u00a7c {1} \u00a76exp (level\u00a7c {2}\u00a76) and needs\u00a7c {3} \u00a76more exp to level up.
expCommandDescription=Give, set or look at a players exp. expCommandDescription=Give, set, reset, or look at a players experience.
expCommandUsage=/<command> [show|set|give] [playername [amount]] expCommandUsage=/<command> [reset|show|set|give] [playername [amount]]
expSet=\u00a7c{0} \u00a76now has\u00a7c {1} \u00a76exp. expSet=\u00a7c{0} \u00a76now has\u00a7c {1} \u00a76exp.
extCommandDescription=Extinguish players. extCommandDescription=Extinguish players.
extCommandUsage=/<command> [player] extCommandUsage=/<command> [player]
@ -365,6 +365,8 @@ jailReleased=\u00a76Player \u00a7c{0}\u00a76 unjailed.
jailReleasedPlayerNotify=\u00a76You have been released\! jailReleasedPlayerNotify=\u00a76You have been released\!
jailSentenceExtended=\u00a76Jail time extended to \u00a7c{0}\u00a76. jailSentenceExtended=\u00a76Jail time extended to \u00a7c{0}\u00a76.
jailSet=\u00a76Jail\u00a7c {0} \u00a76has been set. jailSet=\u00a76Jail\u00a7c {0} \u00a76has been set.
jumpEasterDisable=\u00a76Flying wizard mode disabled.
jumpEasterEnable=\u00a76Flying wizard mode enabled.
jailsCommandDescription=List all jails. jailsCommandDescription=List all jails.
jailsCommandUsage=/<command> jailsCommandUsage=/<command>
jumpCommandDescription=Jumps to the nearest block in the line of sight. jumpCommandDescription=Jumps to the nearest block in the line of sight.
@ -434,6 +436,7 @@ meCommandDescription=Describes an action in the context of the player.
meCommandUsage=/<command> <description> meCommandUsage=/<command> <description>
meSender=me meSender=me
meRecipient=me meRecipient=me
minimumBalanceError=\u00a74The minimum balance a user can have is {0}.
minimumPayAmount=\u00a7cThe minimum amount you can pay is {0}. minimumPayAmount=\u00a7cThe minimum amount you can pay is {0}.
minute=minute minute=minute
minutes=minutes minutes=minutes
@ -495,6 +498,7 @@ nickSet=\u00a76Your nickname is now \u00a7c{0}\u00a76.
nickTooLong=\u00a74That nickname is too long. nickTooLong=\u00a74That nickname is too long.
noAccessCommand=\u00a74You do not have access to that command. noAccessCommand=\u00a74You do not have access to that command.
noAccessPermission=\u00a74You do not have permission to access that \u00a7c{0}\u00a74. noAccessPermission=\u00a74You do not have permission to access that \u00a7c{0}\u00a74.
noAccessSubCommand=\u00a74You do not have access to \u00a7c{0}\u00a74.
noBreakBedrock=\u00a74You are not allowed to destroy bedrock. noBreakBedrock=\u00a74You are not allowed to destroy bedrock.
noDestroyPermission=\u00a74You do not have permission to destroy that \u00a7c{0}\u00a74. noDestroyPermission=\u00a74You do not have permission to destroy that \u00a7c{0}\u00a74.
northEast=NE northEast=NE
@ -550,6 +554,8 @@ payCommandDescription=Pays another player from your balance.
payCommandUsage=/<command> <player> <amount> payCommandUsage=/<command> <player> <amount>
payConfirmToggleOff=\u00a76You will no longer be prompted to confirm payments. payConfirmToggleOff=\u00a76You will no longer be prompted to confirm payments.
payConfirmToggleOn=\u00a76You will now be prompted to confirm payments. payConfirmToggleOn=\u00a76You will now be prompted to confirm payments.
payDisabledFor=\u00a76Disabled accepting payments for \u00a7c{0}\u00a76.
payEnabledFor=\u00a76Enabled accepting payments for \u00a7c{0}\u00a76.
payMustBePositive=\u00a74Amount to pay must be positive. payMustBePositive=\u00a74Amount to pay must be positive.
payToggleOff=\u00a76You are no longer accepting payments. payToggleOff=\u00a76You are no longer accepting payments.
payToggleOn=\u00a76You are now accepting payments. payToggleOn=\u00a76You are now accepting payments.
@ -796,10 +802,11 @@ thunderDuration=\u00a76You\u00a7c {0} \u00a76thunder in your world for\u00a7c {1
timeBeforeHeal=\u00a74Time before next heal\:\u00a7c {0}\u00a74. timeBeforeHeal=\u00a74Time before next heal\:\u00a7c {0}\u00a74.
timeBeforeTeleport=\u00a74Time before next teleport\:\u00a7c {0}\u00a74. timeBeforeTeleport=\u00a74Time before next teleport\:\u00a7c {0}\u00a74.
timeCommandDescription=Display/Change the world time. Defaults to current world. timeCommandDescription=Display/Change the world time. Defaults to current world.
timeCommandUsage=/<command> [day|night|dawn|17:30|4pm|4000ticks] [worldname|all] timeCommandUsage=/<command> [set|add] [day|night|dawn|17:30|4pm|4000ticks] [worldname|all]
timeFormat=\u00a7c{0}\u00a76 or \u00a7c{1}\u00a76 or \u00a7c{2}\u00a76 timeFormat=\u00a7c{0}\u00a76 or \u00a7c{1}\u00a76 or \u00a7c{2}\u00a76
timeSetPermission=\u00a74You are not authorized to set the time. timeSetPermission=\u00a74You are not authorized to set the time.
timeSetWorldPermission=\u00a74You are not authorized to set the time in world ''{0}''. timeSetWorldPermission=\u00a74You are not authorized to set the time in world ''{0}''.
timeWorldAdd=\u00a76The time was moved forward by\u00a7c {0} \u00a76in\: \u00a7c{1}\u00a76.
timeWorldCurrent=\u00a76The current time in\u00a7c {0} \u00a76is \u00a7c{1}\u00a76. timeWorldCurrent=\u00a76The current time in\u00a7c {0} \u00a76is \u00a7c{1}\u00a76.
timeWorldSet=\u00a76The time was set to\u00a7c {0} \u00a76in\: \u00a7c{1}\u00a76. timeWorldSet=\u00a76The time was set to\u00a7c {0} \u00a76in\: \u00a7c{1}\u00a76.
togglejailCommandDescription=Jails/Unjails a player, TPs them to the jail specified. togglejailCommandDescription=Jails/Unjails a player, TPs them to the jail specified.

View File

@ -133,8 +133,8 @@ commands:
usage: /<command> usage: /<command>
aliases: [eessentials, ess, eess, essversion] aliases: [eessentials, ess, eess, essversion]
exp: exp:
description: Give, set or look at a players exp. description: Give, set, reset, or look at a players experience.
usage: /<command> [show|set|give] [playername [amount]] usage: /<command> [reset|show|set|give] [playername [amount]]
aliases: [eexp,xp] aliases: [eexp,xp]
ext: ext:
description: Extinguish players. description: Extinguish players.
@ -450,7 +450,7 @@ commands:
aliases: [ethunder] aliases: [ethunder]
time: time:
description: Display/Change the world time. Defaults to current world. description: Display/Change the world time. Defaults to current world.
usage: /<command> [day|night|dawn|17:30|4pm|4000ticks] [worldname|all] usage: /<command> [set|add] [day|night|dawn|17:30|4pm|4000ticks] [worldname|all]
aliases: [day,eday,night,enight,etime] aliases: [day,eday,night,enight,etime]
togglejail: togglejail:
description: Jails/Unjails a player, TPs them to the jail specified. description: Jails/Unjails a player, TPs them to the jail specified.
@ -634,9 +634,6 @@ permissions:
essentials.silentquit: essentials.silentquit:
default: false default: false
description: Suppress leave/quit messages for users with this permission. description: Suppress leave/quit messages for users with this permission.
essentials.sleepingignored:
default: false
description: User isn't required to be sleeping, for time to be reset.
essentials.sudo.exempt: essentials.sudo.exempt:
default: false default: false
description: Prevents the holder from being sudo'ed by another user description: Prevents the holder from being sudo'ed by another user

View File

@ -1,9 +1,13 @@
package com.earth2me.essentials.spawn; package com.earth2me.essentials.spawn;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.EssentialsCommand;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -18,4 +22,9 @@ public class Commandsetspawn extends EssentialsCommand {
((SpawnStorage) module).setSpawn(user.getLocation(), group); ((SpawnStorage) module).setSpawn(user.getLocation(), group);
user.sendMessage(tl("spawnSet", group)); user.sendMessage(tl("spawnSet", group));
} }
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
return Collections.emptyList();
}
} }

View File

@ -10,6 +10,8 @@ import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tl;
@ -42,7 +44,7 @@ public class Commandspawn extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final User user = getPlayer(server, args, 0, true, false); final User user = getPlayer(server, args, 0, true, false);
@ -55,9 +57,16 @@ public class Commandspawn extends EssentialsCommand {
}); });
} }
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.spawn.others", ess)) {
return getPlayers(server, sender);
}
return Collections.emptyList();
}
private void respawn(final CommandSource sender, final User teleportOwner, final User teleportee, final Trade charge, String commandLabel, CompletableFuture<Boolean> future) throws Exception { private void respawn(final CommandSource sender, final User teleportOwner, final User teleportee, final Trade charge, String commandLabel, CompletableFuture<Boolean> future) throws Exception {
final SpawnStorage spawns = (SpawnStorage) this.module; final Location spawn = ((SpawnStorage) this.module).getSpawn(teleportee.getGroup());
final Location spawn = spawns.getSpawn(teleportee.getGroup());
sender.sendMessage(tl("teleporting", spawn.getWorld().getName(), spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ())); sender.sendMessage(tl("teleporting", spawn.getWorld().getName(), spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()));
future.exceptionally(e -> { future.exceptionally(e -> {
showError(sender.getSender(), e, commandLabel); showError(sender.getSender(), e, commandLabel);
@ -65,8 +74,8 @@ public class Commandspawn extends EssentialsCommand {
}); });
if (teleportOwner == null) { if (teleportOwner == null) {
teleportee.getAsyncTeleport().now(spawn, false, TeleportCause.COMMAND, future); teleportee.getAsyncTeleport().now(spawn, false, TeleportCause.COMMAND, future);
} else { return;
teleportOwner.getAsyncTeleport().teleportPlayer(teleportee, spawn, charge, TeleportCause.COMMAND, future);
} }
teleportOwner.getAsyncTeleport().teleportPlayer(teleportee, spawn, charge, TeleportCause.COMMAND, future);
} }
} }

View File

@ -13,7 +13,7 @@ public class Commandsetxmpp extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException {
if (args.length < 1) { if (args.length == 0 ) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException; import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import org.bukkit.ChatColor;
import org.bukkit.Server; import org.bukkit.Server;
@ -20,14 +21,15 @@ public class Commandxmpp extends EssentialsCommand {
final String address = EssentialsXMPP.getInstance().getAddress(args[0]); final String address = EssentialsXMPP.getInstance().getAddress(args[0]);
if (address == null) { if (address == null) {
sender.sendMessage("§cThere are no players matching that name."); sender.sendMessage(ChatColor.RED + "There are no players matching that name.");
} else { return;
final String message = getFinalArg(args, 1); }
final String senderName = sender.isPlayer() ? ess.getUser(sender.getPlayer()).getDisplayName() : Console.NAME;
sender.sendMessage("[" + senderName + ">" + address + "] " + message); final String message = getFinalArg(args, 1);
if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) { final String senderName = sender.isPlayer() ? ess.getUser(sender.getPlayer()).getDisplayName() : Console.NAME;
sender.sendMessage("§cError sending message."); sender.sendMessage("[" + senderName + ">" + address + "] " + message);
} if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) {
sender.sendMessage(ChatColor.RED + "Error sending message.");
} }
} }
} }

View File

@ -1,38 +1,36 @@
package com.earth2me.essentials.xmpp; package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsLoopCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException; import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.commands.PlayerExemptException;
import com.earth2me.essentials.commands.PlayerNotFoundException;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.List;
public class Commandxmppspy extends EssentialsCommand { public class Commandxmppspy extends EssentialsLoopCommand {
public Commandxmppspy() { public Commandxmppspy() {
super("xmppspy"); super("xmppspy");
} }
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException, PlayerExemptException, MaxMoneyException, ChargeException, PlayerNotFoundException {
if (args.length < 1) { if (args.length == 0) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final List<Player> matches = server.matchPlayer(args[0]); loopOnlinePlayers(server, sender, false, true, args[0], args);
}
if (matches.isEmpty()) { @Override
sender.sendMessage("§cThere are no players matching that name."); protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
} try {
sender.sendMessage("XMPP Spy " + (EssentialsXMPP.getInstance().toggleSpy(user.getBase()) ? "enabled" : "disabled") + " for " + user.getDisplayName());
for (Player p : matches) { } catch (Exception ex) {
try { sender.sendMessage("Error: " + ex.getMessage());
final boolean toggle = EssentialsXMPP.getInstance().toggleSpy(p);
sender.sendMessage("XMPP Spy " + (toggle ? "enabled" : "disabled") + " for " + p.getDisplayName());
} catch (Exception ex) {
sender.sendMessage("Error: " + ex.getMessage());
}
} }
} }
} }