Compare commits

..
36 Commits
Author SHA1 Message Date
md678685 c8dc874a56 Release 2.18.1 2020-08-23 17:18:31 +01:00
Josh Roy b3a6307052 Fix miscellaneous command permission bugs (#3616)
Fixes #3612, in which `/list`'s tab complete previously revealed the presence of vanished players in certain groups, and fixes #3613 in which `/time set` did not properly check whether the player had permission to change the time.
2020-08-22 20:07:21 +01:00
pop4959 3ca0181b79 Update block damaging checks in teleportation safety (#3537)
This PR updates and improves LocationUtil#isBlockDamaging. Notably, the lava check is fixed (it was not working on older versions of Minecraft), many newer materials that were missing damage checks have been added, and the code is a bit cleaner. I've tested this code on MC 1.8 and 1.16 and everything should work correctly.
2020-08-22 18:37:15 +01:00
pop4959 98557dcecf Add world border checking to teleportation safety (#3536)
Fixes #3499. Please see that issue for discussion about the bug.

Fix demonstration with `/tppos`: https://imgur.com/a/Mo4okQa
2020-08-22 17:51:23 +01:00
MD 3351092c79 Add "amplifier" potion meta attribute (#3614)
Adds an `amplifier:<value>` potion meta attribute to MetaItemStack that applies a raw amplifier value, instead of translating inputs between 1 and 3 to match their vanilla names like `power:<value>` does. This matches the Mojang `/effect` command, which doesn't translate any potion effect amplifiers, and allows for creation of level IV potions (using `amplifier:3` instead of a `power` value) through EssentialsX without breaking existing usages of `power:<value>`.

More context for this commit can be found at https://github.com/EssentialsX/Essentials/pull/3592#issuecomment-678656107.

Closes #3592 and fixes #3589.
2020-08-22 17:40:40 +01:00
pop4959 68cd509d41 Fix /bigtree command on versions 1.12 and prior (#3569)
Fixes #3549.

Replaces the `Block#isPassable` check with `Material#isSolid`, which is compatible with all versions through 1.8 to 1.16.
2020-08-22 17:01:50 +01:00
xtomyserrax 5fa65b42ae Fix creeper player damage being cancelled incorrectly (#3604)
Previously, disabling creeper explosion block damage with the `protect.prevent.creeper-explosion` setting would also prevent players getting hurt. This fixes this, meaning servers can disable creeper block damage while still allowing players to take damage from creeper explosions.
2020-08-22 16:55:32 +01:00
Andre_601 bdae259a1d Update links in readme (#3596)
This PR updates several links:

- https://essentialsx.cf -> https://essentialsx.net
- Wiki links (Either github.io links or GitHub Wiki links) now point to their corresponding pages on the actual wiki (https://essentialsx.net/wiki/Home.html)
2020-08-22 16:49:50 +01:00
Jason fea86ea70e Add config note regarding displayname (#3535) 2020-08-22 14:15:24 +01:00
Josh Roy 1133770aeb Fix changing players' gamemodes from the console (#3590)
Fixes #3587 which was introduced by #3337.
2020-08-21 16:37:54 +01:00
MD 2c462106bc Fix blacklisted blocks being pulled by pistons (#3610)
Closes #3609.
2020-08-21 16:31:34 +01:00
triagonal bd1e624c91 clarify piston blacklist config comment 2020-08-21 23:00:56 +10:00
triagonal 6875fa4c7e fix blacklisted blocks being pulled by sticky piston 2020-08-21 23:00:18 +10:00
pop4959 def5f2155d Fix compilation issues on latest Spigot/Paper (#3607) 2020-08-20 19:24:42 +01:00
triagonal 73d2457fea Fix regression with teleportation commands where command cost gets charged twice (#3601) 2020-08-16 14:40:58 -07:00
MD bc52ca856e Update to 1.16.2 (#3586) 2020-08-11 23:12:41 +01:00
Flask Bot 18ccea320a Update items.json from generator
Note: this action was performed by a human (@md678685) under the
Flask-Bot account.
2020-08-11 23:06:07 +01:00
Josh Roy f6cb9ff470 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)
2020-08-11 19:09:22 +01:00
pop4959 14c6c2a055 Fix spawner delay feature (#3239)
Closes #1332

The spawner delay feature has been broken in Essentials for as long as anyone can remember. The reasons for this are mentioned in the issue above.

This PR fixes this by changing the command to utilize new API for setting the minimum and maximum spawn delay on spawners. This API was added in 1.12.2, so all supported versions before that (1.8.8 thru 1.12.1) require NMS to function properly. I'm aware that Essentials avoids NMS for maintainability reasons, however that should not be of much concern here since all versions 1.12.2 and later are going to be using the Bukkit API. Hence, no NMS updates will be necessary.

Also let me know if you want the NMS code refactored somewhere else. I saw the net.ess3.nms packages, but I wasn't sure where this would fit into the organisation of that.

Tested on:
1.8.8, 1.9.4, 1.10.2, 1.11.2 (NMS)
1.12.2, 1.15.2 (Bukkit API)
2020-08-05 20:47:42 +01:00
pop4959 68d0aa9688 Improve GeoIP errors/warnings (#3568)
Aims to provide a better and less confusing error for users of GeoIP who have not configured properly (which is more common now after the license key requirement). Seems like a lot of people miss the initial error on startup, and so this may help a bit.

Closes #3561.
2020-08-04 16:22:14 +01:00
MD 1ef4e15a4d Fix regression in /tpaccept (#3567)
d9bf099c3d introduced a regression where `/tpaccept` no longer unconditionally cancels the teleportation request when it is accepted. This restores the previous request cancellation behaviour.

Fixes #3563.
2020-08-04 16:20:24 +01:00
latiku d35b4b9128 Don't send chat messages if they only contain formatting codes (#3505)
Closes #3442.

When a player with the appropriate permission node to use color formatting codes sends a message with nothing but valid formatting code, a message with an empty line is sent. This PR solves this issue by checking if the final formatted message is just a color code, and if so, cancels the event.

Below are some attached screenshots with debug messages containing the event's raw message, the event message after it is formatted, and in the case of the "before" screenshot, the message sent in-game. 

Before: https://user-images.githubusercontent.com/47498808/87505823-7a8c5080-c62f-11ea-99b4-29fc6eaff042.png

After: https://user-images.githubusercontent.com/47498808/87505857-8c6df380-c62f-11ea-95f8-dd59dadaf27c.png
2020-08-04 15:38:53 +01:00
Zefferis 6995be7dbd Updated website in plugin.yml files (#3528)
Replaced "http://tiny.cc/EssentialsCommands" with "https://essentialsx.net"
2020-08-04 15:35:34 +01:00
uf0h f9de6763d3 Use playerNeverOnServer message where appropriate (#3489)
### Use `playerNeverOnServer` message where it should be used:

### https://github.com/EssentialsX/Essentials/pull/3489/commits/309e1c470d4bcfe2a2186f9720ce33f26441b802 
`playerNeverOnServer=\u00a74Player\u00a7c {0} \u00a74was never on this server.` is currently used in the **Commandmail** class at [Line 61](https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/commands/Commandmail.java#L61), [Line 116](https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/commands/Commandmail.java#L116) and [Line 129](https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/commands/Commandmail.java#L129) however is **not called** as PlayerNotFoundException is thrown by `#getPlayer` breaking current execution (below).
```
Commandmail#run() throws Exception {
...
    User u = getPlayer(server, args[1], true, true); // throws PlayerNotFoundException
        if (u == null) {
            throw new Exception(tl("playerNeverOnServer", args[1]));
    } 
...
}
```

Before changes:
![bm](https://user-images.githubusercontent.com/24858857/87236993-6b679180-c3e8-11ea-83a7-002194f5c467.png)
After changes:
![mailafter](https://user-images.githubusercontent.com/24858857/87237060-3576dd00-c3e9-11ea-8020-d5a80a958ca0.png)

--------------------------

**Commandseen** currently throws the default PlayerNotFoundException `playerNotFound` message for players that have not logged on to the server where it would be more appropriate to use the `playerNeverOnServer` message.

```
Commandseen#run throws Exception {
...
    AsyncRunnable#run() {
        User userFromBukkit = ess.getUserMap().getUserFromBukkit(args[0]);  <-- ***
        try {
            if (userFromBukkit != null) {                             <--- ***
                showUserSeen(userFromBukkit);
            } else {
                showUserSeen(getPlayer(server, sender, args, 0)); <--- ***
            }
        } catch (Exception e) {
            ess.showError(sender, e, commandLabel);
        }
    }
    private void showUserSeen(User user) throws Exception {
        if (user == null) {                                    <--- ***
            throw new PlayerNotFoundException();
        }
        showSeenMessage(server, sender, user, showBan, showIp, showLocation);
    }
...
}
```

**`<-- ***`:**
`usersFromBukkit` null check is performed before `#showUserSeen` so there is no need for another null check.
`EssentialsCommand#getPlayer` throws **NotEnoughArguementsException** or **PlayerNotFoundException** after [arg checks](https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java#L88) and [player checks](https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java#L103). https://github.com/EssentialsX/Essentials/pull/3489#issuecomment-657138524

Before changes:
![sb](https://user-images.githubusercontent.com/24858857/87237038-e9c43380-c3e8-11ea-8294-8f91e8b6f25d.png)
After changes:
![seenafter](https://user-images.githubusercontent.com/24858857/87237067-53444200-c3e9-11ea-92c5-1784b4dcd739.png)

----------------

### 725128e
Catch more specfic exception `PlayerNotFoundException`.

Before changes:
![banbefore](https://user-images.githubusercontent.com/24858857/87237021-c1d4d000-c3e8-11ea-99e4-eb97b5a5ba6d.png)
After changes:
![afterunban](https://user-images.githubusercontent.com/24858857/87237081-8d154880-c3e9-11ea-9d35-a25b8c105969.png)
2020-08-04 15:30:05 +01:00
pop4959 dfce971565 Fix stale tpaccept 2020-08-04 02:37:37 -07:00
Olivia 97e3f32d7f Fix some minor errors in config/docs (#3566) 2020-08-04 01:13:09 -07:00
Cameron Seid c86e1a5973 Update backup comments in config.yml to be less ambiguous (#3553) 2020-07-30 21:58:19 -07:00
md678685 ab545dc44c Fix rare ConcurrentModificationException in quit handler
Copies the list of viewers before iterating over it to fix a rare CME that is *sometimes* thrown. It's not clear *why* this broke - Spigot seems to have changed behaviour in late 1.15 or 1.16?
2020-07-30 14:23:22 +01:00
Josh Roy 11cd57e8fb Add sign text tab completion in editsign command (#3497) 2020-07-28 13:12:07 -07:00
pop4959 b7c18d0785 Add missing getRecipe(NamespacedKey) method to FakeServer (#3530) 2020-07-22 12:02:00 -07:00
Josh Roy 9aec89f381 Properly handle jail respawn in togglejail (#3522) 2020-07-21 16:22:20 -07:00
Josh Roy e34984513d Add config option to respawn at respawn anchors (#3498) 2020-07-17 14:13:30 -07:00
Tim S cedd42f411 Fix how random teleport picks a location (#3480) 2020-07-17 13:56:48 -07:00
untuned c9b75aabb2 include new sign types in definitions (#3487) 2020-07-11 15:21:33 -07:00
pop4959 41ae12ed3d Disable random tp pre-cache by default (#3496) 2020-07-11 12:35:19 -07:00
JakeTS dba35f043d Typo, should be "match" not "maths". (#3488) 2020-07-10 21:10:12 -07:00
159 changed files with 1685 additions and 1599 deletions

No files matched your search

+5 -5
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.18.0</version>
<version>2.18.1</version>
</parent>
<artifactId>EssentialsX</artifactId>
@@ -75,13 +75,13 @@
<dependency>
<groupId>net.ess3</groupId>
<artifactId>BaseProviders</artifactId>
<version>2.18.0</version>
<version>2.18.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>NMSReflectionProvider</artifactId>
<version>2.18.0</version>
<version>2.18.1</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
@@ -93,7 +93,7 @@
<dependency>
<groupId>net.ess3</groupId>
<artifactId>PaperProvider</artifactId>
<version>2.18.0</version>
<version>2.18.1</version>
<exclusions>
<exclusion>
<groupId>com.destroystokyo.paper</groupId>
@@ -105,7 +105,7 @@
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8Provider</artifactId>
<version>2.18.0</version>
<version>2.18.1</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
@@ -179,8 +179,13 @@ public class AsyncTeleport implements IAsyncTeleport {
}
}
teleportee.setLastLocation();
PaperLib.getChunkAtAsync(target.getLocation()).thenAccept(chunk -> {
Location loc = target.getLocation();
final Location targetLoc = target.getLocation();
if (ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockOutsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockX(), targetLoc.getBlockZ())) {
targetLoc.setX(LocationUtil.getXInsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockX()));
targetLoc.setZ(LocationUtil.getZInsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockZ()));
}
PaperLib.getChunkAtAsync(targetLoc).thenAccept(chunk -> {
Location loc = targetLoc;
if (LocationUtil.isBlockUnsafeForUser(teleportee, chunk.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) {
if (ess.getSettings().isTeleportSafetyEnabled()) {
if (ess.getSettings().isForceDisableTeleportSafety()) {
@@ -22,8 +22,15 @@ public class CommandSource {
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() {
return (sender instanceof Player);
return sender instanceof Player;
}
public final CommandSender setSender(final CommandSender base) {
@@ -36,4 +43,12 @@ public class CommandSource {
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() : "*";
}
}
@@ -33,18 +33,19 @@ import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.base.Throwables;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.api.ISettings;
import net.ess3.api.*;
import net.ess3.nms.refl.providers.ReflServerStateProvider;
import net.ess3.nms.refl.providers.ReflSpawnEggProvider;
import net.ess3.nms.refl.providers.ReflSpawnerBlockProvider;
import net.ess3.provider.PotionMetaProvider;
import net.ess3.provider.ProviderListener;
import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SpawnEggProvider;
import net.ess3.provider.SpawnerProvider;
import net.ess3.provider.SpawnerBlockProvider;
import net.ess3.provider.SpawnerItemProvider;
import net.ess3.provider.providers.*;
import org.bukkit.Bukkit;
import org.bukkit.Server;
@@ -75,13 +76,10 @@ import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
@@ -106,8 +104,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient MetricsWrapper metrics;
private transient EssentialsTimer timer;
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private transient Method oldGetOnlinePlayers;
private transient SpawnerProvider spawnerProvider;
private transient SpawnerItemProvider spawnerItemProvider;
private transient SpawnerBlockProvider spawnerBlockProvider;
private transient SpawnEggProvider spawnEggProvider;
private transient PotionMetaProvider potionMetaProvider;
private transient ServerStateProvider serverStateProvider;
@@ -182,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 {
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
@@ -244,8 +235,15 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
confList.add(jails);
execTimer.mark("Init(Jails)");
//Spawner provider only uses one but it's here for legacy...
spawnerProvider = new BlockMetaSpawnerProvider();
//Spawner item provider only uses one but it's here for legacy...
spawnerItemProvider = new BlockMetaSpawnerItemProvider();
//Spawner block providers
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) {
spawnerBlockProvider = new ReflSpawnerBlockProvider();
} else {
spawnerBlockProvider = new BukkitSpawnerBlockProvider();
}
//Spawn Egg Providers
if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_8_8_R01)) {
@@ -623,6 +621,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
if (!ex.getMessage().isEmpty()) {
sender.sendMessage(ex.getMessage());
}
if (ex.getCause() != null && settings.isDebug()) {
ex.getCause().printStackTrace();
}
return true;
} catch (Exception ex) {
showError(sender, ex, commandLabel);
@@ -926,27 +927,26 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override
public Collection<Player> getOnlinePlayers() {
try {
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);
}
return (Collection<Player>) getServer().getOnlinePlayers();
}
@Override
public List<User> getOnlineUsers() {
List<User> onlineUsers = new ArrayList<>();
for (Player player : getOnlinePlayers()) {
onlineUsers.add(getUser(player));
}
return onlineUsers;
}
@Override
public Iterable<User> getOnlineUsers() {
return getOnlinePlayers().stream().map(this::getUser).collect(Collectors.toList());
public SpawnerItemProvider getSpawnerItemProvider() {
return spawnerItemProvider;
}
@Override
public SpawnerProvider getSpawnerProvider() {
return spawnerProvider;
public SpawnerBlockProvider getSpawnerBlockProvider() {
return spawnerBlockProvider;
}
@Override
@@ -37,7 +37,7 @@ public class EssentialsBlockListener implements Listener {
final BlockState blockState = event.getBlockPlaced().getState();
if (blockState instanceof CreatureSpawner) {
final CreatureSpawner spawner = (CreatureSpawner) blockState;
final EntityType type = ess.getSpawnerProvider().getEntityType(event.getItemInHand());
final EntityType type = ess.getSpawnerItemProvider().getEntityType(event.getItemInHand());
if (type != null && Mob.fromBukkitType(type) != null) {
if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + Mob.fromBukkitType(type).name().toLowerCase(Locale.ENGLISH))) {
spawner.setSpawnedType(type);
@@ -212,7 +212,8 @@ public class EssentialsPlayerListener implements Listener {
user.getBase().getOpenInventory().getTopInventory().clear();
}
for (HumanEntity viewer : user.getBase().getInventory().getViewers()) {
ArrayList<HumanEntity> viewers = new ArrayList<>(user.getBase().getInventory().getViewers());
for (HumanEntity viewer : viewers) {
if (viewer instanceof Player) {
User uviewer = ess.getUser((Player) viewer);
if (uviewer.isInvSee()) {
@@ -6,7 +6,8 @@ import com.earth2me.essentials.api.IWarps;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SpawnerProvider;
import net.ess3.provider.SpawnerBlockProvider;
import net.ess3.provider.SpawnerItemProvider;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@@ -101,9 +102,11 @@ public interface IEssentials extends Plugin {
Collection<Player> getOnlinePlayers();
Iterable<User> getOnlineUsers();
Collection<User> getOnlineUsers();
SpawnerProvider getSpawnerProvider();
SpawnerItemProvider getSpawnerItemProvider();
SpawnerBlockProvider getSpawnerBlockProvider();
ServerStateProvider getServerStateProvider();
}
@@ -107,6 +107,8 @@ public interface ISettings extends IConf {
boolean getRespawnAtHome();
boolean isRespawnAtAnchor();
Set getMultipleHomes();
int getHomeLimit(String set);
@@ -179,6 +179,8 @@ public interface IUser {
String getName();
String getDisplayName();
String getAfkMessage();
void setAfkMessage(final String message);
@@ -367,6 +367,13 @@ public class MetaItemStack {
} else {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("amplifier") || (allowShortName && split[0].equalsIgnoreCase("a"))) {
if (NumberUtil.isInt(split[1])) {
validPotionPower = true;
power = Integer.parseInt(split[1]);
} else {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) {
if (NumberUtil.isInt(split[1])) {
validPotionDuration = true;
@@ -97,6 +97,7 @@ public enum Mob {
PIGLIN("Piglin", Enemies.ADULT_ENEMY, "PIGLIN"),
STRIDER("Strider", Enemies.FRIENDLY, "STRIDER"),
ZOGLIN("Zoglin", Enemies.ENEMY, "ZOGLIN"),
PIGLIN_BRUTE("PiglinBrute", Enemies.ADULT_ENEMY, "PIGLIN_BRUTE"),
;
public static final Logger logger = Logger.getLogger("Essentials");
@@ -59,7 +59,7 @@ public class PlayerList {
}
// Build the basic player list, divided by groups.
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final User sender, final boolean showHidden) {
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final IUser sender, final boolean showHidden) {
final Map<String, List<User>> playerList = new HashMap<>();
for (User onlineUser : ess.getOnlineUsers()) {
if ((sender == null && !showHidden && onlineUser.isHidden()) || (sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase()))) {
@@ -97,7 +97,7 @@ public class RandomTeleport implements IConf {
}
public boolean getPreCache() {
return config.getBoolean("pre-cache", true);
return config.getBoolean("pre-cache", false);
}
public Queue<Location> getCachedLocations() {
@@ -155,12 +155,29 @@ public class RandomTeleport implements IConf {
// Calculates a random location asynchronously.
private CompletableFuture<Location> calculateRandomLocation(Location center, double minRange, double maxRange) {
CompletableFuture<Location> future = new CompletableFuture<>();
final int dx = RANDOM.nextBoolean() ? 1 : -1, dz = RANDOM.nextBoolean() ? 1 : -1;
// Find an equally distributed offset by randomly rotating a point inside a rectangle about the origin
double rectX = RANDOM.nextDouble() * (maxRange - minRange) + minRange;
double rectZ = RANDOM.nextDouble() * (maxRange + minRange) - minRange;
double offsetX, offsetZ;
int transform = RANDOM.nextInt(4);
if (transform == 0) {
offsetX = rectX;
offsetZ = rectZ;
} else if (transform == 1) {
offsetX = -rectZ;
offsetZ = rectX;
} else if (transform == 2) {
offsetX = -rectX;
offsetZ = -rectZ;
} else {
offsetX = rectZ;
offsetZ = -rectX;
}
Location location = new Location(
center.getWorld(),
center.getX() + dx * (minRange + RANDOM.nextDouble() * (maxRange - minRange)),
center.getX() + offsetX,
center.getWorld().getMaxHeight(),
center.getZ() + dz * (minRange + RANDOM.nextDouble() * (maxRange - minRange)),
center.getZ() + offsetZ,
360 * RANDOM.nextFloat() - 180,
0
);
@@ -61,6 +61,11 @@ public class Settings implements net.ess3.api.ISettings {
return config.getBoolean("respawn-at-home", false);
}
@Override
public boolean isRespawnAtAnchor() {
return config.getBoolean("respawn-at-anchor", false);
}
@Override
public boolean getUpdateBedAtDaytime() {
return config.getBoolean("update-bed-at-daytime", true);
@@ -15,7 +15,6 @@ import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.JailStatusChangeEvent;
import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@@ -325,11 +324,25 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return teleportLocation;
}
public String getNick(final boolean longnick) {
return getNick(longnick, true, true);
public String getNick() {
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();
String nickname;
String suffix = "";
@@ -377,15 +390,6 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final String strPrefix = prefix.toString();
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) == '§') {
output = output.substring(0, output.length() - 1);
}
@@ -398,10 +402,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (isAfk()) {
updateAfkListName();
} else if (ess.getSettings().changePlayerListName()) {
// 1.8 enabled player list-names longer than 16 characters.
// 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());
String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
try {
this.getBase().setPlayerListName(name);
} catch (IllegalArgumentException e) {
@@ -413,6 +414,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
}
@Override
public String getDisplayName() {
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
}
@@ -4,10 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
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 {
CommandSource sender = user.getSource();
if (args.length > 0 && user.isAuthorized("essentials.back.others")) {
this.parseCommand(server, sender, args, true, commandLabel);
parseOthers(server, sender, args, commandLabel);
return;
}
@@ -32,28 +29,17 @@ public class Commandback extends EssentialsCommand {
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (args.length < 1) {
if (args.length == 0) {
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 {
Collection<Player> players = new ArrayList<>();
if (allowOthers && args.length > 0 && args[0].trim().length() > 2) {
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 parseOthers(Server server, CommandSource sender, String[] args, String commandLabel) throws Exception {
User player = getPlayer(server, args, 0, true, false);
sender.sendMessage(tl("backOther", player.getName()));
teleportBack(sender, player, commandLabel);
}
private void teleportBack(CommandSource sender, User user, String commandLabel) throws Exception {
@@ -5,7 +5,6 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
@@ -19,7 +18,7 @@ public class Commandbalance extends EssentialsCommand {
@Override
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();
}
@@ -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 {
if (args.length == 1 && user.isAuthorized("essentials.balance.others")) {
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(bal, ess)));
user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
} else if (args.length < 2) {
final BigDecimal bal = user.getMoney();
user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess)));
user.sendMessage(tl("balance", NumberUtil.displayCurrency(user.getMoney(), ess)));
} else {
throw new NotEnoughArgumentsException();
}
@@ -44,7 +44,7 @@ public class Commandbalancetop extends EssentialsCommand {
if (!force && lock.readLock().tryLock()) {
try {
if (cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page);
outputCache(sender, page);
return;
}
if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
@@ -53,17 +53,16 @@ public class Commandbalancetop extends EssentialsCommand {
} finally {
lock.readLock().unlock();
}
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
} else {
if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
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();
cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
@@ -149,7 +148,7 @@ public class Commandbalancetop extends EssentialsCommand {
lock.readLock().lock();
try {
if (!force && cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page);
outputCache(sender, page);
return;
}
} finally {
@@ -34,7 +34,7 @@ public class Commandbigtree extends EssentialsCommand {
}
final Location loc = LocationUtil.getTarget(user.getBase()).add(0, 1, 0);
if (!user.getWorld().getBlockAt(loc).isPassable()) {
if (loc.getBlock().getType().isSolid()) {
throw new Exception(tl("bigTreeFailure"));
}
final boolean success = user.getWorld().generateTree(loc, tree);
@@ -17,10 +17,8 @@ public class Commandbreak extends EssentialsCommand {
//TODO: Switch to use util class
@Override
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);
if (block == null) {
throw new NoChargeException();
}
if (block.getType() == Material.AIR) {
throw new NoChargeException();
}
@@ -1,7 +1,5 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
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.utils.FormatUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
@@ -18,6 +15,8 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcastworld extends EssentialsCommand {
@@ -27,12 +26,13 @@ public class Commandbroadcastworld extends EssentialsCommand {
@Override
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();
String message = getFinalArg(args, 0);
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
World argWorld = ess.getWorld(args[0]);
if (argWorld != null) {
world = argWorld;
@@ -40,12 +40,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
}
}
if (world == null) {
world = user.getWorld();
message = getFinalArg(args, 0);
}
sendBroadcast(world.getName(), user.getDisplayName(), message);
sendBroadcast(world, user.getDisplayName(), message);
}
@Override
@@ -53,14 +48,15 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (args.length < 2) {
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(worldName);
World world = ess.getWorld(args[0]);
if (world == null) {
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()) {
throw new NotEnoughArgumentsException();
}
@@ -21,10 +21,6 @@ public class Commandburn extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
if (args[0].trim().length() < 2) {
throw new NotEnoughArgumentsException();
}
User user = getPlayer(server, sender, args, 0);
user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1])));
@@ -16,73 +16,56 @@ import java.util.*;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand {
public class Commandclearinventory extends EssentialsLoopCommand {
public Commandclearinventory() {
super("clearinventory");
}
private static final int BASE_AMOUNT = 100000;
private static final int EXTENDED_CAP = 8;
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
parseCommand(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.clearinventory.others"),
user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple"));
}
final String previousClearCommand = user.getConfirmingClearCommand();
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);
if (senderUser != null && senderUser.isPromptingClearConfirm()) {
if (user.isPromptingClearConfirm()) {
if (!formattedCommand.equals(previousClearCommand)) {
senderUser.setConfirmingClearCommand(formattedCommand);
senderUser.sendMessage(tl("confirmClear", formattedCommand));
user.setConfirmingClearCommand(formattedCommand);
user.sendMessage(tl("confirmClear", formattedCommand));
return;
}
}
for (Player player : players) {
clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP);
if (args.length == 0 || (!args[0].contains("*") && server.matchPlayer(args[0]).isEmpty())) {
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 Material material;
private short data;
private final Material material;
private final short data;
public Item(Material material, short data) {
this.material = material;
@@ -102,7 +85,7 @@ public class Commandclearinventory extends EssentialsCommand {
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;
final Set<Item> items = new HashSet<>();
int amount = -1;
@@ -131,18 +114,12 @@ public class Commandclearinventory extends EssentialsCommand {
}
}
if (type == ClearHandlerType.ALL_EXCEPT_ARMOR)
{
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
}
if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) {
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null);
} else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR)
{
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
}
} else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) {
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null);
player.getInventory().setArmorContents(null);
@@ -157,7 +134,7 @@ public class Commandclearinventory extends EssentialsCommand {
stack.setAmount(BASE_AMOUNT);
ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
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()));
}
} else {
@@ -165,10 +142,6 @@ public class Commandclearinventory extends EssentialsCommand {
if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
}
}
}
}
@@ -15,7 +15,7 @@ public class Commanddeljail extends EssentialsCommand {
@Override
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();
}
@@ -18,7 +18,7 @@ public class Commanddelkit extends EssentialsCommand {
@Override
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);
sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException();
@@ -17,7 +17,7 @@ public class Commanddelwarp extends EssentialsCommand {
@Override
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();
}
@@ -18,9 +18,6 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandeco extends EssentialsLoopCommand {
Commandeco.EcoCommands cmd;
BigDecimal amount;
boolean isPercent;
public Commandeco() {
super("eco");
@@ -32,75 +29,49 @@ public class Commandeco extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException();
}
BigDecimal startingBalance = ess.getSettings().getStartingBalance();
EcoCommands cmd;
boolean isPercent;
BigDecimal amount;
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("%");
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) {
throw new NotEnoughArgumentsException(ex);
}
loopOfflinePlayers(server, sender, false, true, args[1], args);
if (cmd == Commandeco.EcoCommands.RESET || cmd == Commandeco.EcoCommands.SET) {
if (args[1].contentEquals("**")) {
server.broadcastMessage(tl("resetBalAll", NumberUtil.displayCurrency(amount, ess)));
} else if (args[1].contentEquals("*")) {
server.broadcastMessage(tl("resetBal", NumberUtil.displayCurrency(amount, ess)));
loopOfflinePlayersConsumer(server, sender, false, true, args[1], player -> {
BigDecimal userAmount = amount;
if (isPercent) {
userAmount = player.getMoney().multiply(userAmount).scaleByPowerOfTen(-2);
}
}
}
@Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException {
if (isPercent && cmd != EcoCommands.RESET) {
amount = player.getMoney().multiply(amount).scaleByPowerOfTen(-2);
}
switch (cmd) {
case GIVE:
player.giveMoney(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
break;
case TAKE:
take(amount, player, sender);
break;
case RESET:
case SET:
set(amount, player, sender);
break;
}
}
private void take(BigDecimal amount, final User player, final CommandSource sender) throws ChargeException {
BigDecimal money = player.getMoney();
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
switch (cmd) {
case GIVE: {
player.giveMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
break;
}
case TAKE: {
if (player.getMoney().subtract(userAmount).compareTo(ess.getSettings().getMinMoney()) >= 0) {
player.takeMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
} else {
ess.showError(sender, new Exception(tl("minimumBalanceError", NumberUtil.displayCurrency(ess.getSettings().getMinMoney(), ess))), commandLabel);
}
break;
}
case RESET:
case SET: {
BigDecimal minBal = ess.getSettings().getMinMoney();
BigDecimal maxBal = ess.getSettings().getMaxMoney();
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)));
sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
break;
}
}
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
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
}
@Override
protected List<String> getTabCompleteOptions(Server server, final CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) {
@@ -67,6 +67,14 @@ public class Commandeditsign extends EssentialsCommand {
return Lists.newArrayList("set", "clear");
} else if (args.length == 2) {
return Lists.newArrayList("1", "2", "3", "4");
} else if (args.length == 3 && args[0].equalsIgnoreCase("set") && NumberUtil.isPositiveInt(args[1])) {
int line = Integer.parseInt(args[1]);
Block target = user.getBase().getTargetBlock(null, 5);
if (target.getState() instanceof Sign && line <= 4) {
Sign sign = (Sign) target.getState();
return Lists.newArrayList(FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(line - 1)));
}
return Collections.emptyList();
} else {
return Collections.emptyList();
}
@@ -11,13 +11,7 @@ import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import java.util.Collections;
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 java.util.*;
import static com.earth2me.essentials.I18n.tl;
@@ -34,16 +28,16 @@ public class Commandenchant extends EssentialsCommand {
if (stack == null || stack.getType() == Material.AIR) {
throw new Exception(tl("nothingInHand"));
}
if (args.length == 0) {
final Set<String> enchantmentslist = new TreeSet<>();
final Set<String> usableEnchants = new TreeSet<>();
for (Map.Entry<String, Enchantment> entry : Enchantments.entrySet()) {
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || (user.isAuthorized("essentials.enchantments." + enchantmentName) && entry.getValue().canEnchantItem(stack))) {
enchantmentslist.add(entry.getKey());
//enchantmentslist.add(enchantmentName);
final String name = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (usableEnchants.contains(name) || (user.isAuthorized("essentials.enchantments." + name) && entry.getValue().canEnchantItem(stack))) {
usableEnchants.add(entry.getKey());
}
}
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray())));
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(usableEnchants.toArray())));
}
int level = 1;
@@ -51,23 +45,20 @@ public class Commandenchant extends EssentialsCommand {
try {
level = Integer.parseInt(args[1]);
} 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 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());
user.getBase().updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
final String enchantName = enchantment.getName().toLowerCase(Locale.ENGLISH).replace('_', ' ');
if (level == 0) {
user.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' ')));
user.sendMessage(tl("enchantmentRemoved", enchantName));
} else {
user.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' ')));
user.sendMessage(tl("enchantmentApplied", enchantName));
}
}
@@ -13,17 +13,14 @@ public class Commandenderchest extends EssentialsCommand {
@Override
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")) {
final User invUser = 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);
target = getPlayer(server, user, args, 0);
}
user.getBase().closeInventory();
user.getBase().openInventory(target.getBase().getEnderChest());
user.setEnderSee(!target.equals(user));
}
@Override
@@ -1,13 +1,14 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -15,126 +16,121 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsCommand {
public class Commandexp extends EssentialsLoopCommand {
public Commandexp() {
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
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 2 && args[0].equalsIgnoreCase("set")) {
expMatch(server, sender, args[1], args[2], false);
} 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();
IUser user = sender.getUser(ess);
if (args.length == 0 || (args.length < 2 && user == null)) {
if (user == null) {
throw new NotEnoughArgumentsException();
}
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 {
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) {
private void showExp(final CommandSource sender, final IUser target) {
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
}
//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;
strAmount = strAmount.toLowerCase(Locale.ENGLISH);
if (strAmount.contains("l")) {
@@ -165,21 +161,18 @@ public class Commandexp extends EssentialsCommand {
sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
List<String> options = Lists.newArrayList("show");
if (user.isAuthorized("essentials.exp.set")) {
options.add("set");
}
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");
for (ExpCommands cmd : ExpCommands.values()) {
if (cmd.hasPermission(user)) {
options.add(cmd.name().toLowerCase(Locale.ENGLISH));
}
}
return options;
} else if (args.length == 2) {
@@ -204,8 +197,11 @@ public class Commandexp extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
// TODO: This seems somewhat buggy, both setting and showing - right now, ignoring that
return Lists.newArrayList("set", "give", "show", "take", "reset");
List<String> list = new ArrayList<>();
for (ExpCommands cmd : ExpCommands.values()) {
list.add(cmd.name().toLowerCase(Locale.ENGLISH));
}
return list;
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", "");
@@ -18,7 +18,7 @@ public class Commandext extends EssentialsLoopCommand {
@Override
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();
}
@@ -53,13 +53,9 @@ public class Commandfireball extends EssentialsCommand {
@Override
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;
boolean ride = false;
if (args.length > 0 && types.containsKey(args[0])) {
type = args[0];
}
boolean ride = args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride");
if (args.length > 1) {
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)) {
throw new Exception(tl("noPerm", "essentials.fireball." + type));
}
@@ -43,79 +43,79 @@ public class Commandfirework extends EssentialsCommand {
@Override
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();
if (MaterialUtil.isFirework(stack.getType())) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("clear")) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared"));
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try {
int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power);
} catch (NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
}
stack.setItemMeta(fmeta);
} else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) {
int amount = 1;
boolean direction = false;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
final int serverLimit = ess.getSettings().getSpawnMobLimit();
amount = Integer.parseInt(args[1]);
if (amount > serverLimit) {
amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit"));
}
} else {
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);
if (!MaterialUtil.isFirework(stack.getType())) {
throw new Exception(tl("holdFirework"));
}
if (args[0].equalsIgnoreCase("clear")) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared"));
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try {
int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power);
} catch (NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
}
stack.setItemMeta(fmeta);
} else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) {
int amount = 1;
boolean direction = false;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
final int serverLimit = ess.getSettings().getSpawnMobLimit();
amount = Integer.parseInt(args[1]);
if (amount > serverLimit) {
amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit"));
}
} else {
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"));
}
direction = true;
}
} 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 {
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"));
}
}
}
@@ -27,9 +27,8 @@ public class Commandfly extends EssentialsToggleCommand {
if (enabled == null) {
enabled = !user.getBase().getAllowFlight();
}
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, controller, enabled);
FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled);
ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
@@ -1,11 +1,11 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.google.common.collect.ImmutableList;
import org.bukkit.GameMode;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@@ -14,22 +14,19 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandgamemode extends EssentialsCommand {
public class Commandgamemode extends EssentialsLoopCommand {
public Commandgamemode() {
super("gamemode");
}
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
GameMode gameMode;
if (args.length == 0) {
throw new NotEnoughArgumentsException();
} else if (args.length == 1) {
gameMode = matchGameMode(commandLabel);
gamemodeOtherPlayers(server, sender, gameMode, args[0]);
loopOnlinePlayersConsumer(server, sender, false, true, args[0], user -> setUserGamemode(sender, matchGameMode(commandLabel), user));
} else if (args.length == 2) {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
gamemodeOtherPlayers(server, sender, gameMode, args[1]);
loopOnlinePlayersConsumer(server, sender, false, true, args[1], user -> setUserGamemode(sender, matchGameMode(args[0]), user));
}
}
@@ -40,16 +37,14 @@ public class Commandgamemode extends EssentialsCommand {
if (args.length == 0) {
gameMode = matchGameMode(commandLabel);
} else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[1]);
loopOnlinePlayersConsumer(server, user.getSource(), false, true, args[1], player -> setUserGamemode(user.getSource(), matchGameMode(args[0].toLowerCase(Locale.ENGLISH)), player));
return;
} else {
try {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
} catch (NotEnoughArgumentsException e) {
if (user.isAuthorized("essentials.gamemode.others")) {
gameMode = matchGameMode(commandLabel);
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[0]);
loopOnlinePlayersConsumer(server, user.getSource(), false, true, args[0], player -> setUserGamemode(user.getSource(), matchGameMode(commandLabel), player));
return;
}
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;
}
if (!canChangeToMode(user, gameMode)) {
if (isProhibitedChange(user, gameMode)) {
user.sendMessage(tl("cantGamemode", gameMode.name()));
return;
}
@@ -69,51 +64,37 @@ public class Commandgamemode extends EssentialsCommand {
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 {
if (name.trim().length() < 2 || gameMode == null) {
private void setUserGamemode(final CommandSource sender, final GameMode gameMode, final User user) throws NotEnoughArgumentsException {
if (gameMode == null) {
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()));
return;
}
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
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();
}
user.getBase().setGameMode(gameMode);
sender.sendMessage(tl("gameMode", tl(gameMode.toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName()));
}
// 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) {
return user.isAuthorized("essentials.gamemode.all") || user.isAuthorized("essentials.gamemode." + to.name().toLowerCase());
private boolean isProhibitedChange(IUser user, GameMode to) {
return user != null && !user.isAuthorized("essentials.gamemode.all") && !user.isAuthorized("essentials.gamemode." + to.name().toLowerCase());
}
private GameMode matchGameMode(String modeString) throws NotEnoughArgumentsException {
GameMode mode = null;
modeString = modeString.toLowerCase();
if (modeString.equalsIgnoreCase("gmc") || modeString.equalsIgnoreCase("egmc") || modeString.contains("creat") || modeString.equalsIgnoreCase("1") || modeString.equalsIgnoreCase("c")) {
mode = GameMode.CREATIVE;
} else if (modeString.equalsIgnoreCase("gms") || modeString.equalsIgnoreCase("egms") || modeString.contains("survi") || modeString.equalsIgnoreCase("0") || modeString.equalsIgnoreCase("s")) {
mode = GameMode.SURVIVAL;
} else if (modeString.equalsIgnoreCase("gma") || modeString.equalsIgnoreCase("egma") || modeString.contains("advent") || modeString.equalsIgnoreCase("2") || modeString.equalsIgnoreCase("a")) {
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")) {
mode = GameMode.SPECTATOR;
} else {
} else if (!modeString.equalsIgnoreCase("gmt") && !modeString.equalsIgnoreCase("egmt") && !modeString.contains("toggle") && !modeString.contains("cycle") && !modeString.equalsIgnoreCase("t")) {
throw new NotEnoughArgumentsException();
}
return mode;
@@ -159,4 +140,9 @@ public class Commandgamemode extends EssentialsCommand {
return Collections.emptyList();
}
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
}
@@ -19,7 +19,7 @@ import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandgive extends EssentialsCommand {
public class Commandgive extends EssentialsLoopCommand {
public Commandgive() {
super("give");
}
@@ -37,8 +37,6 @@ public class Commandgive extends EssentialsCommand {
throw new Exception(tl("cantSpawnItem", itemname));
}
final User giveTo = getPlayer(server, sender, args, 0);
try {
if (args.length > 3 && NumberUtil.isInt(args[2]) && NumberUtil.isInt(args[3])) {
stack.setAmount(Integer.parseInt(args[2]));
@@ -47,7 +45,7 @@ public class Commandgive extends EssentialsCommand {
stack.setAmount(Integer.parseInt(args[2]));
} else if (ess.getSettings().getDefaultStackSize() > 0) {
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());
}
} catch (NumberFormatException e) {
@@ -79,28 +77,29 @@ public class Commandgive extends EssentialsCommand {
}
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();
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 (isDropItemsIfFull) {
World w = giveTo.getWorld();
w.dropItemNaturally(giveTo.getLocation(), item);
if (player.isAuthorized("essentials.oversizedstacks")) {
leftovers = InventoryWorkaround.addOversizedItems(player.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), finalStack);
} 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
@@ -117,4 +116,9 @@ public class Commandgive extends EssentialsCommand {
return Collections.emptyList();
}
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
}
@@ -29,8 +29,7 @@ public class Commandgod extends EssentialsToggleCommand {
enabled = !user.isGodModeEnabled();
}
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(user, controller, enabled);
final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled);
ess.getServer().getPluginManager().callEvent(godEvent);
if (!godEvent.isCancelled()) {
user.setGodModeEnabled(enabled);
@@ -52,42 +52,46 @@ public class Commandhat extends EssentialsCommand {
@Override
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 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")) {
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"));
} else {
final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air);
InventoryWorkaround.addItems(user.getBase().getInventory(), head);
user.sendMessage(tl("hatRemoved"));
return;
}
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 {
final ItemStack hand = user.getItemInHand();
if (hand != null && hand.getType() != Material.AIR) {
if (user.isAuthorized("essentials.hat.prevent-type." + hand.getType().name().toLowerCase())) {
user.sendMessage(tl("hatFail"));
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"));
}
final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air);
InventoryWorkaround.addItems(user.getBase().getInventory(), head);
user.sendMessage(tl("hatRemoved"));
}
}
@@ -30,7 +30,7 @@ public class Commandheal extends EssentialsLoopCommand {
return;
}
healPlayer(user);
updatePlayer(server, user.getSource(), user, args);
}
@Override
@@ -43,45 +43,41 @@ public class Commandheal extends EssentialsLoopCommand {
}
@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 {
healPlayer(player);
sender.sendMessage(tl("healOther", player.getDisplayName()));
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());
}
}
sender.sendMessage(tl("healOther", user.getDisplayName()));
} catch (QuietAbortException e) {
//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
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.heal.others")) {
@@ -6,6 +6,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
@@ -20,7 +21,7 @@ public class Commandhelpop extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
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")) {
user.sendMessage(message);
}
@@ -28,10 +29,10 @@ public class Commandhelpop extends EssentialsCommand {
@Override
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) {
throw new NotEnoughArgumentsException();
}
@@ -43,6 +44,6 @@ public class Commandhelpop extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
return null; // Use vanilla handler for message
return Collections.emptyList();
}
}
@@ -64,7 +64,7 @@ public class Commandhome extends EssentialsCommand {
showError(user.getBase(), new Exception(tl("bedMissing")), commandLabel);
}
});
return;
throw new NoChargeException();
}
goHome(user, player, homeName.toLowerCase(Locale.ENGLISH), charge, getNewExceptionFuture(user.getSource(), commandLabel));
} catch (NotEnoughArgumentsException e) {
@@ -108,6 +108,7 @@ public class Commandhome extends EssentialsCommand {
}
PaperLib.getBedSpawnLocationAsync(player.getBase(), true).thenAccept(message::complete);
}
throw new NoChargeException();
}
private String getHomeLimit(final User player) {
@@ -17,7 +17,7 @@ public class Commandignore extends EssentialsCommand {
@Override
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();
for (UUID uuid : user._getIgnoredPlayers()) {
User curUser = ess.getUser(uuid);
@@ -27,25 +27,27 @@ public class Commandignore extends EssentialsCommand {
}
String ignoredList = sb.toString().trim();
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 {
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 {
user.setIgnoredPlayer(player, true);
user.sendMessage(tl("ignorePlayer", player.getName()));
}
user.setIgnoredPlayer(player, true);
user.sendMessage(tl("ignorePlayer", player.getName()));
}
}
@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
@@ -19,9 +18,7 @@ public class Commandinfo extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick();
}
final IText input = new TextInput(sender, "info", true, ess);
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "info", true, ess), sender, ess));
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
}
}
@@ -22,7 +22,7 @@ public class Commanditem extends EssentialsCommand {
@Override
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();
}
@@ -21,7 +21,7 @@ public class Commanditemdb extends EssentialsCommand {
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
ItemStack itemStack = null;
boolean itemHeld = false;
if (args.length < 1) {
if (args.length == 0) {
if (sender.isPlayer() && sender.getPlayer() != null) {
itemHeld = true;
itemStack = ess.getUser(sender.getPlayer()).getItemInHand();
@@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
@@ -19,13 +20,15 @@ public class Commanditemname extends EssentialsCommand {
@Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
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('_', ' ')));
return;
}
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();
im.setDisplayName(name);
@@ -14,7 +14,7 @@ public class Commandjails extends EssentialsCommand {
@Override
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"));
} else {
sender.sendMessage(tl("jailList", StringUtil.joinList(" ", ess.getJails().getList())));
@@ -24,10 +24,10 @@ public class Commandjump extends EssentialsCommand {
if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) {
if (user.isFlyClickJump()) {
user.setRightClickJump(false);
user.sendMessage("Flying wizard mode disabled");
user.sendMessage(tl("jumpEasterDisable"));
} else {
user.setRightClickJump(true);
user.sendMessage("Enabling flying wizard mode");
user.sendMessage(tl("jumpEasterEnable"));
}
return;
}
@@ -47,6 +47,8 @@ public class Commandjump extends EssentialsCommand {
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel));
throw new NoChargeException();
}
@Override
@@ -19,7 +19,7 @@ public class Commandkill extends EssentialsLoopCommand {
@Override
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();
}
@@ -27,12 +27,9 @@ public class Commandkit extends EssentialsCommand {
user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException();
} else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) {
final User userTo = getPlayer(server, user, args, 1);
final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKits(userTo, user, kitNames);
giveKits(getPlayer(server, user, args, 1), user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim());
} else {
final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKits(user, user, kitNames);
giveKits(user, user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim());
}
}
@@ -44,11 +41,9 @@ public class Commandkit extends EssentialsCommand {
throw new NoChargeException();
} else {
final User userTo = getPlayer(server, args, 1, true, false);
final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(",");
for (final String kitName : kits) {
final Kit kit = new Kit(kitName, ess);
kit.expandItems(userTo);
for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) {
new Kit(kitName, ess).expandItems(userTo);
sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName()));
userTo.sendMessage(tl("kitReceive", kitName));
@@ -60,11 +55,10 @@ public class Commandkit extends EssentialsCommand {
if (kitNames.isEmpty()) {
throw new Exception(tl("kitNotFound"));
}
String[] kitList = kitNames.split(",");
List<Kit> kits = new ArrayList<>();
for (final String kitName : kitList) {
for (final String kitName : kitNames.split(",")) {
if (kitName.isEmpty()) {
throw new Exception(tl("kitNotFound"));
}
@@ -4,7 +4,6 @@ import com.earth2me.essentials.Mob;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Cat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Ocelot;
@@ -22,45 +21,32 @@ public class Commandkittycannon extends EssentialsCommand {
@Override
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);
class KittyCannonExplodeTask implements Runnable {
@Override
public void run() {
final Location loc = ocelot.getLocation();
ocelot.remove();
loc.getWorld().createExplosion(loc, 0F);
}
}
ess.scheduleSyncDelayedTask(new KittyCannonExplodeTask(), 20);
final Entity ocelot = Mob.CAT.getType() == null ? spawnOcelot(server, user) : spawnCat(server, user);
ess.scheduleSyncDelayedTask(() -> {
final Location loc = ocelot.getLocation();
ocelot.remove();
loc.getWorld().createExplosion(loc, 0F);
}, 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());
if (ocelot == null) {
return null;
}
final int i = random.nextInt(Ocelot.Type.values().length);
ocelot.setCatType(Ocelot.Type.values()[i]);
((Tameable) ocelot).setTamed(true);
ocelot.setBaby();
ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
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());
if (cat == null) {
return null;
}
final int i = random.nextInt(Cat.Type.values().length);
cat.setCatType(Cat.Type.values()[i]);
cat.setTamed(true);
cat.setBaby();
cat.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
return cat;
}
}
@@ -3,55 +3,54 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.LightningStrike;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandlightning extends EssentialsLoopCommand {
int power = 5;
public Commandlightning() {
super("lightning");
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if ((args.length < 1 || !user.isAuthorized("essentials.lightning.others"))) {
user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation());
if (args.length == 0) {
if (sender.isPlayer() || !sender.isAuthorized("essentials.lightning.others", ess)) {
sender.getPlayer().getWorld().strikeLightning(sender.getPlayer().getTargetBlock(null, 600).getLocation());
return;
}
throw new NotEnoughArgumentsException();
}
int power = 5;
if (args.length > 1) {
try {
power = Integer.parseInt(args[1]);
} 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);
}
@Override
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
@@ -69,7 +68,7 @@ public class Commandlightning extends EssentialsLoopCommand {
if (args.length == 1) {
return getPlayers(server, sender);
} else if (args.length == 2) {
return Lists.newArrayList(Integer.toString(this.power));
return Lists.newArrayList("5");
} else {
return Collections.emptyList();
}
@@ -78,7 +78,7 @@ public class Commandlist extends EssentialsCommand {
outputUserList = PlayerList.getMergedList(ess, playerList, configGroup);
// If we have no users, than we don't need to continue parsing this group
if (outputUserList == null || outputUserList.isEmpty()) {
if (outputUserList.isEmpty()) {
continue;
}
@@ -120,7 +120,7 @@ public class Commandlist extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return getGroups();
return new ArrayList<>(PlayerList.getPlayerLists(ess, sender.getUser(ess), true).keySet());
} else {
return Collections.emptyList();
}
@@ -26,7 +26,6 @@ public class Commandmail extends EssentialsCommand {
super("mail");
}
//TODO: Tidy this up / TL these errors.
@Override
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])) {
@@ -56,8 +55,10 @@ public class Commandmail extends EssentialsCommand {
throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
}
User u = getPlayer(server, args[1], true, true);
if (u == null) {
User u;
try {
u = getPlayer(server, args[1], true, true);
} catch (PlayerNotFoundException e) {
throw new Exception(tl("playerNeverOnServer", args[1]));
}
@@ -111,8 +112,10 @@ public class Commandmail extends EssentialsCommand {
} else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) {
throw new Exception(tl("onlyPlayers", commandLabel + " clear"));
} else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) {
User u = getPlayer(server, args[1], true, true);
if (u == null) {
User u;
try {
u = getPlayer(server, args[1], true, true);
} catch (PlayerNotFoundException e) {
throw new Exception(tl("playerNeverOnServer", args[1]));
}
u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 2))));
@@ -124,8 +127,10 @@ public class Commandmail extends EssentialsCommand {
return;
} else if (args.length >= 2) {
//allow sending from console without "send" argument, since it's the only thing the console can do
User u = getPlayer(server, args[0], true, true);
if (u == null) {
User u;
try {
u = getPlayer(server, args[0], true, true);
} catch (PlayerNotFoundException e) {
throw new Exception(tl("playerNeverOnServer", args[0]));
}
u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 1))));
@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
@@ -19,9 +18,7 @@ public class Commandmotd extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick();
}
final IText input = new TextInput(sender, "motd", true, ess);
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "motd", true, ess), sender, ess));
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
}
}
@@ -13,19 +13,18 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandmsg extends EssentialsLoopCommand {
public Commandmsg() {
super("msg");
}
@Override
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();
}
String message = getFinalArg(args, 1);
boolean canWildcard;
boolean canWildcard = sender.isAuthorized("essentials.msg.multiple", ess);
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
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));
}
message = FormatUtil.formatMessage(user, "essentials.msg", message);
canWildcard = user.isAuthorized("essentials.msg.multiple");
} else {
message = FormatUtil.replaceFormat(message);
canWildcard = true;
}
// Sending messages to console
@@ -49,7 +46,7 @@ public class Commandmsg extends EssentialsLoopCommand {
return;
}
loopOnlinePlayers(server, sender, canWildcard, canWildcard, args[0], new String[]{message});
loopOnlinePlayers(server, sender, false, canWildcard, args[0], new String[]{message});
}
@Override
@@ -32,14 +32,12 @@ public class Commandmute extends EssentialsCommand {
nomatch = true;
user = ess.getUser(new OfflinePlayer(args[0], ess.getServer()));
}
if (!user.getBase().isOnline()) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.offline")) {
if (!user.getBase().isOnline() && sender.isPlayer()) {
if (!sender.isAuthorized("essentials.mute.offline", ess)) {
throw new Exception(tl("muteExemptOffline"));
}
} else {
if (user.isAuthorized("essentials.mute.exempt") && sender.isPlayer()) {
} else if (user.isAuthorized("essentials.mute.exempt")) {
throw new Exception(tl("muteExempt"));
}
}
long muteTimestamp = 0;
@@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.google.common.collect.Lists;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
@@ -59,7 +60,7 @@ public class Commandnear extends EssentialsCommand {
if (otherUser == null || !user.isAuthorized("essentials.near.others")) {
otherUser = user;
}
user.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius)));
user.sendMessage(tl("nearbyPlayers", getLocal(otherUser, radius)));
}
@Override
@@ -75,10 +76,10 @@ public class Commandnear extends EssentialsCommand {
} 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 World world = loc.getWorld();
final StringBuilder output = new StringBuilder();
@@ -106,7 +107,10 @@ public class Commandnear extends EssentialsCommand {
output.append(", ");
}
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");
@@ -11,6 +11,7 @@ import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Predicate;
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")) {
final String[] nickname = formatNickname(user, args[1]).split(" ");
loopOfflinePlayers(server, user.getSource(), false, true, args[0], nickname);
loopOfflinePlayers(server, user.getSource(), false, true, args[0], formatNickname(user, args[1]).split(" "));
user.sendMessage(tl("nickChanged"));
} else {
final String[] nickname = formatNickname(user, args[0]).split(" ");
updatePlayer(server, user.getSource(), user, nickname);
updatePlayer(server, user.getSource(), user, formatNickname(user, args[0]).split(" "));
}
}
@@ -47,8 +46,7 @@ public class Commandnick extends EssentialsLoopCommand {
if (!ess.getSettings().changeDisplayName()) {
throw new Exception(tl("nickDisplayName"));
}
final String[] nickname = formatNickname(null, args[1]).split(" ");
loopOfflinePlayers(server, sender, false, true, args[0], nickname);
loopOfflinePlayers(server, sender, false, true, args[0], formatNickname(null, args[1]).split(" "));
sender.sendMessage(tl("nickChanged"));
}
@@ -59,13 +57,12 @@ public class Commandnick extends EssentialsLoopCommand {
setNickname(server, sender, target, null);
target.sendMessage(tl("nickNoMore"));
} else if (target.getName().equalsIgnoreCase(nick)) {
String oldName = target.getDisplayName();
setNickname(server, sender, target, nick);
if (!target.getDisplayName().equalsIgnoreCase(oldName)) {
if (!target.getDisplayName().equalsIgnoreCase(target.getDisplayName())) {
target.sendMessage(tl("nickNoMore"));
}
target.sendMessage(tl("nickSet", target.getDisplayName()));
} else if (nickInUse(server, target, nick)) {
} else if (nickInUse(target, nick)) {
throw new NotEnoughArgumentsException(tl("nickInUse"));
} else {
setNickname(server, sender, target, nick);
@@ -90,15 +87,19 @@ public class Commandnick extends EssentialsLoopCommand {
}
private boolean isNickBanned(String newNick) {
return ess.getSettings().getNickBlacklist().stream()
.anyMatch(entry -> entry.test(newNick));
for (Predicate<String> predicate : ess.getSettings().getNickBlacklist()) {
if (predicate.test(newNick)) {
return true;
}
}
return false;
}
private int getNickLength(final String nick) {
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));
for (final Player onlinePlayer : ess.getOnlinePlayers()) {
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) {
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
final NickChangeEvent nickEvent = new NickChangeEvent(controller, target, nickname);
final NickChangeEvent nickEvent = new NickChangeEvent(sender.getUser(ess), target, nickname);
server.getPluginManager().callEvent(nickEvent);
if (!nickEvent.isCancelled()) {
target.setNickname(nickname);
@@ -25,10 +25,8 @@ public class Commandnuke extends EssentialsCommand {
Collection<Player> targets;
if (args.length > 0) {
targets = new ArrayList<>();
int pos = 0;
for (String arg : args) {
targets.add(getPlayer(server, sender, args, pos).getBase());
pos++;
for (int i = 0; i < args.length; ++i) {
targets.add(getPlayer(server, sender, args, i).getBase());
}
} else {
targets = ess.getOnlinePlayers();
@@ -43,8 +41,7 @@ public class Commandnuke extends EssentialsCommand {
final World world = loc.getWorld();
for (int x = -10; x <= 10; x += 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);
final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class);
world.spawn(new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z), TNTPrimed.class);
}
}
}
@@ -1,12 +1,10 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import com.google.common.collect.Lists;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.UserBalanceUpdateEvent;
@@ -15,21 +13,18 @@ import org.bukkit.Server;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.earth2me.essentials.I18n.tl;
public class Commandpay extends EssentialsLoopCommand {
BigDecimal amount;
boolean informToConfirm;
public Commandpay() {
super("pay");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
informToConfirm = false;
if (args.length < 2) {
throw new NotEnoughArgumentsException();
}
@@ -44,49 +39,50 @@ public class Commandpay extends EssentialsLoopCommand {
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
throw new Exception(tl("minimumPayAmount", NumberUtil.displayCurrencyExactly(ess.getSettings().getMinimumPayAmount(), ess)));
}
loopOnlinePlayers(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], args);
if (informToConfirm) {
final AtomicBoolean informToConfirm = new AtomicBoolean(false);
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);
user.sendMessage(tl("confirmPayment", NumberUtil.displayCurrency(amount, ess), cmd));
}
}
@Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws ChargeException {
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());
}
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) {
}
@Override
@@ -1,11 +1,10 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandpayconfirmtoggle extends EssentialsCommand {
public Commandpayconfirmtoggle() {
@@ -21,11 +20,7 @@ public class Commandpayconfirmtoggle extends EssentialsCommand {
confirmingPay = false;
}
user.setPromptingPayConfirm(confirmingPay);
if (confirmingPay) {
user.sendMessage(tl("payConfirmToggleOn"));
} else {
user.sendMessage(tl("payConfirmToggleOff"));
}
user.sendMessage(confirmingPay ? tl("payConfirmToggleOn") : tl("payConfirmToggleOff"));
user.getConfirmingPayments().clear(); // Clear any outstanding confirmations.
}
}
@@ -1,29 +1,44 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandpaytoggle extends EssentialsCommand {
public class Commandpaytoggle extends EssentialsToggleCommand {
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
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
boolean acceptingPay = !user.isAcceptingPay();
if (commandLabel.contains("payon")) {
acceptingPay = true;
togglePlayer(user.getSource(), user, true);
} else if (commandLabel.contains("payoff")) {
acceptingPay = false;
}
user.setAcceptingPay(acceptingPay);
if (acceptingPay) {
user.sendMessage(tl("payToggleOn"));
togglePlayer(user.getSource(), user, false);
} 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()));
}
}
}
@@ -14,8 +14,7 @@ public class Commandping extends EssentialsCommand {
@Override
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"));
} else {
sender.sendMessage(FormatUtil.replaceFormat(getFinalArg(args, 0)));
@@ -26,7 +26,6 @@ public class Commandpotion extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getItemInHand();
if (args.length == 0) {
final Set<String> potionslist = new TreeSet<>();
for (Map.Entry<String, PotionEffectType> entry : Potions.entrySet()) {
@@ -44,31 +43,28 @@ public class Commandpotion extends EssentialsCommand {
}
if (holdingPotion) {
PotionMeta pmeta = (PotionMeta) stack.getItemMeta();
if (args.length > 0) {
if (args[0].equalsIgnoreCase("clear")) {
pmeta.clearCustomEffects();
if (args[0].equalsIgnoreCase("clear")) {
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);
} 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);
} else {
user.sendMessage(tl("invalidPotion"));
throw new NotEnoughArgumentsException();
}
user.sendMessage(tl("invalidPotion"));
throw new NotEnoughArgumentsException();
}
}
} else {
throw new Exception(tl("holdPotion"));
}
@@ -91,7 +87,7 @@ public class Commandpotion extends EssentialsCommand {
}
return options;
} else if (args.length == 2 && args[0].startsWith("effect:")) {
return Lists.newArrayList("power:1", "power:2", "power:3", "power:4");
return Lists.newArrayList("power:1", "power:2", "power:3", "power:4", "amplifier:0", "amplifier:1", "amplifier:2", "amplifier:3");
} else if (args.length == 3 && args[0].startsWith("effect:")) {
List<String> options = Lists.newArrayList();
for (String duration : COMMON_DURATIONS) {
@@ -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 {
final String command = getFinalArg(args, 0);
final ItemStack itemStack = user.getBase().getItemInHand();
powertool(server, user.getSource(), user, commandLabel, itemStack, command);
powertool(user.getSource(), user, itemStack, command);
}
@Override
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>");
}
final User user = getPlayer(server, args, 0, true, true);
final ItemStack itemStack = ess.getItemDb().get(args[1]);
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
if (command != null && command.equalsIgnoreCase("d:")) {
user.clearAllPowertools();
@@ -1,28 +1,20 @@
package com.earth2me.essentials.commands;
import com.google.common.collect.Lists;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DescParseTickFormat;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.*;
import static com.earth2me.essentials.I18n.tl;
public class Commandptime extends EssentialsCommand {
private static final Set<String> getAliases = new HashSet<>();
static {
getAliases.add("get");
getAliases.add("list");
getAliases.add("show");
getAliases.add("display");
}
public class Commandptime extends EssentialsLoopCommand {
private static final List<String> getAliases = Arrays.asList("get", "list", "show", "display");
public Commandptime() {
super("ptime");
@@ -30,160 +22,96 @@ public class Commandptime extends EssentialsCommand {
@Override
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?
String userSelector = null;
if (args.length == 2) {
userSelector = args[1];
}
Set<User> users = getUsers(server, sender, userSelector);
// 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"));
if (args.length == 0 || getAliases.contains(args[0].toLowerCase())) {
if (args.length > 1) { // /ptime get md_5 || /ptime get *
if (args[1].equals("*") || args[1].equals("**")) {
sender.sendMessage(tl("pTimePlayers"));
}
loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> getUserTime(sender, player));
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;
// Parse the target time int ticks from args[0]
String timeParam = args[0];
boolean relative = true;
if (timeParam.startsWith("@")) {
relative = false;
timeParam = timeParam.substring(1);
if (args.length > 1 && !sender.isAuthorized("essentials.ptime.others", ess) && !args[1].equalsIgnoreCase(sender.getSelfSelector())) {
sender.sendMessage(tl("pTimeOthersPermission"));
return;
}
if (getAliases.contains(timeParam)) {
getUsersTime(sender, users);
return;
} else if (DescParseTickFormat.meansReset(timeParam)) {
String time = args[0];
boolean fixed = time.startsWith("@");
if (fixed) {
time = time.substring(1);
}
final Long ticks;
if (DescParseTickFormat.meansReset(time)) {
ticks = null;
} else {
try {
ticks = DescParseTickFormat.parse(timeParam);
ticks = DescParseTickFormat.parse(time);
} catch (NumberFormatException 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) {
// Reset
for (User user : users) {
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);
}
sender.sendMessage(tl("pTimeReset", joiner.toString()));
return;
}
final StringBuilder msg = new StringBuilder();
for (User user : users) {
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()));
}
}
String formattedTime = DescParseTickFormat.format(ticks);
sender.sendMessage(fixed ? tl("pTimeSetFixed", formattedTime, joiner.toString()) : tl("pTimeSet", formattedTime, joiner.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);
}
public void getUserTime(final CommandSource sender, IUser user) {
if (user == null) {
return;
}
if (user.getBase().getPlayerTimeOffset() == 0) {
sender.sendMessage(tl("pTimeNormal", user.getName()));
return;
}
String time = DescParseTickFormat.format(user.getBase().getPlayerTime());
sender.sendMessage(user.getBase().isPlayerTimeRelative() ? tl("pTimeCurrent", user.getName(), time) : tl("pTimeCurrentFixed", user.getName(), time));
}
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
@@ -198,12 +126,8 @@ public class Commandptime extends EssentialsCommand {
return Collections.emptyList();
}
}
}
class UserNameComparator implements Comparator<User> {
@Override
public int compare(User a, User b) {
return a.getName().compareTo(b.getName());
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
}
@@ -1,27 +1,21 @@
package com.earth2me.essentials.commands;
import com.google.common.collect.Lists;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import java.util.*;
import static com.earth2me.essentials.I18n.tl;
public class Commandpweather extends EssentialsCommand {
public static final Set<String> getAliases = new HashSet<>();
public static final Map<String, WeatherType> weatherAliases = new HashMap<>();
public class Commandpweather extends EssentialsLoopCommand {
private static final List<String> getAliases = Arrays.asList("get", "list", "show", "display");
private static final Map<String, WeatherType> weatherAliases = new HashMap<>();
static {
getAliases.add("get");
getAliases.add("list");
getAliases.add("show");
getAliases.add("display");
weatherAliases.put("sun", WeatherType.CLEAR);
weatherAliases.put("clear", WeatherType.CLEAR);
weatherAliases.put("storm", WeatherType.DOWNFALL);
@@ -34,123 +28,74 @@ public class Commandpweather extends EssentialsCommand {
@Override
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?
String userSelector = null;
if (args.length == 2) {
userSelector = args[1];
}
Set<User> users = getUsers(server, sender, userSelector);
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"));
if (args.length == 0 || getAliases.contains(args[0].toLowerCase())) {
if (args.length > 1) { // /pweather get md_5 || /pweather get *
if (args[1].equals("*") || args[1].equals("**")) {
sender.sendMessage(tl("pWeatherPlayers"));
}
loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> getUserWeather(sender, player));
return;
}
}
setUsersWeather(sender, users, args[0].toLowerCase());
}
/**
* 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);
if (args.length == 1 || sender.isPlayer()) { // /pweather get
if (sender.isPlayer()) {
getUserWeather(sender, sender.getUser(ess));
return;
}
throw new NotEnoughArgumentsException(); // We cannot imply the target for console
}
return users;
}
// 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);
// Default to showing the weather of all online users for console when no arguments are provided
if (ess.getOnlinePlayers().size() > 1) {
sender.sendMessage(tl("pWeatherPlayers"));
}
for (User player : ess.getOnlineUsers()) {
getUserWeather(sender, player);
}
}
// We failed to understand the world target...
else {
throw new PlayerNotFoundException();
if (args.length > 1 && !sender.isAuthorized("essentials.pweather.others", ess) && !args[1].equalsIgnoreCase(sender.getSelfSelector())) {
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
@@ -163,4 +108,8 @@ public class Commandpweather extends EssentialsCommand {
return Collections.emptyList();
}
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) {
}
}
@@ -24,10 +24,8 @@ public class Commandr extends EssentialsCommand {
String message = getFinalArg(args, 0);
IMessageRecipient messageSender;
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if (user.isMuted()) {
String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) {
@@ -17,10 +17,12 @@ public class Commandrealname extends EssentialsCommand {
@Override
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();
}
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 foundUser = false;
for (User u : ess.getOnlineUsers()) {
@@ -28,8 +30,7 @@ public class Commandrealname extends EssentialsCommand {
continue;
}
u.setDisplayNick();
final String displayName = FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (displayName.contains(whois)) {
if (FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH).contains(lookup)) {
foundUser = true;
sender.sendMessage(tl("realName", u.getDisplayName(), u.getName()));
}
@@ -226,10 +226,8 @@ public class Commandremove extends EssentialsCommand {
break;
case ENTITIES:
case ALL:
if (e instanceof Entity) {
e.remove();
removed++;
}
e.remove();
removed++;
break;
case CUSTOM:
for (Mob type : customRemoveTypes) {
@@ -26,7 +26,7 @@ public class Commandrepair extends EssentialsCommand {
@Override
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);
} else if (args[0].equalsIgnoreCase("all")) {
final Trade charge = new Trade("repair-all", ess);
@@ -1,6 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Server;
@@ -16,29 +17,20 @@ public class Commandrest extends EssentialsLoopCommand {
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
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)) {
sender.sendMessage(tl("unsupportedFeature"));
return;
}
if (args.length < 1) {
if (args.length == 0 && !sender.isPlayer()) {
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
@@ -47,23 +39,14 @@ public class Commandrest extends EssentialsLoopCommand {
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.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
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);
} else {
return Collections.emptyList();
@@ -22,7 +22,7 @@ public class Commandrtoggle extends EssentialsToggleCommand {
}
@Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException {
void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) {
enabled = !user.isLastMessageReplyRecipient();
}
@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
@@ -19,9 +18,7 @@ public class Commandrules extends EssentialsCommand {
ess.getUser(sender.getPlayer()).setDisplayNick();
}
final IText input = new TextInput(sender, "rules", true, ess);
final IText output = new KeywordReplacer(input, sender, ess);
final TextPager pager = new TextPager(output);
final TextPager pager = new TextPager(new KeywordReplacer(new TextInput(sender, "rules", true, ess), sender, ess));
pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender);
}
}
@@ -28,16 +28,9 @@ public class Commandseen extends EssentialsCommand {
@Override
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);
}
@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 {
boolean showBan = sender.isAuthorized("essentials.seen.banreason", ess);
boolean showIp = sender.isAuthorized("essentials.seen.ip", ess);
boolean showLocation = sender.isAuthorized("essentials.seen.location", ess);
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
@@ -46,13 +39,13 @@ public class Commandseen extends EssentialsCommand {
try {
UUID uuid = UUID.fromString(args[0]);
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]);
}
if (player == null) {
if (ipLookup && FormatUtil.validIP(args[0])) {
seenIP(server, sender, args[0]);
if (sender.isAuthorized("essentials.seen.ipsearch", ess) && FormatUtil.validIP(args[0])) {
seenIP(sender, args[0]);
return;
} else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) {
sender.sendMessage(tl("isIpBanned", args[0]));
@@ -69,7 +62,11 @@ public class Commandseen extends EssentialsCommand {
if (userFromBukkit != null) {
showUserSeen(userFromBukkit);
} else {
showUserSeen(getPlayer(server, sender, args, 0));
try {
showUserSeen(getPlayer(server, sender, args, 0));
} catch (PlayerNotFoundException e) {
throw new Exception(tl("playerNeverOnServer", args[0]));
}
}
} catch (Exception e) {
ess.showError(sender, e, commandLabel);
@@ -77,26 +74,23 @@ public class Commandseen extends EssentialsCommand {
}
private void showUserSeen(User user) throws Exception {
if (user == null) {
throw new PlayerNotFoundException();
}
showSeenMessage(server, sender, user, showBan, showIp, showLocation);
showSeenMessage(sender, user, showBan, showIp, showLocation);
}
});
} 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)) {
seenOnline(server, sender, player, showBan, showIp, showLocation);
seenOnline(sender, player, showIp);
} 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();
sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin())));
@@ -133,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();
if (user.getLastLogout() > 0) {
sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout())));
@@ -190,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();
if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) {
@@ -27,7 +27,6 @@ public class Commandsell extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
BigDecimal totalWorth = BigDecimal.ZERO;
String type = "";
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
@@ -82,9 +81,9 @@ public class Commandsell extends EssentialsCommand {
}
if (count != 1) {
if (args[0].equalsIgnoreCase("blocks")) {
user.sendMessage(tl("totalWorthBlocks", type, NumberUtil.displayCurrency(totalWorth, ess)));
user.sendMessage(tl("totalWorthBlocks", NumberUtil.displayCurrency(totalWorth, ess)));
} else {
user.sendMessage(tl("totalWorthAll", type, NumberUtil.displayCurrency(totalWorth, ess)));
user.sendMessage(tl("totalWorthAll", NumberUtil.displayCurrency(totalWorth, ess)));
}
}
}
@@ -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 {
User usersHome = user;
String name = "home";
final Location location = user.getLocation();
if (args.length > 0) {
//Allowing both formats /sethome khobbits house | /sethome khobbits:house
@@ -52,6 +51,7 @@ public class Commandsethome extends EssentialsCommand {
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())) {
throw new Exception(tl("unsafeTeleportDestination", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()));
}
@@ -19,6 +19,5 @@ public class Commandsetjail extends EssentialsCommand {
}
ess.getJails().setJail(args[0], user.getLocation());
user.sendMessage(tl("jailSet", StringUtil.sanitizeString(args[0])));
}
}
@@ -18,15 +18,14 @@ public class Commandsetwarp extends EssentialsCommand {
@Override
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();
}
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();
Location warpLoc = null;
@@ -36,7 +35,7 @@ public class Commandsetwarp extends EssentialsCommand {
}
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 {
throw new Exception(tl("warpOverwrite"));
}
@@ -22,7 +22,6 @@ public class Commandsetworth extends EssentialsCommand {
ItemStack stack;
String price;
if (args.length == 1) {
stack = user.getBase().getInventory().getItemInHand();
price = args[0];
@@ -41,8 +40,7 @@ public class Commandsetworth extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
ItemStack stack = ess.getItemDb().get(args[0]);
ess.getWorth().setPrice(ess, stack, FloatUtil.parseDouble(args[1]));
ess.getWorth().setPrice(ess, ess.getItemDb().get(args[0]), FloatUtil.parseDouble(args[1]));
sender.sendMessage(tl("worthSet"));
}
}
@@ -12,7 +12,6 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandshowkit extends EssentialsCommand {
public Commandshowkit() {
super("showkit");
}
@@ -23,11 +22,9 @@ public class Commandshowkit extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(",");
for (final String kitName : kits) {
Kit kit = new Kit(kitName, ess);
for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) {
user.sendMessage(tl("kitContains", kitName));
for (String s : kit.getItems()) {
for (String s : new Kit(kitName, ess).getItems()) {
user.sendMessage(tl("kitItem", s));
}
}
@@ -9,14 +9,17 @@ import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
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");
public Commandskull() {
@@ -26,9 +29,8 @@ public class Commandskull extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
String owner;
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"));
}
owner = args[0];
@@ -37,7 +39,7 @@ public class Commandskull extends EssentialsCommand {
}
ItemStack itemSkull = user.getItemInHand();
SkullMeta metaSkull = null;
SkullMeta metaSkull;
boolean spawn = false;
if (itemSkull != null && MaterialUtil.isPlayerHead(itemSkull.getType(), itemSkull.getDurability())) {
@@ -54,17 +56,30 @@ public class Commandskull extends EssentialsCommand {
throw new Exception(tl("noPermissionSkull"));
}
metaSkull.setDisplayName("§fSkull of " + owner);
metaSkull.setOwner(owner);
editSkull(user, itemSkull, metaSkull, owner, spawn);
}
itemSkull.setItemMeta(metaSkull);
if (spawn) {
InventoryWorkaround.addItems(user.getBase().getInventory(), itemSkull);
user.sendMessage(tl("givenSkull", owner));
} else {
user.sendMessage(tl("skullChanged", owner));
}
private void editSkull(User user, ItemStack stack, SkullMeta skullMeta, String owner, boolean spawn) {
new BukkitRunnable() {
@Override
public void run() {
//Run this stuff async because SkullMeta#setOwner causes a http request.
skullMeta.setDisplayName("§fSkull of " + 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
@@ -23,14 +23,13 @@ public class Commandsocialspy extends EssentialsToggleCommand {
}
@Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException {
protected void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) {
enabled = !user.isSocialSpyEnabled();
}
user.setSocialSpyEnabled(enabled);
user.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled")));
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) {
sender.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled")));
@@ -7,6 +7,7 @@ import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.provider.SpawnerBlockProvider;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
@@ -18,6 +19,9 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandspawner extends EssentialsCommand {
private static final Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER");
public Commandspawner() {
super("spawner");
}
@@ -29,36 +33,41 @@ public class Commandspawner extends EssentialsCommand {
}
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"));
}
String name = args[0];
int delay = 0;
Mob mob = null;
mob = Mob.fromName(name);
Mob mob = Mob.fromName(name);
if (mob == null) {
throw new Exception(tl("invalidMob"));
}
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("disabledToSpawnMob"));
}
if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("noPermToSpawnMob"));
}
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
delay = Integer.parseInt(args[1]);
}
if (args.length > 1 && NumberUtil.isInt(args[1])) {
delay = Integer.parseInt(args[1]);
}
final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess);
charge.isAffordableFor(user);
try {
CreatureSpawner spawner = (CreatureSpawner) target.getBlock().getState();
spawner.setSpawnedType(mob.getType());
if (delay > 0) {
SpawnerBlockProvider spawnerBlockProvider = ess.getSpawnerBlockProvider();
spawnerBlockProvider.setMinSpawnDelay(spawner, 1);
spawnerBlockProvider.setMaxSpawnDelay(spawner, Integer.MAX_VALUE);
spawnerBlockProvider.setMinSpawnDelay(spawner, delay);
spawnerBlockProvider.setMaxSpawnDelay(spawner, delay);
}
spawner.setDelay(delay);
spawner.update();
} catch (Throwable ex) {
@@ -21,9 +21,8 @@ public class Commandspawnmob extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
final String mobList = SpawnMob.mobList(user);
throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList));
if (args.length == 0) {
throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList())));
}
List<String> mobParts = SpawnMob.mobParts(args[0]);
@@ -39,8 +38,7 @@ public class Commandspawnmob extends EssentialsCommand {
}
if (args.length >= 3) {
final User target = getPlayer(ess.getServer(), user, args, 2);
SpawnMob.spawnmob(ess, server, user.getSource(), target, mobParts, mobData, mobCount);
SpawnMob.spawnmob(ess, server, user.getSource(), getPlayer(ess.getServer(), user, args, 2), mobParts, mobData, mobCount);
return;
}
@@ -50,16 +48,13 @@ public class Commandspawnmob extends EssentialsCommand {
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 3) {
final String mobList = StringUtil.joinList(Mob.getMobList());
throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList));
throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList())));
}
List<String> mobParts = SpawnMob.mobParts(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, target, mobParts, mobData, mobCount);
SpawnMob.spawnmob(ess, server, sender, getPlayer(ess.getServer(), args, 2, true, false), mobParts, mobData, Integer.parseInt(args[1]));
}
@Override
@@ -6,6 +6,7 @@ import com.earth2me.essentials.utils.FloatUtil;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -13,6 +14,9 @@ import static com.earth2me.essentials.I18n.tl;
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() {
super("speed");
}
@@ -22,9 +26,7 @@ public class Commandspeed extends EssentialsCommand {
if (args.length < 2) {
throw new NotEnoughArgumentsException();
}
final boolean isFly = isFlyMode(args[0]);
final float speed = getMoveSpeed(args[1]);
speedOtherPlayers(server, sender, isFly, true, speed, args[2]);
speedOtherPlayers(server, sender, isFlyMode(args[0]), true, getMoveSpeed(args[1]), args[2]);
}
@Override
@@ -52,12 +54,12 @@ public class Commandspeed extends EssentialsCommand {
}
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()));
} else {
user.getBase().setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass));
user.sendMessage(tl("moveSpeed", tl("walking"), speed, user.getDisplayName()));
return;
}
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 {
@@ -71,10 +73,10 @@ public class Commandspeed extends EssentialsCommand {
}
foundUser = true;
if (isFly) {
matchPlayer.setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass));
matchPlayer.setFlySpeed(getRealMoveSpeed(speed, true, isBypass));
sender.sendMessage(tl("moveSpeed", tl("flying"), speed, matchPlayer.getDisplayName()));
} else {
matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass));
matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, false, isBypass));
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 canWalk = user.isAuthorized("essentials.speed.walk");
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
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);
} else {
return Collections.emptyList();
@@ -1,9 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Server;
import java.util.Locale;
@@ -22,20 +20,15 @@ public class Commandsudo extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException();
}
final String[] arguments = new String[args.length - 1];
if (arguments.length > 0) {
System.arraycopy(args, 1, arguments, 0, args.length - 1);
}
final String command = getFinalArg(arguments, 0);
final String command = getFinalArg(args, 1);
boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple");
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
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())) {
return; // Silently don't do anything.
}
@@ -51,7 +44,7 @@ public class Commandsudo extends EssentialsLoopCommand {
}
final String command = getFinalArg(args, 0);
if (command != null && command.length() > 0) {
if (command.length() > 0) {
class SudoCommandTask implements Runnable {
@Override
public void run() {
@@ -26,16 +26,12 @@ public class Commandtempban extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
final User user = getPlayer(server, args, 0, true, true);
if (!user.getBase().isOnline()) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) {
sender.sendMessage(tl("tempbanExemptOffline"));
return;
}
} else {
if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) {
sender.sendMessage(tl("tempbanExempt"));
return;
}
if (!user.getBase().isOnline() && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) {
sender.sendMessage(tl("tempbanExemptOffline"));
return;
} else if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) {
sender.sendMessage(tl("tempbanExempt"));
return;
}
final String time = getFinalArg(args, 1);
final long banTimestamp = DateUtil.parseDateDiff(time, true);
@@ -44,7 +40,7 @@ public class Commandtempban extends EssentialsCommand {
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"))) {
sender.sendMessage(tl("oversizedTempban"));
throw new NoChargeException();
return;
}
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);
final String expiry = DateUtil.formatDateDiff(banTimestamp);
final String banDisplay = tl("tempBanned", expiry, senderName, banReason);
user.getBase().kickPlayer(banDisplay);
user.getBase().kickPlayer(tl("tempBanned", expiry, senderName, banReason));
final String message = tl("playerTempBanned", senderName, user.getName(), expiry, banReason);
server.getLogger().log(Level.INFO, message);
@@ -52,24 +52,23 @@ public class Commandtempbanip extends EssentialsCommand {
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"))) {
sender.sendMessage(tl("oversizedTempban"));
throw new NoChargeException();
return;
}
if (banReason.length() < 2) {
banReason = tl("defaultBanReason");
}
String banDisplay = tl("banFormat", banReason, 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()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
player.kickPlayer(banDisplay);
}
}
String message = tl("playerTempBanIpAddress", senderName, ipAddress, DateUtil.formatDateDiff(banTimestamp), banReason);
server.getLogger().log(Level.INFO, message);
ess.broadcastMessage("essentials.banip.notify", message);
}
@@ -18,22 +18,21 @@ public class Commandthunder extends EssentialsCommand {
@Override
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();
}
final World world = user.getWorld();
final boolean setThunder = args[0].equalsIgnoreCase("true");
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 {
if (args.length == 1) {
world.setThundering(setThunder);
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
@@ -14,64 +14,79 @@ import static com.earth2me.essentials.I18n.tl;
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() {
super("time");
}
@Override
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;
final List<String> argList = new ArrayList<>(Arrays.asList(args));
if (argList.remove("set") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) {
argList.set(0, argList.get(0) + "t");
}
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";
if (args.length == 0) {
worlds = getWorlds(server, sender, null);
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
} else {
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 {
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());
if (user != null && !user.isAuthorized("essentials.time.set")) {
// Start updating world times, we have what we need
User user = ess.getUser(sender.getPlayer());
if (!user.isAuthorized("essentials.time.set")) {
throw new Exception(tl("timeSetPermission"));
}
// Parse the target time int ticks from args[0]
long ticks;
try {
ticks = DescParseTickFormat.parse(setTime);
} catch (NumberFormatException e) {
throw new NotEnoughArgumentsException(e);
for (World world : worlds) {
if (!canUpdateWorld(user, world)) {
throw new Exception(tl("timeSetWorldPermission", user.getWorld().getName()));
}
}
setWorldsTime(sender, worlds, ticks, add);
final StringJoiner joiner = new StringJoiner(",");
for (World world : worlds) {
long time = world.getTime();
if (!add) {
time -= time % 24000;
}
world.setTime(time + (add ? 0 : 24000) + timeTick);
joiner.add(world.getName());
}
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) {
if (worlds.size() == 1) {
final Iterator<World> iter = worlds.iterator();
@@ -85,39 +100,7 @@ public class Commandtime extends EssentialsCommand {
}
/**
* Used to set the time and inform of the change
*/
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"
* Parses worlds from command args, otherwise returns all worlds.
*/
private Set<World> getWorlds(final Server server, final CommandSource sender, final String selector) throws Exception {
final Set<World> worlds = new TreeSet<>(new WorldNameComparator());
@@ -125,9 +108,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 (selector == null) {
if (sender.isPlayer()) {
final User user = ess.getUser(sender.getPlayer());
worlds.add(user.getWorld());
worlds.add(sender.getPlayer().getWorld());
} else {
worlds.addAll(server.getWorlds());
}
@@ -138,16 +119,11 @@ public class Commandtime extends EssentialsCommand {
final World world = server.getWorld(selector);
if (world != null) {
worlds.add(world);
}
// If that fails, Is the argument something like "*" or "all"?
else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) {
} else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) { // If that fails, Is the argument something like "*" or "all"?
worlds.addAll(server.getWorlds());
}
// We failed to understand the world target...
else {
} else { // We failed to understand the world target...
throw new Exception(tl("invalidWorld"));
}
return worlds;
}
@@ -166,25 +142,28 @@ public class Commandtime extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
final User user = ess.getUser(sender.getPlayer());
if (args.length == 1) {
if (user == null || user.isAuthorized("essentials.time.set")) {
return Lists.newArrayList("set", "add");
if (sender.isAuthorized("essentials.time.set", ess)) {
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 {
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"))) {
List<String> worlds = Lists.newArrayList();
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());
}
}
if (user == null || user.isAuthorized("essentials.time.world.all")) {
if (sender.isAuthorized("essentials.time.world.all", ess)) {
worlds.add("*");
}
return worlds;
@@ -5,6 +5,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DateUtil;
import net.ess3.api.events.JailStatusChangeEvent;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.ArrayList;
import java.util.Collections;
@@ -21,7 +22,7 @@ public class Commandtogglejail extends EssentialsCommand {
@Override
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();
}
@@ -33,14 +34,14 @@ public class Commandtogglejail extends EssentialsCommand {
sender.sendMessage(tl("mayNotJailOffline"));
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);
if (!event.isCancelled()) {
@@ -81,8 +82,7 @@ public class Commandtogglejail extends EssentialsCommand {
}
if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) {
final String time = getFinalArg(args, 2);
final long timeDiff = DateUtil.parseDateDiff(time, true);
final long timeDiff = DateUtil.parseDateDiff(getFinalArg(args, 2), true);
player.setJailTimeout(timeDiff);
sender.sendMessage(tl("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff)));
return;
@@ -92,8 +92,8 @@ public class Commandtogglejail extends EssentialsCommand {
if (!player.isJailed()) {
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);
if (!event.isCancelled()) {
@@ -101,7 +101,7 @@ public class Commandtogglejail extends EssentialsCommand {
player.setJailTimeout(0);
player.sendMessage(tl("jailReleasedPlayerNotify"));
player.setJail(null);
if (player.getBase().isOnline()) {
if (player.getBase().isOnline() && ess.getSettings().isTeleportBackWhenFreedFromJail()) {
CompletableFuture<Boolean> future = getNewExceptionFuture(sender, commandLabel);
player.getAsyncTeleport().back(future);
future.thenAccept(success -> {
@@ -109,6 +109,11 @@ public class Commandtogglejail extends EssentialsCommand {
sender.sendMessage(tl("jailReleased", player.getName()));
}
});
future.exceptionally(e -> {
player.getAsyncTeleport().respawn(null, PlayerTeleportEvent.TeleportCause.PLUGIN, new CompletableFuture<>());
sender.sendMessage(tl("jailReleased", player.getName()));
return false;
});
return;
}
sender.sendMessage(tl("jailReleased", player.getName()));
@@ -44,7 +44,7 @@ public class Commandtp extends EssentialsCommand {
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getAsyncTeleport().teleport(player.getBase(), charge, TeleportCause.COMMAND, future);
break;
throw new NoChargeException();
case 3:
if (!user.isAuthorized("essentials.tp.position")) {
throw new Exception(tl("noPerm", "essentials.tp.position"));
@@ -56,11 +56,6 @@ public class Commandtpaccept extends EssentialsCommand {
user.sendMessage(tl("pendingTeleportCancelled"));
return false;
});
future.thenAccept(success -> {
if (success) {
user.requestTeleport(null, false);
}
});
if (user.isTpRequestHere()) {
final Location loc = user.getTpRequestLocation();
AsyncTeleport teleport = (AsyncTeleport) requester.getAsyncTeleport();
@@ -76,6 +71,8 @@ public class Commandtpaccept extends EssentialsCommand {
teleport.setTpType(AsyncTeleport.TeleportType.TPA);
teleport.teleport(user.getBase(), charge, TeleportCause.COMMAND, future);
}
user.requestTeleport(null, false);
throw new NoChargeException();
}
}
@@ -26,6 +26,7 @@ public class Commandtphere extends EssentialsCommand {
throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName()));
}
user.getAsyncTeleport().teleportPlayer(player, user.getBase(), new Trade(this.getName(), ess), TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel));
throw new NoChargeException();
}
@Override
@@ -56,6 +56,8 @@ public class Commandtppos extends EssentialsCommand {
charge.isAffordableFor(user);
user.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel));
throw new NoChargeException();
}
@Override
@@ -39,6 +39,7 @@ public class Commandtpr extends EssentialsCommand {
}
});
});
throw new NoChargeException();
}
@Override
@@ -43,15 +43,15 @@ public class Commandtree extends EssentialsCommand {
}
final Location loc = LocationUtil.getTarget(user.getBase()).add(0, 1, 0);
if (!user.getWorld().getBlockAt(loc).isPassable()) {
if (loc.getBlock().getType().isSolid()) {
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"));
} else {
user.sendMessage(tl("treeFailure"));
return;
}
user.sendMessage(tl("treeFailure"));
}
@Override
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more