1
0
mirror of https://github.com/essentials/Essentials.git synced 2025-09-26 06:09:15 +02:00

This is a big refactoring of the user class and more.

Many commands have been cleaned.

File changes:
- all user data has been moved from users.yml to userdata folder
- all files in userdata folder are lower case
Both changes should be done automatically.

Class changes:
- Moved all user data functions to UserData class
- Moved all user teleport functions to Teleport class
- Moved the user list to Essentials class
- Less static functions for better testing
- EssentialsCommand now has ess Property (Essentials class)
- New NotEnoughArgumentsException, that will show command description and syntax

New commands:
- /seen, shows the last login or logout
- /tempban, temporarily ban someone
- /tjail and mute, temporarily option added

Other changes:
- ban reason is saved
- don't show "You have xxx mail" on login, if user doesn't have essentials.mail permission
-  time will be parsed: years, months (mo), weeks, days, hours, minutes (m), seconds, these can be shortened and combined, example: 2 days 5h 30m

git-svn-id: https://svn.java.net/svn/essentials~svn/trunk@1300 e251c2fe-e539-e718-e476-b85c1f46cddb
This commit is contained in:
snowleo
2011-05-01 21:07:30 +00:00
parent 03fd6249fc
commit 224c18348a
126 changed files with 3542 additions and 3145 deletions

View File

@@ -79,7 +79,7 @@ reference.EssentialsGeoIP.jar=${project.EssentialsGeoIP}/dist/EssentialsGeoIP.ja
reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/EssentialsGroupBridge.jar reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/EssentialsGroupBridge.jar
reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar
reference.EssentialsiConomyBridge.jar=${project.EssentialsiConomyBridge}/dist/EssentialsiConomyBridge.jar reference.EssentialsiConomyBridge.jar=${project.EssentialsiConomyBridge}/dist/EssentialsiConomyBridge.jar
reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/original-EssentialsProtect.jar reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/EssentialsProtect.jar
reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar
run.classpath=\ run.classpath=\
${javac.classpath}:\ ${javac.classpath}:\

View File

@@ -26,7 +26,7 @@ public class Backup implements Runnable {
private void startTask() { private void startTask() {
if (!running) { if (!running) {
long interval = Essentials.getSettings().getBackupInterval()*1200; // minutes -> ticks long interval = Essentials.getStatic().getSettings().getBackupInterval()*1200; // minutes -> ticks
if (interval < 1200) { if (interval < 1200) {
return; return;
} }
@@ -38,7 +38,7 @@ public class Backup implements Runnable {
public void run() { public void run() {
if (active) return; if (active) return;
active = true; active = true;
final String command = Essentials.getSettings().getBackupCommand(); final String command = Essentials.getStatic().getSettings().getBackupCommand();
if (command == null || "".equals(command)) { if (command == null || "".equals(command)) {
return; return;
} }

View File

@@ -8,6 +8,7 @@ import org.bukkit.*;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
@@ -17,9 +18,6 @@ import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type; import org.bukkit.event.Event.Type;
import org.bukkit.plugin.*; import org.bukkit.plugin.*;
import org.bukkit.plugin.java.*; import org.bukkit.plugin.java.*;
import org.yaml.snakeyaml.*;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class Essentials extends JavaPlugin public class Essentials extends JavaPlugin
@@ -27,102 +25,96 @@ public class Essentials extends JavaPlugin
public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans."; public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans.";
public static final int minBukkitBuildVersion = 733; public static final int minBukkitBuildVersion = 733;
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
private static final Yaml yaml = new Yaml(new SafeConstructor()); private Settings settings;
private static Map<String, Object> users;
private static Settings settings;
private static final Object usersLock = new Object();
public static Object permissions = null;
public final Map<User, User> tpcRequests = new HashMap<User, User>();
public final Map<User, Boolean> tpcHere = new HashMap<User, Boolean>();
public final List<User> away = new ArrayList<User>();
private EssentialsPlayerListener playerListener; private EssentialsPlayerListener playerListener;
private EssentialsBlockListener blockListener; private EssentialsBlockListener blockListener;
private EssentialsEntityListener entityListener; private EssentialsEntityListener entityListener;
private JailPlayerListener jailPlayerListener; private JailPlayerListener jailPlayerListener;
private static Essentials staticThis = null; private static Essentials instance = null;
public Spawn spawn; private Spawn spawn;
private Jail jail; private Jail jail;
private Warps warps; private Warps warps;
private Worth worth; private Worth worth;
private List<IConf> confList; private List<IConf> confList;
public ArrayList bans = new ArrayList(); public ArrayList bans = new ArrayList();
public ArrayList bannedIps = new ArrayList(); public ArrayList bannedIps = new ArrayList();
public Backup backup; private Backup backup;
private Map<String, User> users = new HashMap<String, User>();
private EssentialsTimer timer;
public Essentials() throws IOException public Essentials()
{ {
} }
public static void ensureEnabled(Server server)
{
PluginManager pm = server.getPluginManager();
Essentials ess = (Essentials)pm.getPlugin("Essentials");
if (!ess.isEnabled())
pm.enablePlugin(ess);
}
public static Essentials getStatic() public static Essentials getStatic()
{ {
return staticThis; return instance;
} }
public static Settings getSettings() public Settings getSettings()
{ {
return settings; return settings;
} }
public void setupPermissions() public void setupForTesting() throws IOException, InvalidDescriptionException
{ {
Plugin permPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); File dataFolder = File.createTempFile("essentialstest", "");
if (permissions == null && permPlugin != null) permissions = permPlugin; dataFolder.delete();
} dataFolder.mkdir();
logger.log(Level.INFO,"Using temp folder for testing:");
public Player getPlayer(String[] args, int pos) logger.log(Level.INFO,dataFolder.toString());
throws IndexOutOfBoundsException, NoSuchFieldException this.initialize(null, null, new PluginDescriptionFile(new FileReader(new File("src"+File.separator+"plugin.yml"))), dataFolder, null, null);
{ settings = new Settings(dataFolder);
if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?");
List<Player> matches = getServer().matchPlayer(args[0]);
if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found.");
return matches.get(0);
} }
public void setStatic() public void setStatic()
{ {
staticThis = this; instance = this;
} }
@SuppressWarnings("LoggerStringConcat") @SuppressWarnings("LoggerStringConcat")
public void onEnable() public void onEnable()
{ {
setStatic(); setStatic();
new EssentialsUpgrade(this.getDescription().getVersion(), this.getDataFolder()); EssentialsUpgrade upgrade = new EssentialsUpgrade(this.getDescription().getVersion(), this);
if (newWorldsLoaded) {
logger.log(Level.SEVERE, "New worlds have been loaded while upgrading files. Will reload the server.");
getServer().reload();
}
confList = new ArrayList<IConf>(); confList = new ArrayList<IConf>();
settings = new Settings(this.getDataFolder()); settings = new Settings(this.getDataFolder());
confList.add(settings); confList.add(settings);
this.spawn = new Spawn(getServer(), this.getDataFolder()); spawn = new Spawn(getServer(), this.getDataFolder());
confList.add(spawn); confList.add(spawn);
warps = new Warps(getServer(), this.getDataFolder()); warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps); confList.add(warps);
worth = new Worth(this.getDataFolder()); worth = new Worth(this.getDataFolder());
confList.add(worth); confList.add(worth);
reload(); reload();
this.backup = new Backup(); backup = new Backup();
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins()) { for (Plugin plugin : pm.getPlugins())
if (plugin.getDescription().getName().startsWith("Essentials")) { {
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) { if (plugin.getDescription().getName().startsWith("Essentials"))
logger.log(Level.WARNING, "Version mismatch! Please update "+plugin.getDescription().getName()+" to the same version."); {
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
logger.log(Level.WARNING, "Version mismatch! Please update " + plugin.getDescription().getName() + " to the same version.");
} }
} }
} }
Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion()); Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches()) { if (versionMatch.matches())
{
int versionNumber = Integer.parseInt(versionMatch.group(4)); int versionNumber = Integer.parseInt(versionMatch.group(4));
if (versionNumber < minBukkitBuildVersion) { if (versionNumber < minBukkitBuildVersion)
{
logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials."); logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials.");
} }
} else { }
else
{
logger.log(Level.INFO, "Bukkit version format changed. Version not checked."); logger.log(Level.INFO, "Bukkit version format changed. Version not checked.");
} }
@@ -132,7 +124,9 @@ public class Essentials extends JavaPlugin
pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this); pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this); pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
if (getSettings().getNetherPortalsEnabled()) if (getSettings().getNetherPortalsEnabled())
{
pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this);
}
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this);
@@ -150,7 +144,7 @@ public class Essentials extends JavaPlugin
pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this);
jail = new Jail(this.getDataFolder()); jail = new Jail(this);
jailPlayerListener = new JailPlayerListener(this); jailPlayerListener = new JailPlayerListener(this);
confList.add(jail); confList.add(jail);
pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this); pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this);
@@ -164,17 +158,19 @@ public class Essentials extends JavaPlugin
getServer().createWorld(settings.getNetherName(), World.Environment.NETHER); getServer().createWorld(settings.getNetherName(), World.Environment.NETHER);
} }
timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 50);
logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS); logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS);
} }
public void onDisable() public void onDisable()
{ {
staticThis = null; instance = null;
} }
public void reload() public void reload()
{ {
loadData();
loadBanList(); loadBanList();
for (IConf iConf : confList) for (IConf iConf : confList)
@@ -192,190 +188,6 @@ public class Essentials extends JavaPlugin
} }
} }
public static Map<String, Object> getData(User player)
{
return getData(player.getName());
}
public static Map<String, Object> getData(String player)
{
try
{
Map<String, Object> retval;
synchronized (usersLock)
{
retval = (Map<String, Object>)users.get(player.toLowerCase());
}
return retval == null ? new HashMap<String, Object>() : retval;
}
catch (Throwable ex)
{
return new HashMap<String, Object>();
}
}
public static void flushData()
{
Thread run = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists())
Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists())
file.createNewFile();
FileWriter tx = new FileWriter(file);
synchronized (usersLock)
{
tx.write(yaml.dump(users));
}
tx.flush();
tx.close();
}
catch (Throwable ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
run.setDaemon(false);
run.start();
}
public static void loadData()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists()) Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists()) file.createNewFile();
FileInputStream rx = new FileInputStream(file);
synchronized (usersLock)
{
users = (Map<String, Object>)yaml.load(new UnicodeReader(rx));
}
rx.close();
}
catch (Exception ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
synchronized (usersLock)
{
users = new HashMap<String, Object>();
}
}
finally
{
synchronized (usersLock)
{
if (users == null) users = new HashMap<String, Object>();
}
}
}
public static void setData(User player, Map<String, Object> data)
{
setData(player.getName(), data);
}
public static void setData(String player, Map<String, Object> data)
{
synchronized (usersLock)
{
users.put(player.toLowerCase(), data);
}
}
public static List<String> readMail(User player)
{
return readMail(player.getName());
}
public static List<String> readMail(String player)
{
try
{
Map<String, Object> data = getData(player);
List<String> retval = (List<String>)data.get("mail");
return retval == null ? new ArrayList<String>() : retval;
}
catch (Throwable ex)
{
return new ArrayList<String>();
}
}
public static void clearMail(User player)
{
try
{
Map<String, Object> data = getData(player);
data.put("mail", new ArrayList<String>());
setData(player, data);
flushData();
}
catch (Throwable ex)
{
}
}
public static void sendMail(User from, String to, String message)
throws Exception
{
try
{
Map<String, Object> data = getData(ChatColor.stripColor(to));
List<String> mail = readMail(to);
mail.add(ChatColor.stripColor(from.getDisplayName()) + ": " + message);
data.put("mail", mail);
setData(to, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while sending the mail.", ex);
}
}
public String readNickname(User player)
{
try
{
Map<String, Object> data = getData(player);
String nick = (String)data.get("nickname");
if (nick == null)
return player.getName();
if (nick.equals(player.getName()))
return player.getName();
return getSettings().getNicknamePrefix() + nick;
}
catch (Exception ex)
{
return player.getName();
}
}
public void saveNickname(User player, String nickname) throws Exception
{
try
{
Map<String, Object> data = getData(player);
data.put("nickname", nickname);
setData(player, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while saving the nickname.", ex);
}
}
public String[] getMotd(CommandSender sender, String def) public String[] getMotd(CommandSender sender, String def)
{ {
return getLines(sender, "motd", def); return getLines(sender, "motd", def);
@@ -384,7 +196,10 @@ public class Essentials extends JavaPlugin
public String[] getLines(CommandSender sender, String node, String def) public String[] getLines(CommandSender sender, String node, String def)
{ {
List<String> lines = (List<String>)getConfiguration().getProperty(node); List<String> lines = (List<String>)getConfiguration().getProperty(node);
if (lines == null) return new String[0]; if (lines == null)
{
return new String[0];
}
String[] retval = new String[lines.size()]; String[] retval = new String[lines.size()];
if (lines == null || lines.isEmpty() || lines.get(0) == null) if (lines == null || lines.isEmpty() || lines.get(0) == null)
@@ -408,18 +223,22 @@ public class Essentials extends JavaPlugin
// if still empty, call it a day // if still empty, call it a day
if (lines == null || lines.isEmpty() || lines.get(0) == null) if (lines == null || lines.isEmpty() || lines.get(0) == null)
{
return new String[0]; return new String[0];
}
for (int i = 0; i < lines.size(); i++) for (int i = 0; i < lines.size(); i++)
{ {
String m = lines.get(i); String m = lines.get(i);
if (m == null) if (m == null)
{
continue; continue;
}
m = m.replace('&', '§').replace("§§", "&"); m = m.replace('&', '§').replace("§§", "&");
if (sender instanceof User || sender instanceof Player) if (sender instanceof User || sender instanceof Player)
{ {
User user = User.get(sender); User user = getUser(sender);
m = m.replace("{PLAYER}", user.getDisplayName()); m = m.replace("{PLAYER}", user.getDisplayName());
m = m.replace("{IP}", user.getAddress().toString()); m = m.replace("{IP}", user.getAddress().toString());
m = m.replace("{BALANCE}", Double.toString(user.getMoney())); m = m.replace("{BALANCE}", Double.toString(user.getMoney()));
@@ -433,7 +252,9 @@ public class Essentials extends JavaPlugin
for (Player p : getServer().getOnlinePlayers()) for (Player p : getServer().getOnlinePlayers())
{ {
if (online.length() > 0) if (online.length() > 0)
{
online.append(", "); online.append(", ");
}
online.append(p.getDisplayName()); online.append(p.getDisplayName());
} }
m = m.replace("{PLAYERLIST}", online.toString()); m = m.replace("{PLAYERLIST}", online.toString());
@@ -462,36 +283,16 @@ public class Essentials extends JavaPlugin
return retval; return retval;
} }
public static String FormatTime(long Milliseconds)
{ // format time into a string showing hours, minutes, or seconds
if (Milliseconds > 3600000)
{
double val = Math.round((double)Milliseconds / 360000D) / 10D;
return val + " hour" + (val > 1 ? "s" : "");
}
else if (Milliseconds > 60000)
{
double val = Math.round((double)Milliseconds / 6000D) / 10D;
return val + " minute" + (val > 1 ? "s" : "");
}
else if (Milliseconds <= 1000)
return "1 second";
else
return (Milliseconds / 1000L) + " seconds";
}
@SuppressWarnings("LoggerStringConcat") @SuppressWarnings("LoggerStringConcat")
public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args) public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{ {
if (sender instanceof Player) if (sender instanceof Player)
{
logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0));
} }
}
@Override @Override
@SuppressWarnings(
{
"LoggerStringConcat", "CallToThreadDumpStack"
})
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{ {
// Allow plugins to override the command via onCommand // Allow plugins to override the command via onCommand
@@ -500,26 +301,38 @@ public class Essentials extends JavaPlugin
for (Plugin p : getServer().getPluginManager().getPlugins()) for (Plugin p : getServer().getPluginManager().getPlugins())
{ {
if (p == this) if (p == this)
{
continue; continue;
}
PluginDescriptionFile desc = p.getDescription(); PluginDescriptionFile desc = p.getDescription();
if (desc == null) if (desc == null)
{
continue; continue;
}
if (desc.getName() == null) if (desc.getName() == null)
{
continue; continue;
}
if (!(desc.getCommands() instanceof Map)) if (!(desc.getCommands() instanceof Map))
{
continue; continue;
}
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName())) if (!cmds.containsKey(command.getName()))
{
continue; continue;
}
PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel); PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel);
if (pcmd == null) if (pcmd == null)
{
continue; continue;
}
return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args); return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args);
} }
@@ -528,17 +341,23 @@ public class Essentials extends JavaPlugin
try try
{ {
previewCommand(sender, command, commandLabel, args); previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? User.get(sender) : null; User user = sender instanceof Player ? getUser(sender) : null;
// New mail notification // New mail notification
if (user != null && !Essentials.getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail")) if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{ {
List<String> mail = Essentials.readMail(user); List<String> mail = user.getMails();
if (!mail.isEmpty()) user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); if (!mail.isEmpty())
{
user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
}
} }
// Check for disabled commands // Check for disabled commands
if (Essentials.getSettings().isCommandDisabled(commandLabel)) return true; if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd; IEssentialsCommand cmd;
try try
@@ -548,14 +367,14 @@ public class Essentials extends JavaPlugin
catch (Exception ex) catch (Exception ex)
{ {
sender.sendMessage(ChatColor.RED + "That command is improperly loaded."); sender.sendMessage(ChatColor.RED + "That command is improperly loaded.");
ex.printStackTrace(); logger.log(Level.SEVERE, "Command " + commandLabel + " is improperly loaded.", ex);
return true; return true;
} }
// Check authorization // Check authorization
if (user != null && !user.isAuthorized(cmd)) if (user != null && !user.isAuthorized(cmd))
{ {
logger.warning(user.getName() + " was denied access to command."); logger.log(Level.WARNING, user.getName() + " was denied access to command.");
user.sendMessage(ChatColor.RED + "You do not have access to that command."); user.sendMessage(ChatColor.RED + "You do not have access to that command.");
return true; return true;
} }
@@ -564,23 +383,34 @@ public class Essentials extends JavaPlugin
try try
{ {
if (user == null) if (user == null)
cmd.run(getServer(), this, sender, commandLabel, command, args); {
cmd.run(getServer(), sender, commandLabel, command, args);
}
else else
cmd.run(getServer(), this, user, commandLabel, command, args); {
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage());
return true; return true;
} }
catch (Throwable ex) catch (Throwable ex)
{ {
sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage()); sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage());
if (getSettings().isDebug()) { if (getSettings().isDebug())
logger.log(Level.WARNING, "Error calling command /"+commandLabel, ex); {
logger.log(Level.WARNING, "Error calling command /" + commandLabel, ex);
} }
return true; return true;
} }
} }
catch (Throwable ex) catch (Throwable ex)
{ {
ex.printStackTrace(); logger.log(Level.SEVERE, "Command " + commandLabel + " failed: ", ex);
return true; return true;
} }
} }
@@ -592,7 +422,10 @@ public class Essentials extends JavaPlugin
File ipFile = new File("banned-ips.txt"); File ipFile = new File("banned-ips.txt");
try try
{ {
if (!file.exists()) throw new FileNotFoundException("banned-players.txt not found"); if (!file.exists())
{
throw new FileNotFoundException("banned-players.txt not found");
}
BufferedReader rx = new BufferedReader(new FileReader(file)); BufferedReader rx = new BufferedReader(new FileReader(file));
bans.clear(); bans.clear();
@@ -602,7 +435,10 @@ public class Essentials extends JavaPlugin
{ {
String line = rx.readLine().trim().toLowerCase(); String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue; if (line.startsWith("#"))
{
continue;
}
bans.add(line); bans.add(line);
} }
@@ -619,7 +455,10 @@ public class Essentials extends JavaPlugin
try try
{ {
if (!ipFile.exists()) throw new FileNotFoundException("banned-ips.txt not found"); if (!ipFile.exists())
{
throw new FileNotFoundException("banned-ips.txt not found");
}
BufferedReader rx = new BufferedReader(new FileReader(ipFile)); BufferedReader rx = new BufferedReader(new FileReader(ipFile));
bannedIps.clear(); bannedIps.clear();
@@ -629,7 +468,10 @@ public class Essentials extends JavaPlugin
{ {
String line = rx.readLine().trim().toLowerCase(); String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue; if (line.startsWith("#"))
{
continue;
}
bannedIps.add(line); bannedIps.add(line);
} }
@@ -648,8 +490,8 @@ public class Essentials extends JavaPlugin
private void attachEcoListeners() private void attachEcoListeners()
{ {
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(); EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(this);
EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(); EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(this);
pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this);
pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this); pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this);
pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this); pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this);
@@ -674,4 +516,86 @@ public class Essentials extends JavaPlugin
{ {
return getStatic().worth; return getStatic().worth;
} }
public static Backup getBackup()
{
return getStatic().backup;
}
public static Spawn getSpawn()
{
return getStatic().spawn;
}
public <T> User getUser(T base)
{
if (base instanceof Player)
{
return getUser((Player)base);
}
return null;
}
private <T extends Player> User getUser(T base)
{
if (base == null)
{
return null;
}
if (base instanceof User)
{
return (User)base;
}
if (users.containsKey(base.getName()))
{
return users.get(base.getName()).update(base);
}
User u = new User(base, this);
users.put(u.getName(), u);
return u;
}
public User getOfflineUser(String name)
{
File userFolder = new File(getDataFolder(), "userdata");
File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml");
if (userFile.exists())
{
return new User(new OfflinePlayer(name), this);
}
return null;
}
private boolean newWorldsLoaded = false;
public World getWorld(String name)
{
if (name.matches("[0-9]+"))
{
int id = Integer.parseInt(name);
if (id < getServer().getWorlds().size())
{
return getServer().getWorlds().get(id);
}
}
World w = getServer().getWorld(name);
if (w != null)
{
return w;
}
File bukkitDirectory = getStatic().getDataFolder().getParentFile().getParentFile();
File worldDirectory = new File(bukkitDirectory, name);
if (worldDirectory.exists() && worldDirectory.isDirectory())
{
w = getServer().createWorld(name, World.Environment.NORMAL);
if (w != null)
{
newWorldsLoaded = true;
}
return w;
}
return null;
}
} }

View File

@@ -1,20 +1,16 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.block.*; import org.bukkit.block.*;
import org.bukkit.craftbukkit.block.CraftSign; import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.*; import org.bukkit.event.block.*;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
public class EssentialsBlockListener extends BlockListener public class EssentialsBlockListener extends BlockListener
{ {
private final Essentials parent; private final Essentials ess;
public final static ArrayList<Material> protectedBlocks = new ArrayList<Material>(4); public final static ArrayList<Material> protectedBlocks = new ArrayList<Material>(4);
static static
@@ -25,17 +21,17 @@ public class EssentialsBlockListener extends BlockListener
protectedBlocks.add(Material.DISPENSER); protectedBlocks.add(Material.DISPENSER);
} }
public EssentialsBlockListener(Essentials parent) public EssentialsBlockListener(Essentials ess)
{ {
this.parent = parent; this.ess = ess;
} }
@Override @Override
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled()) return;
if (Essentials.getSettings().areSignsDisabled()) return; if (ess.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override")) if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override"))
{ {
if (isBlockProtected(event.getBlock(), user)) if (isBlockProtected(event.getBlock(), user))
@@ -58,8 +54,8 @@ public class EssentialsBlockListener extends BlockListener
public void onSignChange(SignChangeEvent event) public void onSignChange(SignChangeEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled()) return;
if (Essentials.getSettings().areSignsDisabled()) return; if (ess.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
try try
@@ -171,7 +167,7 @@ public class EssentialsBlockListener extends BlockListener
return; return;
} }
} }
final User user = User.get(event.getPlayer()); final User user = ess.getUser(event.getPlayer());
// Do not rely on getItemInHand(); // Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663 // http://leaky.bukkit.org/issues/663
final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData()); final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData());
@@ -236,7 +232,7 @@ public class EssentialsBlockListener extends BlockListener
} }
boolean unlimitedForUser = user.hasUnlimited(is); boolean unlimitedForUser = user.hasUnlimited(is);
if (unlimitedForUser) { if (unlimitedForUser) {
Essentials.getStatic().getScheduler().scheduleSyncDelayedTask(Essentials.getStatic(), ess.getScheduler().scheduleSyncDelayedTask(ess,
new Runnable() { new Runnable() {
public void run() { public void run() {

View File

@@ -28,7 +28,8 @@ public class EssentialsConf extends Configuration
{ {
super(configFile); super(configFile);
this.configFile = configFile; this.configFile = configFile;
if (this.root == null) { if (this.root == null)
{
this.root = new HashMap<String, Object>(); this.root = new HashMap<String, Object>();
} }
} }
@@ -62,7 +63,8 @@ public class EssentialsConf extends Configuration
} }
} }
super.load(); super.load();
if (this.root == null) { if (this.root == null)
{
this.root = new HashMap<String, Object>(); this.root = new HashMap<String, Object>();
} }
} }
@@ -98,7 +100,8 @@ public class EssentialsConf extends Configuration
{ {
try try
{ {
if (ostr != null) { if (ostr != null)
{
ostr.close(); ostr.close();
} }
} }
@@ -120,73 +123,83 @@ public class EssentialsConf extends Configuration
return configFile; return configFile;
} }
public void setTemplateName(String templateName, Class<?> resClass) { public void setTemplateName(String templateName, Class<?> resClass)
{
this.templateName = templateName; this.templateName = templateName;
this.resourceClass = resClass; this.resourceClass = resClass;
} }
public boolean hasProperty(String path) { public boolean hasProperty(String path)
{
return getProperty(path) != null; return getProperty(path) != null;
} }
public Location getLocation(String path, Server server) { public Location getLocation(String path, Server server)
String worldName = getString(path+".world"); {
if (worldName == null || worldName.isEmpty()) { String worldName = getString((path != null ? path + "." : "") + "world");
if (worldName == null || worldName.isEmpty())
{
return null; return null;
} }
World world = server.getWorld(worldName); World world = server.getWorld(worldName);
if (world == null) { if (world == null)
{
return null; return null;
} }
return new Location(world, return new Location(world,
getDouble(path+".x", 0), getDouble((path != null ? path + "." : "") + "x", 0),
getDouble(path+".y", 0), getDouble((path != null ? path + "." : "") + "y", 0),
getDouble(path+".z", 0), getDouble((path != null ? path + "." : "") + "z", 0),
(float)getDouble(path+".paw", 0), (float)getDouble((path != null ? path + "." : "") + "yaw", 0),
(float)getDouble(path+".pitch", 0)); (float)getDouble((path != null ? path + "." : "") + "pitch", 0));
} }
public void setProperty(String path, Location loc) { public void setProperty(String path, Location loc)
Map<String, Object> map = new HashMap<String, Object>(); {
map.put("world", loc.getWorld().getName()); setProperty((path != null ? path + "." : "") + "world", loc.getWorld().getName());
map.put("x", loc.getX()); setProperty((path != null ? path + "." : "") + "x", loc.getX());
map.put("y", loc.getY()); setProperty((path != null ? path + "." : "") + "y", loc.getY());
map.put("z", loc.getZ()); setProperty((path != null ? path + "." : "") + "z", loc.getZ());
map.put("yaw", loc.getYaw()); setProperty((path != null ? path + "." : "") + "yaw", loc.getYaw());
map.put("pitch", loc.getPitch()); setProperty((path != null ? path + "." : "") + "pitch", loc.getPitch());
setProperty(path, map);
} }
public ItemStack getItemStack(String path) { public ItemStack getItemStack(String path)
{
return new ItemStack( return new ItemStack(
Material.valueOf(getString(path+".type", "AIR")), Material.valueOf(getString(path + ".type", "AIR")),
getInt(path+".amount", 1), getInt(path + ".amount", 1),
(short)getInt(path+".damage", 0), (short)getInt(path + ".damage", 0)/*,
(byte)getInt(path+".data", 0)); (byte)getInt(path + ".data", 0)*/);
} }
public void setProperty(String path, ItemStack stack) { public void setProperty(String path, ItemStack stack)
{
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
map.put("type", stack.getType().toString()); map.put("type", stack.getType().toString());
map.put("amount", stack.getAmount()); map.put("amount", stack.getAmount());
map.put("damage", stack.getDurability()); map.put("damage", stack.getDurability());
// getData().getData() is broken // getData().getData() is broken
map.put("data", stack.getDurability()); //map.put("data", stack.getDurability());
setProperty(path, map); setProperty(path, map);
} }
public long getLong(String path, long def) { public long getLong(String path, long def)
{
Number num = (Number)getProperty(path); Number num = (Number)getProperty(path);
if (num == null) { if (num == null)
{
return def; return def;
} }
return num.longValue(); return num.longValue();
} }
@Override @Override
public double getDouble(String path, double def) { public double getDouble(String path, double def)
{
Number num = (Number)getProperty(path); Number num = (Number)getProperty(path);
if (num == null) { if (num == null)
{
return def; return def;
} }
return num.doubleValue(); return num.doubleValue();

View File

@@ -11,21 +11,37 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEcoBlockListener extends BlockListener public class EssentialsEcoBlockListener extends BlockListener
{ {
Essentials ess;
public EssentialsEcoBlockListener(Essentials ess)
{
this.ess = ess;
}
@Override @Override
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled())
if (Essentials.getSettings().areSignsDisabled()) return; {
User user = User.get(event.getPlayer()); return;
}
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST) if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST)
{
return; return;
}
Sign sign = new CraftSign(event.getBlock()); Sign sign = new CraftSign(event.getBlock());
if (sign.getLine(0).equals("§1[Trade]")) if (sign.getLine(0).equals("§1[Trade]"))
{ {
if (!sign.getLine(3).substring(2).equals(username)) { if (!sign.getLine(3).substring(2).equals(username))
if (!user.isOp()) { {
if (!user.isOp())
{
event.setCancelled(true); event.setCancelled(true);
} }
return; return;
@@ -40,20 +56,31 @@ public class EssentialsEcoBlockListener extends BlockListener
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r1 = Integer.parseInt(l1[m1 ? 1 : 2]); int r1 = Integer.parseInt(l1[m1 ? 1 : 2]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); if (q1 < 1 || q2 < 1)
{
throw new Exception("Quantities must be greater than 0.");
}
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1); ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1);
ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], r2); ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], r2);
if (m1) if (m1)
{
user.giveMoney(r1); user.giveMoney(r1);
}
else if (i1 != null) else if (i1 != null)
{
user.getWorld().dropItem(user.getLocation(), i1); user.getWorld().dropItem(user.getLocation(), i1);
}
if (m2) if (m2)
{
user.giveMoney(r2); user.giveMoney(r2);
}
else if (i2 != null) else if (i2 != null)
{
user.getWorld().dropItem(user.getLocation(), i2); user.getWorld().dropItem(user.getLocation(), i2);
}
sign.setType(Material.AIR); sign.setType(Material.AIR);
} }
@@ -65,12 +92,14 @@ public class EssentialsEcoBlockListener extends BlockListener
} }
} }
@Override @Override
public void onSignChange(SignChangeEvent event) public void onSignChange(SignChangeEvent event)
{ {
if (Essentials.getSettings().areSignsDisabled()) return; if (ess.getSettings().areSignsDisabled())
User user = User.get(event.getPlayer()); {
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getLine(0).equalsIgnoreCase("[Buy]") && user.isAuthorized("essentials.signs.buy.create")) if (event.getLine(0).equalsIgnoreCase("[Buy]") && user.isAuthorized("essentials.signs.buy.create"))
@@ -80,7 +109,8 @@ public class EssentialsEcoBlockListener extends BlockListener
event.setLine(0, "§1[Buy]"); event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2)); ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0) { if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air."); throw new Exception("Don't sell air.");
} }
event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", "")));
@@ -103,7 +133,8 @@ public class EssentialsEcoBlockListener extends BlockListener
event.setLine(0, "§1[Sell]"); event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2)); ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0) { if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't buy air."); throw new Exception("Don't buy air.");
} }
event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", "")));
@@ -131,19 +162,31 @@ public class EssentialsEcoBlockListener extends BlockListener
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r2 = r2 - r2 % q2; r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1 || r2 < 1) throw new Exception("Quantities must be greater than 0."); if (q1 < 1 || q2 < 1 || r2 < 1)
if (!m1) ItemDb.get(l1[1]); {
throw new Exception("Quantities must be greater than 0.");
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2) if (m2)
{ {
if (user.getMoney() < r2) throw new Exception("You do not have sufficient funds."); if (user.getMoney() < r2)
{
throw new Exception("You do not have sufficient funds.");
}
user.takeMoney(r2); user.takeMoney(r2);
user.sendMessage("r2: " + r2 + " q2: " + q2); user.sendMessage("r2: " + r2 + " q2: " + q2);
} }
else else
{ {
ItemStack i2 = ItemDb.get(l2[1], r2); ItemStack i2 = ItemDb.get(l2[1], r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2)) throw new Exception("You do not have " + r2 + "x " + l2[1] + "."); if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception("You do not have " + r2 + "x " + l2[1] + ".");
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2); InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory(); user.updateInventory();
} }

View File

@@ -12,17 +12,30 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEcoPlayerListener extends PlayerListener public class EssentialsEcoPlayerListener extends PlayerListener
{ {
Essentials ess;
@Override EssentialsEcoPlayerListener(Essentials ess)
{
this.ess = ess;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event)
{ {
if (ess.getSettings().areSignsDisabled())
if (Essentials.getSettings().areSignsDisabled()) return; {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; return;
User user = User.get(event.getPlayer()); }
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST) if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return; return;
}
Sign sign = new CraftSign(event.getClickedBlock()); Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use")) if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
@@ -32,10 +45,14 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int amount = Integer.parseInt(sign.getLine(1)); int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount); ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1)); int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds."); if (user.getMoney() < cost)
{
throw new Exception("You do not have sufficient funds.");
}
user.takeMoney(cost); user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item); Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values()) { for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack); user.getWorld().dropItem(user.getLocation(), itemStack);
} }
user.updateInventory(); user.updateInventory();
@@ -54,7 +71,10 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int amount = Integer.parseInt(sign.getLine(1)); int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount); ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1)); int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell."); if (!InventoryWorkaround.containsItem(user.getInventory(), true, item))
{
throw new Exception("You do not have enough items to sell.");
}
user.giveMoney(cost); user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item); InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory(); user.updateInventory();
@@ -80,9 +100,12 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r1 = r1 - r1 % q1; r1 = r1 - r1 % q1;
r2 = r2 - r2 % q2; r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); if (q1 < 1 || q2 < 1)
{
throw new Exception("Quantities must be greater than 0.");
}
ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1); ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1); ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2); ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2);
@@ -95,7 +118,8 @@ public class EssentialsEcoPlayerListener extends PlayerListener
else if (i1 != null) else if (i1 != null)
{ {
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1); Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values()) { for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack); user.getWorld().dropItem(user.getLocation(), itemStack);
} }
user.updateInventory(); user.updateInventory();
@@ -108,26 +132,41 @@ public class EssentialsEcoPlayerListener extends PlayerListener
if (m1) if (m1)
{ {
if (user.getMoney() < q1) if (user.getMoney() < q1)
{
throw new Exception("You do not have sufficient funds."); throw new Exception("You do not have sufficient funds.");
} }
}
else else
{ {
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1)) if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
{
throw new Exception("You do not have " + q1 + "x " + l1[1] + "."); throw new Exception("You do not have " + q1 + "x " + l1[1] + ".");
} }
}
if (r2 < q2) throw new Exception("The trade sign does not have enough supply left."); if (r2 < q2)
{
throw new Exception("The trade sign does not have enough supply left.");
}
if (m1) if (m1)
{
user.takeMoney(q1); user.takeMoney(q1);
}
else else
{
InventoryWorkaround.removeItem(user.getInventory(), true, qi1); InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
}
if (m2) if (m2)
{
user.giveMoney(q2); user.giveMoney(q2);
else { }
else
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2); Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2);
for (ItemStack itemStack : leftOver.values()) { for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack); user.getWorld().dropItem(user.getLocation(), itemStack);
} }
} }

View File

@@ -16,13 +16,11 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEntityListener extends EntityListener public class EssentialsEntityListener extends EntityListener
{ {
private final Server server; private final Essentials ess;
private final Essentials parent;
public EssentialsEntityListener(Essentials parent) public EssentialsEntityListener(Essentials parent)
{ {
this.parent = parent; this.ess = parent;
this.server = parent.getServer();
} }
@Override @Override
@@ -35,11 +33,12 @@ public class EssentialsEntityListener extends EntityListener
Entity eDefend = edEvent.getEntity(); Entity eDefend = edEvent.getEntity();
if (eDefend instanceof Player && eAttack instanceof Player) if (eDefend instanceof Player && eAttack instanceof Player)
{ {
User defender = User.get(eDefend); User defender = ess.getUser(eDefend);
User attacker = User.get(eAttack); User attacker = ess.getUser(eAttack);
ItemStack is = attacker.getItemInHand(); ItemStack is = attacker.getItemInHand();
String command = attacker.getPowertool(is); String command = attacker.getPowertool(is);
if (command != null && !command.isEmpty()) { if (command != null && !command.isEmpty())
{
attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName())); attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName()));
event.setCancelled(true); event.setCancelled(true);
return; return;
@@ -49,7 +48,7 @@ public class EssentialsEntityListener extends EntityListener
if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent) if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent)
{ {
if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{ {
CraftPlayer player = (CraftPlayer)event.getEntity(); CraftPlayer player = (CraftPlayer)event.getEntity();
player.getHandle().fireTicks = 0; player.getHandle().fireTicks = 0;
@@ -59,11 +58,10 @@ public class EssentialsEntityListener extends EntityListener
} }
} }
@Override @Override
public void onEntityCombust(EntityCombustEvent event) public void onEntityCombust(EntityCombustEvent event)
{ {
if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{ {
event.setCancelled(true); event.setCancelled(true);
} }
@@ -74,13 +72,12 @@ public class EssentialsEntityListener extends EntityListener
{ {
if (event.getEntity() instanceof Player) if (event.getEntity() instanceof Player)
{ {
User user = User.get(event.getEntity()); User user = ess.getUser(event.getEntity());
if(user.isAuthorized("essentials.back.ondeath")) if (user.isAuthorized("essentials.back.ondeath"))
{ {
user.lastLocation = user.getLocation(); user.setLastLocation();
user.sendMessage("§7Use the /back command to return to your death point"); user.sendMessage("§7Use the /back command to return to your death point");
} }
} }
} }
} }

View File

@@ -20,12 +20,12 @@ public class EssentialsPlayerListener extends PlayerListener
{ {
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
private final Server server; private final Server server;
private final Essentials parent; private final Essentials ess;
private EssentialsBlockListener essBlockListener = null; private EssentialsBlockListener essBlockListener = null;
public EssentialsPlayerListener(Essentials parent) public EssentialsPlayerListener(Essentials parent)
{ {
this.parent = parent; this.ess = parent;
this.server = parent.getServer(); this.server = parent.getServer();
essBlockListener = new EssentialsBlockListener(parent); essBlockListener = new EssentialsBlockListener(parent);
} }
@@ -33,15 +33,24 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerRespawn(PlayerRespawnEvent event) public void onPlayerRespawn(PlayerRespawnEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
user.setDisplayName(user.getNick()); user.setDisplayName(user.getNick());
updateCompass(user); updateCompass(user);
if (user.isJailed() && user.getJail() != null && !user.getJail().isEmpty()) {
try
{
event.setRespawnLocation(Essentials.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
}
}
} }
@Override @Override
public void onPlayerChat(PlayerChatEvent event) public void onPlayerChat(PlayerChatEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (user.isMuted()) if (user.isMuted())
{ {
event.setCancelled(true); event.setCancelled(true);
@@ -52,20 +61,29 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerMove(PlayerMoveEvent event) public void onPlayerMove(PlayerMoveEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled())
final User user = User.get(event.getPlayer()); {
return;
}
final User user = ess.getUser(event.getPlayer());
if (!Essentials.getSettings().getNetherPortalsEnabled()) return; if (!ess.getSettings().getNetherPortalsEnabled())
{
return;
}
final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ()); final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
List<World> worlds = server.getWorlds(); List<World> worlds = server.getWorlds();
if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal")) if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal"))
{ {
if (user.getJustPortaled()) return; if (user.getJustPortaled())
{
return;
}
Location loc = event.getTo(); Location loc = event.getTo();
World nether = server.getWorld(Essentials.getSettings().getNetherName()); World nether = server.getWorld(ess.getSettings().getNetherName());
if (nether == null) { if (nether == null) {
for (World world : worlds) for (World world : worlds)
{ {
@@ -81,8 +99,9 @@ public class EssentialsPlayerListener extends PlayerListener
final World world = user.getWorld() == nether ? worlds.get(0) : nether; final World world = user.getWorld() == nether ? worlds.get(0) : nether;
double factor; double factor;
if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) { if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL)
if (Essentials.getSettings().use1to1RatioInNether()) {
if (ess.getSettings().use1to1RatioInNether())
{ {
factor = 1.0; factor = 1.0;
} }
@@ -91,8 +110,9 @@ public class EssentialsPlayerListener extends PlayerListener
factor = 16.0; factor = 16.0;
} }
} }
else if (user.getWorld().getEnvironment() != world.getEnvironment()) { else if (user.getWorld().getEnvironment() != world.getEnvironment())
if (Essentials.getSettings().use1to1RatioInNether()) {
if (ess.getSettings().use1to1RatioInNether())
{ {
factor = 1.0; factor = 1.0;
} }
@@ -101,7 +121,8 @@ public class EssentialsPlayerListener extends PlayerListener
factor = 1.0 / 16.0; factor = 1.0 / 16.0;
} }
} }
else { else
{
factor = 1.0; factor = 1.0;
} }
@@ -110,9 +131,13 @@ public class EssentialsPlayerListener extends PlayerListener
int z = loc.getBlockZ(); int z = loc.getBlockZ();
if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL) if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL)
{
z--; z--;
}
if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL) if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL)
{
x--; x--;
}
x = (int)(x * factor); x = (int)(x * factor);
z = (int)(z * factor); z = (int)(z * factor);
@@ -122,7 +147,7 @@ public class EssentialsPlayerListener extends PlayerListener
NetherPortal portal = NetherPortal.findPortal(dest); NetherPortal portal = NetherPortal.findPortal(dest);
if (portal == null) if (portal == null)
{ {
if (world.getEnvironment() == World.Environment.NETHER || Essentials.getSettings().getGenerateExitPortals()) if (world.getEnvironment() == World.Environment.NETHER || ess.getSettings().getGenerateExitPortals())
{ {
portal = NetherPortal.createPortal(dest); portal = NetherPortal.createPortal(dest);
logger.info(event.getPlayer().getName() + " used a portal and generated an exit portal."); logger.info(event.getPlayer().getName() + " used a portal and generated an exit portal.");
@@ -141,7 +166,7 @@ public class EssentialsPlayerListener extends PlayerListener
event.setTo(loc); event.setTo(loc);
try try
{ {
user.teleportToNow(loc); user.getTeleport().teleport(loc, "portal");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -160,14 +185,14 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerQuit(PlayerQuitEvent event) public void onPlayerQuit(PlayerQuitEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if(user.savedInventory != null) if (user.getSavedInventory() != null)
{ {
user.getInventory().setContents(user.savedInventory); user.getInventory().setContents(user.getSavedInventory());
user.savedInventory = null; user.setSavedInventory(null);
} }
if (!Essentials.getSettings().getReclaimSetting()) if (!ess.getSettings().getReclaimSetting())
{ {
return; return;
} }
@@ -201,54 +226,68 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerJoin(PlayerJoinEvent event) public void onPlayerJoin(PlayerJoinEvent event)
{ {
Essentials.getStatic().backup.onPlayerJoin(); Essentials.getBackup().onPlayerJoin();
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
//we do not know the ip address on playerlogin so we need to do this here. //we do not know the ip address on playerlogin so we need to do this here.
if (user.isIpBanned()) if (user.isIpBanned())
{ {
user.kickPlayer("The Ban Hammer has spoken!"); String banReason = user.getBanReason();
user.kickPlayer(banReason != null && !banReason.isEmpty() ? banReason : "The Ban Hammer has spoken!");
return; return;
} }
user.setDisplayName(user.getNick()); user.setDisplayName(user.getNick());
if (!Essentials.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd"))
{ {
for (String m : parent.getMotd(user, null)) for (String m : ess.getMotd(user, null))
{ {
if (m == null) continue; if (m == null)
{
continue;
}
user.sendMessage(m); user.sendMessage(m);
} }
} }
if (!Essentials.getSettings().isCommandDisabled("mail")) if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail"))
{ {
List<String> mail = Essentials.readMail(user); List<String> mail = user.getMails();
if (mail.isEmpty()) user.sendMessage("§7You have no new mail."); if (mail.isEmpty())
else user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); {
user.sendMessage("§7You have no new mail.");
}
else
{
user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
}
} }
} }
@Override @Override
public void onPlayerLogin(PlayerLoginEvent event) public void onPlayerLogin(PlayerLoginEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (event.getResult() != Result.ALLOWED) if (event.getResult() != Result.ALLOWED)
return;
if (user.isBanned())
{ {
event.disallow(Result.KICK_BANNED, "The Ban Hammer has spoken!");
return; return;
} }
if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isOp()) if (user.isBanned())
{
String banReason = user.getBanReason();
event.disallow(Result.KICK_BANNED, banReason != null && !banReason.isEmpty() ? banReason : "The Ban Hammer has spoken!");
return;
}
if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isAuthorized("essentials.joinfullserver"))
{ {
event.disallow(Result.KICK_FULL, "Server is full"); event.disallow(Result.KICK_FULL, "Server is full");
return; return;
} }
user.setLastLogin(System.currentTimeMillis());
updateCompass(user); updateCompass(user);
} }
@@ -266,13 +305,18 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerTeleport(PlayerTeleportEvent event) public void onPlayerTeleport(PlayerTeleportEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled())
User user = User.get(event.getPlayer()); {
if (user.currentJail == null || user.currentJail.isEmpty())
return; return;
}
User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try try
{ {
event.setTo(Essentials.getJail().getJail(user.currentJail)); event.setTo(Essentials.getJail().getJail(user.getJail()));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -284,11 +328,21 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled())
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; {
User user = User.get(event.getPlayer()); return;
if (user.isJailed()) return; }
if (!Essentials.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType())) if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
return;
}
if (!ess.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType()))
{ {
if (!user.isAuthorized("essentials.signs.protection.override")) if (!user.isAuthorized("essentials.signs.protection.override"))
{ {
@@ -301,7 +355,7 @@ public class EssentialsPlayerListener extends PlayerListener
} }
} }
if (Essentials.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK) if (ess.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK)
{ {
try try
{ {
@@ -314,9 +368,14 @@ public class EssentialsPlayerListener extends PlayerListener
} }
if (Essentials.getSettings().areSignsDisabled()) return; if (ess.getSettings().areSignsDisabled())
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST) {
return; return;
}
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getClickedBlock()); Sign sign = new CraftSign(event.getClickedBlock());
try try
@@ -375,13 +434,16 @@ public class EssentialsPlayerListener extends PlayerListener
} }
if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail")) if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail"))
{ {
List<String> mail = Essentials.readMail(user); List<String> mail = user.getMails();
if (mail.isEmpty()) if (mail.isEmpty())
{ {
user.sendMessage("§cYou do not have any mail!"); user.sendMessage("§cYou do not have any mail!");
return; return;
} }
for (String s : mail) user.sendMessage(s); for (String s : mail)
{
user.sendMessage(s);
}
user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); user.sendMessage("§cTo mark your mail as read, type §c/mail clear");
return; return;
} }
@@ -425,22 +487,19 @@ public class EssentialsPlayerListener extends PlayerListener
{ {
if (sign.getLine(2).equals("§2Everyone")) if (sign.getLine(2).equals("§2Everyone"))
{ {
user.teleportCooldown(); user.getTeleport().warp(sign.getLine(1), "warpsign");
user.warpTo(sign.getLine(1));
return; return;
} }
if (user.inGroup(sign.getLine(2))) if (user.inGroup(sign.getLine(2)))
{ {
user.teleportCooldown(); user.getTeleport().warp(sign.getLine(1), "warpsign");
user.warpTo(sign.getLine(1));
return; return;
} }
} }
if (user.isAuthorized("essentials.signs.warp.use") if (user.isAuthorized("essentials.signs.warp.use")
&& (!Essentials.getSettings().getPerWarpPermission() || user.isAuthorized("essentials.warp." + sign.getLine(1)))) && (!ess.getSettings().getPerWarpPermission() || user.isAuthorized("essentials.warp." + sign.getLine(1))))
{ {
user.teleportCooldown(); user.getTeleport().warp(sign.getLine(1), "warpsign");
user.warpTo(sign.getLine(1));
} }
return; return;
} }
@@ -454,7 +513,7 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerEggThrow(PlayerEggThrowEvent event) public void onPlayerEggThrow(PlayerEggThrowEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
ItemStack is = new ItemStack(Material.EGG, 1); ItemStack is = new ItemStack(Material.EGG, 1);
if (user.hasUnlimited(is)) if (user.hasUnlimited(is))
{ {
@@ -466,7 +525,7 @@ public class EssentialsPlayerListener extends PlayerListener
@Override @Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{ {
final User user = User.get(event.getPlayer()); final User user = ess.getUser(event.getPlayer());
if (user.hasUnlimited(new ItemStack(event.getBucket()))) if (user.hasUnlimited(new ItemStack(event.getBucket())))
{ {
event.getItemStack().setType(event.getBucket()); event.getItemStack().setType(event.getBucket());
@@ -493,7 +552,7 @@ public class EssentialsPlayerListener extends PlayerListener
{ {
return; return;
} }
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
ItemStack is = user.getItemInHand(); ItemStack is = user.getItemInHand();
if (is == null || is.getType() == Material.AIR) if (is == null || is.getType() == Material.AIR)
{ {

View File

@@ -0,0 +1,81 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Player;
public class EssentialsTimer implements Runnable, IConf
{
private Essentials parent;
private Set<User> allUsers = new HashSet<User>();
EssentialsTimer(Essentials parent)
{
this.parent = parent;
File userdir = new File(parent.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
for (String string : userdir.list())
{
if (!string.endsWith(".yml")) {
continue;
}
String name = string.substring(0, string.length()-4);
User u = parent.getUser(new OfflinePlayer(name));
allUsers.add(u);
}
}
public void run()
{
long currentTime = System.currentTimeMillis();
for (Player player : parent.getServer().getOnlinePlayers())
{
User u = parent.getUser(player);
allUsers.add(u);
u.setLastActivity(currentTime);
}
for (User user: allUsers) {
if (user.getBanTimeout() > 0 && user.getBanTimeout() < currentTime) {
user.setBanTimeout(0);
((CraftServer)parent.getServer()).getHandle().b(user.getName());
Essentials.getStatic().loadBanList();
}
if (user.getMuteTimeout() > 0 && user.getMuteTimeout() < currentTime && user.isMuted()) {
user.setMuteTimeout(0);
user.sendMessage("§7You can talk again");
user.setMuted(false);
}
if (user.getJailTimeout() > 0 && user.getJailTimeout() < currentTime && user.isJailed()) {
user.setJailTimeout(0);
user.setJailed(false);
user.sendMessage("§7You have been released");
user.setJail(null);
try
{
user.getTeleport().back();
}
catch (Exception ex)
{
}
}
if (user.getLastActivity() < currentTime && user.getLastActivity() > user.getLastLogout()) {
user.setLastLogout(user.getLastActivity());
}
}
}
public void reloadConfig()
{
for (User user : allUsers)
{
user.reloadConfig();
}
}
}

View File

@@ -5,77 +5,351 @@ import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class EssentialsUpgrade {
public class EssentialsUpgrade
{
private static boolean alreadyRun = false; private static boolean alreadyRun = false;
private final static Logger logger = Logger.getLogger("Minecraft"); private final static Logger logger = Logger.getLogger("Minecraft");
private Essentials ess;
EssentialsUpgrade(String version, File dataFolder) { EssentialsUpgrade(String version, Essentials essentials)
if (alreadyRun == true) return; {
if (alreadyRun == true)
{
return;
}
alreadyRun = true; alreadyRun = true;
moveWorthValuesToWorthYml(dataFolder); ess = essentials;
if (!ess.getDataFolder().exists())
{
ess.getDataFolder().mkdirs();
}
moveWorthValuesToWorthYml();
sanitizeAllUserFilenames();
updateUsersToNewDefaultHome();
moveUsersDataToUserdataFolder();
convertWarps();
} }
private void moveWorthValuesToWorthYml(File dataFolder) { private void moveWorthValuesToWorthYml()
try { {
File configFile = new File(dataFolder, "config.yml"); try
if (!configFile.exists()) { {
File configFile = new File(ess.getDataFolder(), "config.yml");
if (!configFile.exists())
{
return; return;
} }
EssentialsConf conf = new EssentialsConf(configFile); EssentialsConf conf = new EssentialsConf(configFile);
conf.load(); conf.load();
Worth w = new Worth(dataFolder); Worth w = new Worth(ess.getDataFolder());
for (Material mat : Material.values()) { for (Material mat : Material.values())
{
int id = mat.getId(); int id = mat.getId();
double value = conf.getDouble("worth-"+id, Double.NaN); double value = conf.getDouble("worth-" + id, Double.NaN);
if (!Double.isNaN(value)) { if (!Double.isNaN(value))
{
w.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value); w.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value);
} }
} }
removeLinesFromConfig(configFile,"\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml"); removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
} catch (Throwable e) { }
catch (Throwable e)
{
logger.log(Level.SEVERE, "Error while upgrading the files", e); logger.log(Level.SEVERE, "Error while upgrading the files", e);
} }
} }
private void removeLinesFromConfig(File file, String regex, String info) throws Exception { private void removeLinesFromConfig(File file, String regex, String info) throws Exception
{
boolean needUpdate = false; boolean needUpdate = false;
BufferedReader br = new BufferedReader(new FileReader(file)); BufferedReader br = new BufferedReader(new FileReader(file));
File tempFile = File.createTempFile("essentialsupgrade", ".yml"); File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder());
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
do { do
{
String line = br.readLine(); String line = br.readLine();
if (line == null) break; if (line == null)
if (line.matches(regex)) { {
if (needUpdate == false && info != null) { break;
}
if (line.matches(regex))
{
if (needUpdate == false && info != null)
{
bw.write(info, 0, info.length()); bw.write(info, 0, info.length());
bw.newLine(); bw.newLine();
} }
needUpdate = true; needUpdate = true;
} else { }
if (line.endsWith("\r\n")) { else
{
if (line.endsWith("\r\n"))
{
bw.write(line, 0, line.length() - 2); bw.write(line, 0, line.length() - 2);
} else if (line.endsWith("\r") || line.endsWith("\n")) { }
else if (line.endsWith("\r") || line.endsWith("\n"))
{
bw.write(line, 0, line.length() - 1); bw.write(line, 0, line.length() - 1);
} else { }
else
{
bw.write(line, 0, line.length()); bw.write(line, 0, line.length());
} }
bw.newLine(); bw.newLine();
} }
} while(true); }
while (true);
br.close(); br.close();
bw.close(); bw.close();
if (needUpdate) { if (needUpdate)
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("."+System.currentTimeMillis()+".upgradebackup")))) { {
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup"))))
{
throw new Exception("Failed to move config.yml to backup location."); throw new Exception("Failed to move config.yml to backup location.");
} }
if (!tempFile.renameTo(file)) { if (!tempFile.renameTo(file))
{
throw new Exception("Failed to rename temp file to config.yml"); throw new Exception("Failed to rename temp file to config.yml");
} }
} }
} }
private void updateUsersToNewDefaultHome()
{
File userdataFolder = new File(ess.getDataFolder(), "userdata");
if (!userdataFolder.exists() || !userdataFolder.isDirectory())
{
return;
}
File[] userFiles = userdataFolder.listFiles();
for (File file : userFiles)
{
if (!file.isFile() || !file.getName().endsWith(".yml"))
{
continue;
}
EssentialsConf config = new EssentialsConf(file);
if (config.hasProperty("home") && !config.hasProperty("home.default"))
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)config.getProperty("home");
World world = ess.getServer() == null ? null : ess.getServer().getWorlds().get(0);
if (vals.size() > 5 && ess.getServer() != null)
{
world = ess.getServer().getWorld((String)vals.get(5));
}
if (world != null)
{
Location loc = new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
String worldName = world.getName().toLowerCase();
if (worldName != null && !worldName.isEmpty())
{
config.removeProperty("home");
config.setProperty("home.default", worldName);
config.setProperty("home.worlds." + worldName, loc);
config.save();
}
}
}
}
}
private void moveUsersDataToUserdataFolder()
{
File usersFile = new File(ess.getDataFolder(), "users.yml");
if (!usersFile.exists())
{
return;
}
EssentialsConf usersConfig = new EssentialsConf(usersFile);
usersConfig.load();
for (String username : usersConfig.getKeys(null))
{
User user = new User(new OfflinePlayer(username), ess);
String nickname = usersConfig.getString(username + ".nickname");
if (nickname != null && !nickname.isEmpty() && !nickname.equals(username))
{
user.setNickname(nickname);
}
List<String> mails = usersConfig.getStringList(username + ".mail", null);
if (mails != null && !mails.isEmpty())
{
user.setMails(mails);
}
if (user.getHome() == null)
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home");
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = ess.getWorld((String)vals.get(5));
}
if (world != null)
{
user.setHome(new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue()), true);
}
}
}
}
private void convertWarps()
{
File warpsFolder = new File(ess.getDataFolder(), "warps");
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
}
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1)
{
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".dat"))
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x = Double.parseDouble(rx.readLine().trim());
double y = Double.parseDouble(rx.readLine().trim());
double z = Double.parseDouble(rx.readLine().trim());
float yaw = Float.parseFloat(rx.readLine().trim());
float pitch = Float.parseFloat(rx.readLine().trim());
String worldName = rx.readLine();
rx.close();
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
boolean forceWorldName = false;
if (worldName != null)
{
worldName.trim();
World w1 = null;
w1 = ess.getWorld(worldName);
if (w1 != null)
{
w = w1;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
Essentials.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc);
if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{
throw new Exception("Renaming file " + filename + " failed");
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
}
File warpFile = new File(ess.getDataFolder(), "warps.txt");
if (warpFile.exists())
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(warpFile));
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":"))
{
if (parts.length < 6)
{
continue;
}
String name = parts[0];
double x = Double.parseDouble(parts[1].trim());
double y = Double.parseDouble(parts[2].trim());
double z = Double.parseDouble(parts[3].trim());
float yaw = Float.parseFloat(parts[4].trim());
float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty())
{
continue;
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
Essentials.getWarps().setWarp(name, loc);
if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old")))
{
throw new Exception("Renaming warps.txt failed");
}
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
private void sanitizeAllUserFilenames()
{
File usersFolder = new File(ess.getDataFolder(), "userdata");
if (!usersFolder.exists())
{
return;
}
File[] listOfFiles = usersFolder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (!listOfFiles[i].isFile() || !filename.endsWith(".yml"))
{
continue;
}
String sanitizedFilename = Util.sanitizeFileName(filename);
if (sanitizedFilename.equals(filename))
{
continue;
}
File newFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename);
if (newFile.exists())
{
logger.log(Level.WARNING, "Duplicated userdata: "+filename+" and "+sanitizedFilename);
continue;
}
if (!listOfFiles[i].renameTo(newFile)) {
logger.log(Level.WARNING, "Failed to move userdata/"+filename+" to userdata/"+sanitizedFilename);
}
}
}
} }

View File

@@ -8,7 +8,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.*; import java.util.*;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -96,7 +95,7 @@ public class ItemDb
throw new Exception("Unknown item id: "+itemid); throw new Exception("Unknown item id: "+itemid);
} }
ItemStack retval = new ItemStack(mat); ItemStack retval = new ItemStack(mat);
retval.setAmount(Essentials.getSettings().getDefaultStackSize()); retval.setAmount(Essentials.getStatic().getSettings().getDefaultStackSize());
retval.setDurability(durabilities.containsKey(id.toLowerCase()) ? durabilities.get(id.toLowerCase()) : 0); retval.setDurability(durabilities.containsKey(id.toLowerCase()) ? durabilities.get(id.toLowerCase()) : 0);
return retval; return retval;
} }

View File

@@ -1,12 +1,9 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import java.io.File; import java.io.File;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.BlockListener;
@@ -17,23 +14,18 @@ public class Jail extends BlockListener implements IConf
{ {
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
private EssentialsConf config; private EssentialsConf config;
private Essentials ess;
public Jail(File dataFolder) public Jail(Essentials ess)
{ {
config = new EssentialsConf(new File(dataFolder, "jail.yml")); this.ess = ess;
config = new EssentialsConf(new File(ess.getDataFolder(), "jail.yml"));
config.load(); config.load();
} }
public void setJail(Location loc, String jailName) throws Exception public void setJail(Location loc, String jailName) throws Exception
{ {
Map<String, Object> map = new HashMap<String, Object>(); config.setProperty(jailName.toLowerCase(), loc);
map.put("world", loc.getWorld().getName());
map.put("x", loc.getX());
map.put("y", loc.getY());
map.put("z", loc.getZ());
map.put("yaw", loc.getYaw());
map.put("pitch", loc.getPitch());
config.setProperty(jailName.toLowerCase(), map);
config.save(); config.save();
} }
@@ -44,29 +36,14 @@ public class Jail extends BlockListener implements IConf
throw new Exception("That jail does not exist"); throw new Exception("That jail does not exist");
} }
World jWorld = null; Location loc = config.getLocation(jailName.toLowerCase(), Essentials.getStatic().getServer());
String world = config.getString(jailName + ".world", ""); // wh.spawnX return loc;
double x = config.getDouble(jailName + ".x", 0); // wh.spawnX
double y = config.getDouble(jailName + ".y", 0); // wh.spawnY
double z = config.getDouble(jailName + ".z", 0); // wh.spawnZ
float yaw = (float)config.getDouble(jailName + ".yaw", 0);
float pitch = (float)config.getDouble(jailName + ".pitch", 0);
for (World w : Essentials.getStatic().getServer().getWorlds())
{
if (w.getName().equalsIgnoreCase(world))
{
jWorld = w;
break;
}
}
return new Location(jWorld, x, y, z, yaw, pitch);
} }
public void sendToJail(User user, String jail) throws Exception public void sendToJail(User user, String jail) throws Exception
{ {
user.teleportToNow(getJail(jail)); user.getTeleport().now(getJail(jail));
user.currentJail = jail; user.setJail(jail);
} }
public void delJail(String jail) throws Exception public void delJail(String jail) throws Exception
@@ -88,7 +65,7 @@ public class Jail extends BlockListener implements IConf
@Override @Override
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (user.isJailed()) if (user.isJailed())
{ {
event.setCancelled(true); event.setCancelled(true);
@@ -98,7 +75,7 @@ public class Jail extends BlockListener implements IConf
@Override @Override
public void onBlockPlace(BlockPlaceEvent event) public void onBlockPlace(BlockPlaceEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (user.isJailed()) if (user.isJailed())
{ {
event.setCancelled(true); event.setCancelled(true);
@@ -108,7 +85,7 @@ public class Jail extends BlockListener implements IConf
@Override @Override
public void onBlockDamage(BlockDamageEvent event) public void onBlockDamage(BlockDamageEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (user.isJailed()) if (user.isJailed())
{ {
event.setCancelled(true); event.setCancelled(true);

View File

@@ -1,25 +1,22 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerListener;
public class JailPlayerListener extends PlayerListener public class JailPlayerListener extends PlayerListener
{ {
private final Server server; private final Essentials ess;
private final Essentials parent;
public JailPlayerListener(Essentials parent) public JailPlayerListener(Essentials parent)
{ {
this.parent = parent; this.ess = parent;
this.server = parent.getServer();
} }
@Override @Override
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event)
{ {
User user = User.get(event.getPlayer()); User user = ess.getUser(event.getPlayer());
if (user.isJailed()) if (user.isJailed())
{ {
event.setCancelled(true); event.setCancelled(true);

View File

@@ -1,7 +1,5 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer;
import net.minecraft.server.EntityPlayer; import net.minecraft.server.EntityPlayer;
import net.minecraft.server.IInventory; import net.minecraft.server.IInventory;
@@ -45,63 +43,6 @@ public class PlayerExtension extends PlayerWrapper
showInventory((IInventory)inventory.getInventory()); showInventory((IInventory)inventory.getInventory());
} }
public Location getSafeDestination(Location loc) throws Exception
{
World world = loc.getWorld();
double x = Math.floor(loc.getX())+0.5;
double y = Math.floor(loc.getY());
double z = Math.floor(loc.getZ())+0.5;
while (isBlockAboveAir(world, x, y, z))
{
y -= 1.0D;
if (y < 0.0D) {
throw new Exception("Hole in floor");
}
}
while (isBlockUnsafe(world, x, y, z))
{
y += 1.0D;
if (y >= 110.0D) {
x += 1.0D;
break;
}
}
while (isBlockUnsafe(world, x, y, z))
{
y -= 1.0D;
if (y <= 1.0D)
{
y = 110.0D;
x += 1.0D;
}
}
return new Location(world, x, y, z, loc.getYaw(), loc.getPitch());
}
private boolean isBlockAboveAir(World world, double x, double y, double z)
{
return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR;
}
public boolean isBlockUnsafe(World world, double x, double y, double z)
{
Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z));
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
return true;
if (below.getType() == Material.FIRE)
return true;
if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR))
{
return true;
}
return isBlockAboveAir(world, x, y, z);
}
public TargetBlock getTarget() public TargetBlock getTarget()
{ {
return new TargetBlock(getBase()); return new TargetBlock(getBase());

View File

@@ -38,9 +38,9 @@ public class Settings implements IConf
return config.getInt("chat.radius", config.getInt("chat-radius", 0)); return config.getInt("chat.radius", config.getInt("chat-radius", 0));
} }
public long getTeleportDelay() public double getTeleportDelay()
{ {
return config.getInt("teleport-delay", 0) * 1000L; return config.getDouble("teleport-delay", 0);
} }
public int getDefaultStackSize() public int getDefaultStackSize()
@@ -134,14 +134,14 @@ public class Settings implements IConf
return config.getString("nickname-prefix", ""); return config.getString("nickname-prefix", "");
} }
public long getTeleportCooldown() public double getTeleportCooldown()
{ {
return ((Number)config.getInt("teleport-cooldown", 60)).longValue() * 1000L; return config.getDouble("teleport-cooldown", 60);
} }
public long getHealCooldown() public double getHealCooldown()
{ {
return ((Number)config.getInt("heal-cooldown", 60)).longValue() * 1000L; return config.getDouble("heal-cooldown", 60);
} }
public Object getKit(String name) public Object getKit(String name)

View File

@@ -0,0 +1,257 @@
package com.earth2me.essentials;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
public class Teleport implements Runnable
{
private static class Target
{
private Location location = null;
private Entity entity = null;
public Target(Location location)
{
this.location = location;
}
public Target(Entity entity)
{
this.entity = entity;
}
public Location getLocation()
{
if (this.entity != null)
{
return this.entity.getLocation();
}
return location;
}
}
User user;
private int teleTimer = -1;
private long started; // time this task was initiated
private long delay; // how long to delay the teleport
private int health;
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
private long initX;
private long initY;
private long initZ;
private Target teleportTarget;
private String chargeFor;
private Essentials ess;
private void initTimer(long delay, Target target, String chargeFor)
{
this.started = System.currentTimeMillis();
this.delay = delay;
this.health = user.getHealth();
this.initX = Math.round(user.getLocation().getX() * 10000);
this.initY = Math.round(user.getLocation().getY() * 10000);
this.initZ = Math.round(user.getLocation().getZ() * 10000);
this.teleportTarget = target;
this.chargeFor = chargeFor;
}
public void run()
{
if (user == null || !user.isOnline() || user.getLocation() == null)
{
cancel();
return;
}
if (Math.round(user.getLocation().getX() * 10000) != initX
|| Math.round(user.getLocation().getY() * 10000) != initY
|| Math.round(user.getLocation().getZ() * 10000) != initZ
|| user.getHealth() < health)
{ // user moved, cancel teleport
cancel(true);
return;
}
health = user.getHealth(); // in case user healed, then later gets injured
long now = System.currentTimeMillis();
if (now > started + delay)
{
try
{
cooldown(false);
user.sendMessage("§7Teleportation commencing...");
try
{
if (chargeFor != null)
{
user.charge(chargeFor);
}
now(teleportTarget);
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
catch (Exception ex)
{
user.sendMessage("§cCooldown: " + ex.getMessage());
}
}
}
public Teleport(User user, Essentials ess)
{
this.user = user;
this.ess = ess;
}
public void respawn(Spawn spawn, String chargeFor) throws Exception
{
teleport(new Target(spawn.getSpawn(user.getGroup())), chargeFor);
}
public void warp(String warp, String chargeFor) throws Exception
{
Location loc = Essentials.getWarps().getWarp(warp);
teleport(new Target(loc), chargeFor);
user.sendMessage("§7Warping to " + warp + ".");
}
public void cooldown(boolean check) throws Exception
{
Calendar now = new GregorianCalendar();
if (user.getLastTeleportTimestamp() > 0)
{
double cooldown = ess.getSettings().getTeleportCooldown();
Calendar cooldownTime = new GregorianCalendar();
cooldownTime.setTimeInMillis(user.getLastTeleportTimestamp());
cooldownTime.add(Calendar.SECOND, (int)cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !user.isAuthorized("essentials.teleport.cooldown.bypass"))
{
throw new Exception("Time before next teleport: " + Util.formatDateDiff(cooldownTime.getTimeInMillis()));
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
if (!check)
{
user.setLastTeleportTimestamp(now.getTimeInMillis());
}
}
public void cancel(boolean notifyUser)
{
if (teleTimer == -1)
{
return;
}
try
{
user.getServer().getScheduler().cancelTask(teleTimer);
if (notifyUser)
{
user.sendMessage("§cPending teleportation request cancelled.");
}
}
finally
{
teleTimer = -1;
}
}
public void cancel()
{
cancel(false);
}
public void teleport(Location loc, String name) throws Exception
{
teleport(new Target(loc), chargeFor);
}
public void teleport(Entity entity, String name) throws Exception
{
teleport(new Target(entity), chargeFor);
}
private void teleport(Target target, String chargeFor) throws Exception
{
double delay = ess.getSettings().getTeleportDelay();
cooldown(true);
if (delay <= 0 || user.isAuthorized("essentials.teleport.timer.bypass"))
{
if (chargeFor != null)
{
user.charge(chargeFor);
}
now(target);
return;
}
cancel();
Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
user.sendMessage("§7Teleportation will commence in " + Util.formatDateDiff(c.getTimeInMillis()) + ". Don't move.");
initTimer((long)(delay * 1000.0), target, chargeFor);
teleTimer = user.getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), this, 10, 10);
}
private void now(Target target) throws Exception
{
cancel();
user.setLastLocation();
user.getBase().teleport(Util.getSafeDestination(target.getLocation()));
}
public void now(Location loc) throws Exception
{
now(new Target(loc));
}
public void now(Entity entity) throws Exception
{
now(new Target(entity));
}
public void back(final String chargeFor) throws Exception
{
teleport(new Target(user.getLastLocation()), chargeFor);
}
public void back() throws Exception
{
back(null);
}
public void home(String chargeFor) throws Exception
{
home(user, chargeFor);
}
public void home(User user, String chargeFor) throws Exception
{
Location loc = user.getHome();
if (loc == null)
{
if (ess.getSettings().spawnIfNoHome())
{
respawn(Essentials.getSpawn(), chargeFor);
}
else
{
throw new Exception(user == this.user ? "You have not set a home." : "Player has not set a home.");
}
}
teleport(new Target(loc), chargeFor);
}
}

View File

@@ -1,73 +0,0 @@
package com.earth2me.essentials;
import java.util.TimerTask;
import java.util.Calendar;
public abstract class TeleportTimer implements Runnable
{
private long started; // time this task was initiated
private long delay; // how long to delay the teleport
public User user; // the person doing the teleport
private int health;
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
private long initX;
private long initY;
private long initZ;
public TeleportTimer(User tUser, long tDelay)
{
this.started = Calendar.getInstance().getTimeInMillis();
this.delay = tDelay;
this.user = tUser;
this.health = user.getHealth();
this.initX = Math.round(user.getLocation().getX() * 10000);
this.initY = Math.round(user.getLocation().getY() * 10000);
this.initZ = Math.round(user.getLocation().getZ() * 10000);
}
// This function needs to be defined when creating a new TeleportTimer
// The actual teleport command by itself should be stuck in there, such as teleportToNow(loc)
public abstract void DoTeleport();
public abstract void DoCancel();
public void run()
{
if (user == null || !user.isOnline() || user.getLocation() == null)
{
DoCancel();
return;
}
if (Math.round(user.getLocation().getX() * 10000) != initX
|| Math.round(user.getLocation().getY() * 10000) != initY
|| Math.round(user.getLocation().getZ() * 10000) != initZ
|| user.getHealth() < health)
{ // user moved, cancel teleport
user.cancelTeleport(true);
return;
}
health = user.getHealth(); // in case user healed, then later gets injured
long now = Calendar.getInstance().getTimeInMillis();
if (now > started + delay)
{
try
{
user.teleportCooldown(false);
user.sendMessage("§7Teleportation commencing...");
this.DoTeleport();
return;
}
catch (Exception ex)
{
user.sendMessage("§cCooldown: " + ex.getMessage());
}
}
//else // uncomment for timing debug
// user.sendMessage("§7" + (started + delay - now));
}
}

View File

@@ -1,97 +1,31 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import java.util.*;
import java.util.logging.*;
import java.io.*;
import org.bukkit.*;
import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.IEssentialsCommand;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.*; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class User extends PlayerExtension implements Comparable<User>, IReplyTo public class User extends UserData implements Comparable<User>, IReplyTo
{ {
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
private final Yaml yaml = new Yaml(new SafeConstructor());
private boolean isLoaded = false;
private final File folder;
private Map<String, Object> data = new HashMap<String, Object>();
private static Map<String, User> users = new HashMap<String, User>();
private boolean teleEnabled = true;
private long lastTeleport = 0;
private long lastHeal = 0;
private boolean justPortaled = false; private boolean justPortaled = false;
//private TimerTask teleTimer = null;
private int teleTimer = -1;
public Location lastLocation = null;
private CommandSender replyTo = null; private CommandSender replyTo = null;
private boolean isNew = false; private User teleportRequester;
public String currentJail; private boolean teleportRequestHere;
public ItemStack[] savedInventory; private Teleport teleport;
private Map<String,Object> metadata = new HashMap<String,Object>(); private long lastActivity;
private User(Player base) User(Player base, Essentials ess)
{ {
super(base); super(base, ess);
this.folder = new File((Essentials.getStatic() == null ? new File(".") : Essentials.getStatic().getDataFolder()), "userdata"); teleport = new Teleport(this, ess);
this.lastLocation = getBase().getLocation();
load();
} }
public static int size() User update(Player base)
{
return users.size();
}
public static <T> User get(T base)
{
if (base instanceof Player)
return get((Player)base);
return null;
}
public static <T extends Player> User get(T base)
{
if (base == null)
return null;
if (base instanceof User)
return (User)base;
if (users.containsKey(base.getName()))
return users.get(base.getName()).update(base);
User u = new User(base);
users.put(u.getName(), u);
return u;
}
public static <T> void charge(T base, IEssentialsCommand cmd) throws Exception
{
if (base instanceof Player)
User.get(base).charge(cmd);
}
public boolean isNew()
{
return isNew;
}
public void respawn(Spawn spawn) throws Exception
{
respawn(spawn, null);
}
public void respawn(Spawn spawn, final String chargeFor) throws Exception
{
teleportTo(getSafeDestination(spawn.getSpawn(getGroup())), chargeFor);
}
private User update(Player base)
{ {
setBase(base); setBase(base);
return this; return this;
@@ -105,10 +39,14 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public boolean isAuthorized(String node) public boolean isAuthorized(String node)
{ {
if (isOp()) if (isOp())
{
return true; return true;
}
if (isJailed()) if (isJailed())
{
return false; return false;
}
try try
{ {
@@ -117,204 +55,44 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
catch (Throwable ex) catch (Throwable ex)
{ {
String[] cmds = node.split("\\.", 2); String[] cmds = node.split("\\.", 2);
return !Essentials.getSettings().isCommandRestricted(cmds[cmds.length - 1]); return !ess.getSettings().isCommandRestricted(cmds[cmds.length - 1]);
} }
} }
public boolean isTeleEnabled()
{
return teleEnabled;
}
public boolean toggleTeleEnabled()
{
return teleEnabled = !teleEnabled;
}
public void teleportCooldown(boolean justCheck) throws Exception
{
long now = Calendar.getInstance().getTimeInMillis();
if (lastTeleport > 0)
{
long cooldown = Essentials.getSettings().getTeleportCooldown();
long left = lastTeleport + cooldown - now;
if (left > 0 && !isOp() && !isAuthorized("essentials.teleport.cooldown.bypass"))
{
throw new Exception("Time before next teleport: " + Essentials.FormatTime(left));
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
if (!justCheck) lastTeleport = now;
}
public void teleportCooldown() throws Exception
{
teleportCooldown(true);
}
public void healCooldown() throws Exception public void healCooldown() throws Exception
{ {
long now = Calendar.getInstance().getTimeInMillis(); Calendar now = new GregorianCalendar();
if (lastHeal > 0) if (getLastHealTimestamp() > 0)
{ {
long cooldown = Essentials.getSettings().getHealCooldown(); double cooldown = ess.getSettings().getHealCooldown();
long left = lastHeal + cooldown - now; Calendar cooldownTime = new GregorianCalendar();
if (left > 0 && !isOp() && !isAuthorized("essentials.heal.cooldown.bypass")) cooldownTime.setTimeInMillis(getLastHealTimestamp());
cooldownTime.add(Calendar.SECOND, (int)cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass"))
{ {
throw new Exception("Time before next heal: " + Essentials.FormatTime(left)); throw new Exception("Time before next heal: " + Util.formatDateDiff(cooldownTime.getTimeInMillis()));
} }
} }
lastHeal = now; setLastHealTimestamp(now.getTimeInMillis());
}
private void load()
{
if (isLoaded) return;
isLoaded = true;
data = Essentials.getData(this);
try
{
if (!folder.exists()) folder.mkdirs();
File file = new File(folder, getName() + ".yml");
if (!file.exists())
{
isNew = true;
file.createNewFile();
logger.info(getName() + " has logged in for the first time.");
}
FileInputStream rx = new FileInputStream(file);
Map<String, Object> userData = (Map<String, Object>)yaml.load(new UnicodeReader(rx));
if (userData != null) data.putAll(userData);
rx.close();
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, null, ex);
}
finally
{
if (data == null) data = new HashMap<String, Object>();
}
}
private void flush()
{
try
{
if (!folder.exists()) folder.mkdirs();
File file = new File(folder, getName() + ".yml");
if (!file.exists()) file.createNewFile();
FileWriter tx = new FileWriter(file);
tx.write(yaml.dump(data));
tx.flush();
tx.close();
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
public boolean isGodModeEnabled()
{
load();
return data.containsKey("godmode") && (Boolean)data.get("godmode");
}
public boolean toggleGodMode()
{
boolean retval = !isGodModeEnabled();
data.put("godmode", retval);
flush();
return retval;
}
public boolean isMuted()
{
load();
return data.containsKey("muted") && (Boolean)data.get("muted");
}
public boolean toggleMuted()
{
boolean retval = !isMuted();
data.put("muted", retval);
flush();
return retval;
}
public boolean isJailed()
{
//load(); Do not load config everytime time!
return data.containsKey("jailed") && (Boolean)data.get("jailed");
}
public boolean toggleJailed()
{
boolean retval = !isJailed();
data.put("jailed", retval);
flush();
load();
return retval;
}
public double getMoney()
{
load();
if (data.containsKey("money"))
{
if (data.get("money") instanceof Number)
{
return ((Number)data.get("money")).doubleValue();
}
logger.log(Level.SEVERE, "Can't convert money value to double:" + data.get("money"));
}
try
{
return com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).getBalance();
}
catch (Throwable ex)
{
try
{
Map<String, Object> idata = Essentials.getData(this);
return ((Number)idata.get("money")).doubleValue();
}
catch (Throwable ex2)
{
return Essentials.getSettings().getStartingBalance();
}
}
}
public void setMoney(double value)
{
try
{
com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value);
}
catch (Throwable ex)
{
data.put("money", value);
flush();
}
} }
public void giveMoney(double value) public void giveMoney(double value)
{ {
if (value == 0) return; if (value == 0)
{
return;
}
setMoney(getMoney() + value); setMoney(getMoney() + value);
sendMessage("§a$" + value + " has been added to your account."); sendMessage("§a$" + value + " has been added to your account.");
} }
public void payUser(User reciever, int value) throws Exception public void payUser(User reciever, double value) throws Exception
{ {
if (value == 0) return; if (value == 0)
{
return;
}
if (!canAfford(value)) if (!canAfford(value))
{ {
throw new Exception("You do not have sufficient funds."); throw new Exception("You do not have sufficient funds.");
@@ -330,7 +108,10 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public void takeMoney(double value) public void takeMoney(double value)
{ {
if (value == 0) return; if (value == 0)
{
return;
}
setMoney(getMoney() - value); setMoney(getMoney() - value);
sendMessage("§c$" + value + " has been taken from your account."); sendMessage("§c$" + value + " has been taken from your account.");
} }
@@ -343,24 +124,28 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
return; return;
} }
double mon = getMoney(); double mon = getMoney();
double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); double cost = ess.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isOp()) if (mon < cost && !isAuthorized("essentials.eco.loan"))
{
throw new Exception("You do not have sufficient funds."); throw new Exception("You do not have sufficient funds.");
}
takeMoney(cost); takeMoney(cost);
} }
public void canAfford(String cmd) throws Exception public void canAfford(String cmd) throws Exception
{ {
double mon = getMoney(); double mon = getMoney();
double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); double cost = ess.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isOp()) if (mon < cost && !isAuthorized("essentials.eco.loan"))
{
throw new Exception("You do not have sufficient funds."); throw new Exception("You do not have sufficient funds.");
} }
}
public boolean canAfford(double cost) public boolean canAfford(double cost)
{ {
double mon = getMoney(); double mon = getMoney();
if (mon < cost && !isOp()) if (mon < cost && !isAuthorized("essentials.eco.loan"))
{ {
return false; return false;
} }
@@ -375,312 +160,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
canAfford(cmd.getName()); canAfford(cmd.getName());
} }
public void cancelTeleport(boolean notifyUser)
{
if (teleTimer == -1) return;
try
{
getServer().getScheduler().cancelTask(teleTimer);
if (notifyUser) sendMessage("§cPending teleportation request cancelled.");
}
catch (Throwable ex)
{
}
finally
{
teleTimer = -1;
}
}
public void cancelTeleport()
{
cancelTeleport(false);
}
public void teleportTo(final Location loc, final String chargeFor)
{
final long delay = Essentials.getSettings().getTeleportDelay();
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(loc);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(loc);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
@Override
public void teleportTo(final Location loc)
{
teleportTo(loc, null);
}
public void teleportTo(final Entity entity, final String chargeFor)
{
final long delay = Essentials.getSettings().getTeleportDelay();
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(entity);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(entity);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
@Override
public void teleportTo(final Entity entity)
{
teleportTo(entity, null);
}
public Location getHome() throws Exception
{
return getHome(null);
}
public Location getHome(String playerName) throws Exception
{
Map<String, Object> userData = new HashMap<String, Object>();
if (playerName == null)
{
userData = data;
}
else
{
userData = Essentials.getData(playerName);
}
if (userData.containsKey("home"))
{
List<Object> vals = (List<Object>)userData.get("home");
World world = getServer() == null ? null : getServer().getWorlds().get(0);
if (vals.size() > 5 && getServer() != null)
{
world = getServer().getWorld((String)vals.get(5));
}
if (world == null)
{
throw new Exception();
}
return new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
}
try
{
Map<String, Object> gdata = null;
if (playerName != null)
{
gdata = Essentials.getData(playerName);
}
else
{
gdata = Essentials.getData(this);
}
List<Object> vals = (List<Object>)gdata.get("home");
World world = getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = getServer().getWorld((String)vals.get(5));
}
if (world == null)
{
throw new Exception();
}
return new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
}
catch (Throwable ex)
{
throw new Exception("You have not set a home.");
}
}
public void teleportToHome(final String chargeFor)
{
teleportToHome(chargeFor, null);
}
public void teleportToHome(final String chargeFor, String otherPlayer)
{
final long delay = Essentials.getSettings().getTeleportDelay();
Location loc = null;
try
{// check this first in case user hasn't set a home yet
if (otherPlayer == null)
{
loc = getHome();
}
else
{
loc = getHome(otherPlayer);
}
}
catch (Throwable ex)
{
if (Essentials.getSettings().spawnIfNoHome())
{
try
{
respawn(Essentials.getStatic().spawn, null);
return;
}
catch (Throwable rex)
{
sendMessage("§cTeleport: " + rex.getMessage());
return;
}
}
sendMessage("§cTeleport: " + ex.getMessage());
return;
}
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(loc);
sendMessage("§7Teleporting home...");
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in "
+ Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(getHome());
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
public void teleportToHome()
{
teleportToHome(null);
}
public void teleportToNow(Location loc) throws Exception
{
cancelTeleport();
lastLocation = getLocation();
getBase().teleport(getSafeDestination(loc));
}
public void teleportToNow(Entity entity)
{
cancelTeleport();
lastLocation = getLocation();
getBase().teleport(entity);
}
public void teleportBack(final String chargeFor)
{
teleportTo(lastLocation, chargeFor);
}
public void teleportBack()
{
teleportBack(null);
}
public void dispose() public void dispose()
{ {
this.base = new OfflinePlayer(getName()); this.base = new OfflinePlayer(getName());
@@ -694,9 +173,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public boolean getJustPortaled() public boolean getJustPortaled()
{ {
return justPortaled; return justPortaled;
} }
public void setJustPortaled(boolean value) public void setJustPortaled(boolean value)
@@ -714,53 +190,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
return replyTo; return replyTo;
} }
public void setHome()
{
setHome(getLocation());
}
public void setHome(Location home)
{
List<Object> vals = new ArrayList<Object>(6);
vals.add(new Double(home.getX()));
vals.add(new Double(home.getY()));
vals.add(new Double(home.getZ()));
vals.add(new Double(home.getYaw()));
vals.add(new Double(home.getPitch()));
vals.add(home.getWorld() == null ? "world" : home.getWorld().getName());
data.put("home", vals);
flush();
setCompassTarget(home);
}
public String getNick()
{
Essentials ess = Essentials.getStatic();
String name = Essentials.getSettings().isCommandDisabled("nick") ? getName() : ess.readNickname(this);
if (isOp() && ess.getConfiguration().getString("ops-name-color", "c").matches("^[0-9a-f]$"))
name = "§" + ess.getConfiguration().getString("ops-name-color", "c") + name + "§f";
return name;
}
public void warpTo(String warp, final String chargeFor) throws Exception
{
lastLocation = getLocation();
Location loc = Essentials.getWarps().getWarp(warp);
teleportTo(loc, chargeFor);
sendMessage("§7Warping to " + warp + ".");
}
public void warpTo(String string) throws Exception
{
warpTo(string, null);
}
public void clearNewFlag()
{
isNew = false;
}
public int compareTo(User t) public int compareTo(User t)
{ {
return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName())); return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName()));
@@ -768,75 +197,70 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public Boolean canSpawnItem(int itemId) public Boolean canSpawnItem(int itemId)
{ {
return !Essentials.getSettings().itemSpawnBlacklist().contains(itemId); return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
} }
@SuppressWarnings("unchecked") public void setHome()
public List<Integer> getUnlimited()
{ {
if (!data.containsKey("unlimited")) setHome(getLocation(), true);
{
return new ArrayList<Integer>();
}
return (List<Integer>)data.get("unlimited");
} }
public boolean hasUnlimited(ItemStack stack) public void setHome(boolean defaultHome)
{ {
return getUnlimited().contains(stack.getTypeId()); setHome(getLocation(), defaultHome);
} }
@SuppressWarnings("unchecked") public void setLastLocation()
public void setUnlimited(ItemStack stack, boolean state)
{ {
List<Integer> items = getUnlimited(); setLastLocation(getLocation());
if (items.contains(stack.getTypeId()))
{
items.remove(Integer.valueOf(stack.getTypeId()));
}
if (state)
{
items.add(stack.getTypeId());
}
data.put("unlimited", items);
flush();
} }
public String getPowertool(ItemStack stack) public void requestTeleport(User player, boolean here)
{ {
if (!data.containsKey("powertools")) teleportRequester = player;
{ teleportRequestHere = here;
return null;
}
@SuppressWarnings("unchecked")
Map<Integer, String> tools = (Map<Integer, String>)data.get("powertools");
return tools.get(stack.getTypeId());
} }
public void setPowertool(ItemStack stack, String command) public User getTeleportRequest()
{ {
Map<Integer, String> tools = new HashMap<Integer, String>(); return teleportRequester;
if (data.containsKey("powertools"))
{
tools = (Map<Integer, String>)data.get("powertools");
} }
if (command == null || command.trim().isEmpty())
public boolean isTeleportRequestHere()
{ {
tools.remove(Integer.valueOf(stack.getTypeId())); return teleportRequestHere;
}
public String getNick()
{
String nickname = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nickname == null || nickname.isEmpty() || nickname.equals(getName()))
{
nickname = getName();
} }
else else
{ {
tools.put(Integer.valueOf(stack.getTypeId()), command.trim()); nickname = ess.getSettings().getNicknamePrefix() + nickname;
} }
data.put("powertools", tools); if (isOp())
flush(); {
nickname = ess.getSettings().getOperatorColor().toString() + nickname + "§f";
}
return nickname;
} }
public Map<String,Object> getMetadata() { public Teleport getTeleport()
return metadata; {
return teleport;
} }
public void setMetadata(String key, Object value) { public long getLastActivity()
metadata.put(key, value); {
return lastActivity;
}
public void setLastActivity(long timestamp)
{
lastActivity = timestamp;
} }
} }

View File

@@ -13,23 +13,29 @@ import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public abstract class UserData extends PlayerExtension implements IConf {
public abstract class UserData extends PlayerExtension implements IConf
{
private EssentialsConf config; private EssentialsConf config;
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
protected Essentials ess;
protected UserData(Player base, File folder) { protected UserData(Player base, Essentials ess)
{
super(base); super(base);
folder = new File(folder, "userdata"); this.ess = ess;
if (!folder.exists()) { File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs(); folder.mkdirs();
} }
config = new EssentialsConf(new File(folder, base.getName()+".yml")); config = new EssentialsConf(new File(folder, Util.sanitizeFileName(base.getName()) + ".yml"));
reloadConfig(); reloadConfig();
} }
public final void reloadConfig() { public final void reloadConfig()
{
config.load(); config.load();
updateConfig();
unlimited = _getUnlimited(); unlimited = _getUnlimited();
powertools = getPowertools(); powertools = getPowertools();
lastLocation = _getLastLocation(); lastLocation = _getLastLocation();
@@ -47,12 +53,15 @@ public abstract class UserData extends PlayerExtension implements IConf {
jailTimeout = _getJailTimeout(); jailTimeout = _getJailTimeout();
lastLogin = _getLastLogin(); lastLogin = _getLastLogin();
lastLogout = _getLastLogout(); lastLogout = _getLastLogout();
afk = getAfk();
geolocation = _getGeoLocation();
} }
public double getMoney() { public double getMoney()
{
if (config.hasProperty("money")) if (config.hasProperty("money"))
{ {
return config.getDouble("money", Essentials.getSettings().getStartingBalance()); return config.getDouble("money", ess.getSettings().getStartingBalance());
} }
try try
@@ -61,11 +70,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
} }
catch (Throwable ex) catch (Throwable ex)
{ {
return Essentials.getSettings().getStartingBalance(); return ess.getSettings().getStartingBalance();
} }
} }
public void setMoney(double value) { public void setMoney(double value)
{
try try
{ {
com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value); com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value);
@@ -77,446 +87,572 @@ public abstract class UserData extends PlayerExtension implements IConf {
} }
} }
public Location getHome() throws Exception { public Location getHome()
{
if (config.hasProperty("home")) if (config.hasProperty("home"))
{ {
World world = getLocation().getWorld(); World world = getLocation().getWorld();
String worldHome = "home.worlds." + world.getName().toLowerCase(); String worldHome = "home.worlds." + world.getName().toLowerCase();
if (!config.hasProperty(worldHome)) { if (!config.hasProperty(worldHome))
{
String defaultWorld = config.getString("home.default"); String defaultWorld = config.getString("home.default");
worldHome = "home.worlds." + defaultWorld; worldHome = "home.worlds." + defaultWorld;
} }
Location loc = config.getLocation(worldHome, getServer()); Location loc = config.getLocation(worldHome, getServer());
if (loc == null) {
throw new Exception();
}
return loc; return loc;
} else {
throw new Exception("You have not set a home.");
} }
return null;
} }
public void setHome(Location loc, boolean b) { public void setHome(Location loc, boolean b)
{
String worldName = loc.getWorld().getName().toLowerCase(); String worldName = loc.getWorld().getName().toLowerCase();
if (worldName == null || worldName.isEmpty()) { if (worldName == null || worldName.isEmpty())
{
logger.log(Level.WARNING, "Set Home: World name is null or empty."); logger.log(Level.WARNING, "Set Home: World name is null or empty.");
return; return;
} }
if (b) { if (b || !config.hasProperty("home.default"))
{
config.setProperty("home.default", worldName); config.setProperty("home.default", worldName);
} }
config.setProperty("home.worlds."+worldName, loc); config.setProperty("home.worlds." + worldName, loc);
config.save(); config.save();
} }
public String getNickname() { public String getNickname()
{
return config.getString("nickname"); return config.getString("nickname");
} }
public void setNickname(String nick) { public void setNickname(String nick)
{
config.setProperty("nickname", nick); config.setProperty("nickname", nick);
config.save(); config.save();
} }
private List<Integer> unlimited; private List<Integer> unlimited;
private List<Integer> _getUnlimited() { private List<Integer> _getUnlimited()
{
return config.getIntList("unlimited", new ArrayList<Integer>()); return config.getIntList("unlimited", new ArrayList<Integer>());
} }
public List<Integer> getUnlimited() { public List<Integer> getUnlimited()
{
return unlimited; return unlimited;
} }
public boolean hasUnlimited(ItemStack stack) { public boolean hasUnlimited(ItemStack stack)
{
return unlimited.contains(stack.getTypeId()); return unlimited.contains(stack.getTypeId());
} }
public void setUnlimited(ItemStack stack, boolean state) { public void setUnlimited(ItemStack stack, boolean state)
if (unlimited.contains(stack.getTypeId())) { {
if (unlimited.contains(stack.getTypeId()))
{
unlimited.remove(Integer.valueOf(stack.getTypeId())); unlimited.remove(Integer.valueOf(stack.getTypeId()));
} }
if (state) { if (state)
{
unlimited.add(stack.getTypeId()); unlimited.add(stack.getTypeId());
} }
config.setProperty("unlimited", unlimited); config.setProperty("unlimited", unlimited);
config.save(); config.save();
} }
private Map<Integer, String> powertools; private Map<Integer, String> powertools;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<Integer, String> getPowertools() { private Map<Integer, String> getPowertools()
{
Object o = config.getProperty("powertools"); Object o = config.getProperty("powertools");
if (o != null && o instanceof Map) { if (o != null && o instanceof Map)
{
return (Map<Integer, String>)o; return (Map<Integer, String>)o;
} else { }
else
{
return new HashMap<Integer, String>(); return new HashMap<Integer, String>();
} }
} }
public String getPowertool(ItemStack stack) { public String getPowertool(ItemStack stack)
{
return powertools.get(stack.getTypeId()); return powertools.get(stack.getTypeId());
} }
public void setPowertool(ItemStack stack, String command) { public void setPowertool(ItemStack stack, String command)
if (command == null || command.isEmpty()) { {
if (command == null || command.isEmpty())
{
powertools.remove(stack.getTypeId()); powertools.remove(stack.getTypeId());
} else { }
else
{
powertools.put(stack.getTypeId(), command); powertools.put(stack.getTypeId(), command);
} }
config.setProperty("powertools", powertools); config.setProperty("powertools", powertools);
config.save(); config.save();
} }
private Location lastLocation; private Location lastLocation;
private Location _getLastLocation() { private Location _getLastLocation()
{
return config.getLocation("lastlocation", getServer()); return config.getLocation("lastlocation", getServer());
} }
public Location getLastLocation() { public Location getLastLocation()
{
return lastLocation; return lastLocation;
} }
public void setLastLocation(Location loc) { public void setLastLocation(Location loc)
{
lastLocation = loc; lastLocation = loc;
config.setProperty("lastlocation", loc); config.setProperty("lastlocation", loc);
config.save(); config.save();
} }
private long lastTeleportTimestamp; private long lastTeleportTimestamp;
private long _getLastTeleportTimestamp() { private long _getLastTeleportTimestamp()
{
return config.getLong("timestamps.lastteleport", 0); return config.getLong("timestamps.lastteleport", 0);
} }
public long getLastTeleportTimestamp() { public long getLastTeleportTimestamp()
{
return lastTeleportTimestamp; return lastTeleportTimestamp;
} }
public void setLastTeleportTimestamp(long time) { public void setLastTeleportTimestamp(long time)
{
lastTeleportTimestamp = time; lastTeleportTimestamp = time;
config.setProperty("timestamps.lastteleport", time); config.setProperty("timestamps.lastteleport", time);
config.save(); config.save();
} }
private long lastHealTimestamp; private long lastHealTimestamp;
private long _getLastHealTimestamp() { private long _getLastHealTimestamp()
{
return config.getLong("timestamps.lastheal", 0); return config.getLong("timestamps.lastheal", 0);
} }
public long getLastHealTimestamp() { public long getLastHealTimestamp()
{
return lastHealTimestamp; return lastHealTimestamp;
} }
public void setLastHealTimestamp(long time) { public void setLastHealTimestamp(long time)
{
lastHealTimestamp = time; lastHealTimestamp = time;
config.setProperty("timestamps.lastheal", time); config.setProperty("timestamps.lastheal", time);
config.save(); config.save();
} }
private String jail; private String jail;
private String _getJail() { private String _getJail()
{
return config.getString("jail"); return config.getString("jail");
} }
public String getJail() { public String getJail()
{
return jail; return jail;
} }
public void setJail(String jail) { public void setJail(String jail)
if (jail == null || jail.isEmpty()) { {
if (jail == null || jail.isEmpty())
{
this.jail = null; this.jail = null;
config.removeProperty("jail"); config.removeProperty("jail");
} else { }
else
{
this.jail = jail; this.jail = jail;
config.setProperty("jail", jail); config.setProperty("jail", jail);
} }
config.save(); config.save();
} }
private List<String> mails; private List<String> mails;
private List<String> _getMails() { private List<String> _getMails()
{
return config.getStringList("mail", new ArrayList<String>()); return config.getStringList("mail", new ArrayList<String>());
} }
public List<String> getMails() { public List<String> getMails()
{
return mails; return mails;
} }
public void setMails(List<String> mails) { public void setMails(List<String> mails)
if (mails == null) { {
if (mails == null)
{
config.removeProperty("mail"); config.removeProperty("mail");
} else { }
else
{
config.setProperty("mail", mails); config.setProperty("mail", mails);
} }
this.mails = mails; this.mails = mails;
config.save(); config.save();
} }
public void addMail(String mail) { public void addMail(String mail)
{
mails.add(mail); mails.add(mail);
setMails(mails); setMails(mails);
} }
private ItemStack[] savedInventory; private ItemStack[] savedInventory;
public ItemStack[] getSavedInventory() { public ItemStack[] getSavedInventory()
{
return savedInventory; return savedInventory;
} }
private ItemStack[] _getSavedInventory() { private ItemStack[] _getSavedInventory()
{
int size = config.getInt("inventory.size", 0); int size = config.getInt("inventory.size", 0);
if (size < 1 || size > getInventory().getSize()) { if (size < 1 || size > getInventory().getSize())
{
return null; return null;
} }
ItemStack[] is = new ItemStack[size]; ItemStack[] is = new ItemStack[size];
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++)
is[i] = config.getItemStack("inventory."+i); {
is[i] = config.getItemStack("inventory." + i);
} }
return is; return is;
} }
public void setSavedInventory(ItemStack[] is) { public void setSavedInventory(ItemStack[] is)
if (is == null || is.length == 0) { {
if (is == null || is.length == 0)
{
savedInventory = null; savedInventory = null;
config.removeProperty("inventory"); config.removeProperty("inventory");
} else { }
else
{
savedInventory = is; savedInventory = is;
config.setProperty("inventory.size", is.length); config.setProperty("inventory.size", is.length);
for (int i = 0; i < is.length; i++) { for (int i = 0; i < is.length; i++)
if (is[i] == null || is[i].getType() == Material.AIR) { {
if (is[i] == null || is[i].getType() == Material.AIR)
{
continue; continue;
} }
config.setProperty("inventory."+i, is[i]); config.setProperty("inventory." + i, is[i]);
} }
} }
config.save();
} }
private boolean teleportEnabled; private boolean teleportEnabled;
private boolean getTeleportEnabled() { private boolean getTeleportEnabled()
{
return config.getBoolean("teleportenabled", true); return config.getBoolean("teleportenabled", true);
} }
public boolean isTeleportEnabled() { public boolean isTeleportEnabled()
{
return teleportEnabled; return teleportEnabled;
} }
public void setTeleportEnabled(boolean set) { public void setTeleportEnabled(boolean set)
{
teleportEnabled = set; teleportEnabled = set;
config.setProperty("teleportenabled", set); config.setProperty("teleportenabled", set);
config.save(); config.save();
} }
public boolean toggleTeleportEnabled() { public boolean toggleTeleportEnabled()
{
boolean ret = !isTeleportEnabled(); boolean ret = !isTeleportEnabled();
setTeleportEnabled(ret); setTeleportEnabled(ret);
return ret; return ret;
} }
private List<String> ignoredPlayers; private List<String> ignoredPlayers;
public List<String> getIgnoredPlayers() { public List<String> getIgnoredPlayers()
{
return config.getStringList("ignore", new ArrayList<String>()); return config.getStringList("ignore", new ArrayList<String>());
} }
public void setIgnoredPlayers(List<String> players) { public void setIgnoredPlayers(List<String> players)
if (players == null || players.isEmpty()) { {
if (players == null || players.isEmpty())
{
ignoredPlayers = new ArrayList<String>(); ignoredPlayers = new ArrayList<String>();
config.removeProperty("ignore"); config.removeProperty("ignore");
} else { }
else
{
ignoredPlayers = players; ignoredPlayers = players;
config.setProperty("ignore", players); config.setProperty("ignore", players);
} }
config.save(); config.save();
} }
public boolean isIgnoredPlayer(String name) { public boolean isIgnoredPlayer(String name)
{
return ignoredPlayers.contains(name); return ignoredPlayers.contains(name);
} }
public void setIgnoredPlayer(String name, boolean set) { public void setIgnoredPlayer(String name, boolean set)
if (set) { {
if (set)
{
ignoredPlayers.add(name); ignoredPlayers.add(name);
} else { }
else
{
ignoredPlayers.remove(name); ignoredPlayers.remove(name);
} }
setIgnoredPlayers(ignoredPlayers); setIgnoredPlayers(ignoredPlayers);
} }
private boolean godmode; private boolean godmode;
private boolean getGodModeEnabled() { private boolean getGodModeEnabled()
return config.getBoolean("godmode", true); {
return config.getBoolean("godmode", false);
} }
public boolean isGodModeEnabled() { public boolean isGodModeEnabled()
{
return godmode; return godmode;
} }
public void setGodModeEnabled(boolean set) { public void setGodModeEnabled(boolean set)
{
godmode = set; godmode = set;
config.setProperty("godmode", set); config.setProperty("godmode", set);
config.save(); config.save();
} }
public boolean toggleGodModeEnabled() { public boolean toggleGodModeEnabled()
{
boolean ret = !isGodModeEnabled(); boolean ret = !isGodModeEnabled();
setGodModeEnabled(ret); setGodModeEnabled(ret);
return ret; return ret;
} }
private boolean muted; private boolean muted;
private boolean getMuted() { private boolean getMuted()
return config.getBoolean("muted", true); {
return config.getBoolean("muted", false);
} }
public boolean isMuted() { public boolean isMuted()
{
return muted; return muted;
} }
public void setMuted(boolean set) { public void setMuted(boolean set)
{
muted = set; muted = set;
config.setProperty("muted", set); config.setProperty("muted", set);
config.save(); config.save();
} }
public boolean toggleMuted() { public boolean toggleMuted()
{
boolean ret = !isMuted(); boolean ret = !isMuted();
setMuted(ret); setMuted(ret);
return ret; return ret;
} }
private long muteTimeout; private long muteTimeout;
private long _getMuteTimeout() { private long _getMuteTimeout()
{
return config.getLong("timestamps.mute", 0); return config.getLong("timestamps.mute", 0);
} }
public long getMuteTimeout() { public long getMuteTimeout()
{
return muteTimeout; return muteTimeout;
} }
public void setMuteTimeout(long time) { public void setMuteTimeout(long time)
{
muteTimeout = time; muteTimeout = time;
config.setProperty("timestamps.mute", time); config.setProperty("timestamps.mute", time);
config.save(); config.save();
} }
private boolean jailed; private boolean jailed;
private boolean getJailed() { private boolean getJailed()
return config.getBoolean("jailed", true); {
return config.getBoolean("jailed", false);
} }
public boolean isJailed() { public boolean isJailed()
{
return jailed; return jailed;
} }
public void setJailed(boolean set) { public void setJailed(boolean set)
{
jailed = set; jailed = set;
config.setProperty("jailed", set); config.setProperty("jailed", set);
config.save(); config.save();
} }
public boolean toggleJailed() { public boolean toggleJailed()
{
boolean ret = !isJailed(); boolean ret = !isJailed();
setJailed(ret); setJailed(ret);
return ret; return ret;
} }
private long jailTimeout; private long jailTimeout;
private long _getJailTimeout() { private long _getJailTimeout()
{
return config.getLong("timestamps.jail", 0); return config.getLong("timestamps.jail", 0);
} }
public long getJailTimeout() { public long getJailTimeout()
{
return jailTimeout; return jailTimeout;
} }
public void setJailTimeout(long time) { public void setJailTimeout(long time)
{
jailTimeout = time; jailTimeout = time;
config.setProperty("timestamps.jail", time); config.setProperty("timestamps.jail", time);
config.save(); config.save();
} }
public String getBanReason()
public String getBanReason() { {
return config.getString("ban.reason"); return config.getString("ban.reason");
} }
public void setBanReason(String reason) { public void setBanReason(String reason)
{
config.setProperty("ban.reason", reason); config.setProperty("ban.reason", reason);
config.save(); config.save();
} }
public long getBanTimeout() { public long getBanTimeout()
{
return config.getLong("ban.timeout", 0); return config.getLong("ban.timeout", 0);
} }
public void setBanTimeout(long time) { public void setBanTimeout(long time)
{
config.setProperty("ban.timeout", time); config.setProperty("ban.timeout", time);
config.save(); config.save();
} }
private long lastLogin; private long lastLogin;
private long _getLastLogin() { private long _getLastLogin()
{
return config.getLong("timestamps.login", 0); return config.getLong("timestamps.login", 0);
} }
public long getLastLogin() { public long getLastLogin()
{
return lastLogin; return lastLogin;
} }
public void setLastLogin(long time) { public void setLastLogin(long time)
{
lastLogin = time; lastLogin = time;
config.setProperty("timestamps.login", time); config.setProperty("timestamps.login", time);
config.save(); config.save();
} }
private long lastLogout; private long lastLogout;
private long _getLastLogout() { private long _getLastLogout()
{
return config.getLong("timestamps.logout", 0); return config.getLong("timestamps.logout", 0);
} }
public long getLastLogout() { public long getLastLogout()
{
return lastLogout; return lastLogout;
} }
public void setLastLogout(long time) { public void setLastLogout(long time)
{
lastLogout = time; lastLogout = time;
config.setProperty("timestamps.logout", time); config.setProperty("timestamps.logout", time);
config.save(); config.save();
} }
private boolean afk;
private void updateConfig() { private boolean getAfk()
if (config.hasProperty("home") && !config.hasProperty("home.default")) { {
@SuppressWarnings("unchecked") return config.getBoolean("afk", false);
List<Object> vals = (List<Object>)config.getProperty("home");
World world = getServer() == null ? null : getServer().getWorlds().get(0);
if (vals.size() > 5 && getServer() != null) {
world = getServer().getWorld((String)vals.get(5));
} }
Location loc = new Location(
world, public boolean isAfk()
((Number)vals.get(0)).doubleValue(), {
((Number)vals.get(1)).doubleValue(), return afk;
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
config.removeProperty("home");
setHome(loc, true);
} }
public void setAfk(boolean set)
{
afk = set;
config.setProperty("afk", set);
config.save();
}
public boolean toggleAfk()
{
boolean ret = !isAfk();
setAfk(ret);
return ret;
}
private boolean newplayer;
private boolean getNew()
{
return config.getBoolean("newplayer", true);
}
public boolean isNew()
{
return newplayer;
}
public void setNew(boolean set)
{
newplayer = set;
config.setProperty("newplayer", set);
config.save();
}
private String geolocation;
private String _getGeoLocation()
{
return config.getString("geolocation");
}
public String getGeoLocation()
{
return geolocation;
}
public void setGeoLocation(String geolocation)
{
if (geolocation == null || geolocation.isEmpty())
{
this.geolocation = null;
config.removeProperty("geolocation");
}
else
{
this.geolocation = geolocation;
config.setProperty("geolocation", geolocation);
}
config.save();
} }
} }

View File

@@ -0,0 +1,259 @@
package com.earth2me.essentials;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
public class Util
{
public static String sanitizeFileName(String name)
{
return name.toLowerCase().replaceAll("[^a-z0-9]", "_");
}
public static String formatDateDiff(long date)
{
Calendar c = new GregorianCalendar();
c.setTimeInMillis(date);
Calendar now = new GregorianCalendar();
return Util.formatDateDiff(now, c);
}
public static String formatDateDiff(Calendar fromDate, Calendar toDate)
{
boolean future = false;
if (toDate.equals(fromDate))
{
return "now";
}
if (toDate.after(fromDate))
{
future = true;
}
StringBuilder sb = new StringBuilder();
int[] types = new int[]
{
Calendar.YEAR,
Calendar.MONTH,
Calendar.DAY_OF_MONTH,
Calendar.HOUR_OF_DAY,
Calendar.MINUTE,
Calendar.SECOND
};
String[] names = new String[]
{
"year",
"month",
"day",
"hour",
"minute",
"second"
};
for (int i = 0; i < types.length; i++)
{
int diff = dateDiff(types[i], fromDate, toDate, future);
if (diff > 0)
{
sb.append(" ").append(diff).append(" ").append(names[i]);
if (diff > 1)
{
sb.append("s");
}
}
}
if (sb.length() == 0)
{
return "now";
}
return sb.toString();
}
private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
{
int diff = 0;
while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate)))
{
fromDate.add(type, future ? 1 : -1);
diff++;
}
diff--;
fromDate.add(type, future ? -1 : 1);
return diff;
}
private static Pattern timePattern = Pattern.compile(
"(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*s[a-z]*)?", Pattern.CASE_INSENSITIVE);
public static long parseDateDiff(String time, boolean future) throws Exception
{
Matcher m = timePattern.matcher(time);
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
boolean found = false;
while (m.find())
{
if (m.group() == null || m.group().isEmpty())
{
continue;
}
for (int i = 0; i < m.groupCount(); i++)
{
if (m.group(i) != null && !m.group(i).isEmpty())
{
found = true;
break;
}
}
if (found)
{
if (m.group(1) != null && !m.group(1).isEmpty())
{
years = Integer.parseInt(m.group(1));
}
if (m.group(2) != null && !m.group(2).isEmpty())
{
months = Integer.parseInt(m.group(2));
}
if (m.group(3) != null && !m.group(3).isEmpty())
{
weeks = Integer.parseInt(m.group(3));
}
if (m.group(4) != null && !m.group(4).isEmpty())
{
days = Integer.parseInt(m.group(4));
}
if (m.group(5) != null && !m.group(5).isEmpty())
{
hours = Integer.parseInt(m.group(5));
}
if (m.group(6) != null && !m.group(6).isEmpty())
{
minutes = Integer.parseInt(m.group(6));
}
if (m.group(7) != null && !m.group(7).isEmpty())
{
seconds = Integer.parseInt(m.group(7));
}
break;
}
}
if (!found)
{
throw new Exception("Illegal date format.");
}
Calendar c = new GregorianCalendar();
if (years > 0)
{
c.add(Calendar.YEAR, years * (future ? 1 : -1));
}
if (months > 0)
{
c.add(Calendar.MONTH, months * (future ? 1 : -1));
}
if (weeks > 0)
{
c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1));
}
if (days > 0)
{
c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1));
}
if (hours > 0)
{
c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
}
if (minutes > 0)
{
c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
}
if (seconds > 0)
{
c.add(Calendar.SECOND, seconds * (future ? 1 : -1));
}
return c.getTimeInMillis();
}
public static Location getSafeDestination(Location loc) throws Exception
{
if (loc == null)
{
throw new Exception("Destination not set");
}
World world = loc.getWorld();
double x = Math.floor(loc.getX()) + 0.5;
double y = Math.floor(loc.getY());
double z = Math.floor(loc.getZ()) + 0.5;
while (isBlockAboveAir(world, x, y, z))
{
y -= 1.0D;
if (y < 0.0D)
{
throw new Exception("Hole in floor");
}
}
while (isBlockUnsafe(world, x, y, z))
{
y += 1.0D;
if (y >= 110.0D)
{
x += 1.0D;
break;
}
}
while (isBlockUnsafe(world, x, y, z))
{
y -= 1.0D;
if (y <= 1.0D)
{
y = 110.0D;
x += 1.0D;
}
}
return new Location(world, x, y, z, loc.getYaw(), loc.getPitch());
}
private static boolean isBlockAboveAir(World world, double x, double y, double z)
{
return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR;
}
public static boolean isBlockUnsafe(World world, double x, double y, double z)
{
Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z));
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
{
return true;
}
if (below.getType() == Material.FIRE)
{
return true;
}
if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR))
{
return true;
}
return isBlockAboveAir(world, x, y, z);
}
}

View File

@@ -1,215 +1,109 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World;
public class Warps implements IConf {
public class Warps implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>(); Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>();
File warpsFolder; File warpsFolder;
Server server; Server server;
public Warps(Server server, File dataFolder) { public Warps(Server server, File dataFolder)
{
this.server = server; this.server = server;
warpsFolder = new File(dataFolder, "warps"); warpsFolder = new File(dataFolder, "warps");
if (!warpsFolder.exists()) { if (!warpsFolder.exists())
{
warpsFolder.mkdirs(); warpsFolder.mkdirs();
} else {
convertWarps(dataFolder);
} }
reloadConfig(); reloadConfig();
} }
private String convertToFileName(String name) { public boolean isEmpty()
return name.toLowerCase().replaceAll("[^a-z0-9]", "_"); {
}
public boolean isEmpty() {
return warpPoints.isEmpty(); return warpPoints.isEmpty();
} }
public Iterable<String> getWarpNames() { public Iterable<String> getWarpNames()
{
List<String> keys = new ArrayList<String>(); List<String> keys = new ArrayList<String>();
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet())
{
keys.add(stringIgnoreCase.string); keys.add(stringIgnoreCase.string);
} }
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
return keys; return keys;
} }
public Location getWarp(String warp) throws Exception { public Location getWarp(String warp) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null) { if (conf == null)
{
throw new Exception("That warp does not exist."); throw new Exception("That warp does not exist.");
} }
double x = conf.getDouble("x", 0); return conf.getLocation(null, server);
double y = conf.getDouble("y", 0);
double z = conf.getDouble("z", 0);
float yaw = (float) conf.getDouble("yaw", 0);
float pitch = (float) conf.getDouble("pitch", 0);
String world = conf.getString("world");
World w = server.getWorld(world);
if (w == null) {
throw new Exception("World of warp does not exist.");
}
return new Location(w, x, y, z, yaw, pitch);
} }
public void setWarp(String name, Location loc) throws Exception { public void setWarp(String name, Location loc) throws Exception
setWarp(name, loc, null); {
} String filename = Util.sanitizeFileName(name);
private void setWarp(String name, Location loc, String worldName) throws Exception {
String filename = convertToFileName(name);
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) { if (conf == null)
{
File confFile = new File(warpsFolder, filename + ".yml"); File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists()) { if (confFile.exists())
{
throw new Exception("A warp with a similar name already exists."); throw new Exception("A warp with a similar name already exists.");
} }
conf = new EssentialsConf(confFile); conf = new EssentialsConf(confFile);
conf.setProperty("name", name);
warpPoints.put(new StringIgnoreCase(name), conf); warpPoints.put(new StringIgnoreCase(name), conf);
} }
conf.setProperty("x", loc.getBlockX()); conf.setProperty(null, loc);
conf.setProperty("y", loc.getBlockY()); conf.setProperty("name", name);
conf.setProperty("z", loc.getBlockZ());
conf.setProperty("yaw", loc.getYaw());
conf.setProperty("pitch", loc.getPitch());
if (worldName != null) {
conf.setProperty("world", worldName);
} else {
conf.setProperty("world", loc.getWorld().getName());
}
conf.save(); conf.save();
} }
public void delWarp(String name) throws Exception { public void delWarp(String name) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) { if (conf == null)
{
throw new Exception("Warp does not exist."); throw new Exception("Warp does not exist.");
} }
if (!conf.getFile().delete()) { if (!conf.getFile().delete())
{
throw new Exception("Problem deleting the warp file."); throw new Exception("Problem deleting the warp file.");
} }
warpPoints.remove(new StringIgnoreCase(name)); warpPoints.remove(new StringIgnoreCase(name));
} }
private void convertWarps(File dataFolder) { public final void reloadConfig()
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1) {
for (int i = 0; i < listOfFiles.length; i++) {
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".dat")) {
try {
BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x = Double.parseDouble(rx.readLine().trim());
double y = Double.parseDouble(rx.readLine().trim());
double z = Double.parseDouble(rx.readLine().trim());
float yaw = Float.parseFloat(rx.readLine().trim());
float pitch = Float.parseFloat(rx.readLine().trim());
String worldName = rx.readLine();
rx.close();
World w = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() != World.Environment.NETHER) {
w = world;
break;
}
}
boolean forceWorldName = false;
if (worldName != null) {
worldName.trim();
World w1 = null;
for (World world : server.getWorlds()) {
if (world.getName().equalsIgnoreCase(worldName)) {
w1 = world;
break;
}
}
if (w1 != null) {
w = w1;
} else {
File worldFolder = new File(dataFolder.getAbsoluteFile().getParentFile().getParentFile(), worldName);
if (worldFolder.exists() && worldFolder.isDirectory()) {
logger.log(Level.WARNING, "World " + worldName + " not loaded, but directory found. Converting warp anyway.");
forceWorldName = true;
}
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
setWarp(filename.substring(0, filename.length() - 4), loc, forceWorldName ? worldName : null);
if(!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{ {
throw new Exception("Renaming file " + filename + " failed");
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
File warpFile = new File(dataFolder, "warps.txt");
if (warpFile.exists()) {
try {
BufferedReader rx = new BufferedReader(new FileReader(warpFile));
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":")) {
if (parts.length < 6) {
continue;
}
String name = parts[0];
double x = Double.parseDouble(parts[1].trim());
double y = Double.parseDouble(parts[2].trim());
double z = Double.parseDouble(parts[3].trim());
float yaw = Float.parseFloat(parts[4].trim());
float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty()) {
continue;
}
World w = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() != World.Environment.NETHER) {
w = world;
break;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
setWarp(name, loc);
if(!warpFile.renameTo(new File(dataFolder, "warps.txt.old")));
{
throw new Exception("Renaming warps.txt failed");
}
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
public final void reloadConfig() {
warpPoints.clear(); warpPoints.clear();
File[] listOfFiles = warpsFolder.listFiles(); File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1) { if (listOfFiles.length >= 1)
for (int i = 0; i < listOfFiles.length; i++) { {
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName(); String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { if (listOfFiles[i].isFile() && filename.endsWith(".yml"))
{
EssentialsConf conf = new EssentialsConf(listOfFiles[i]); EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
conf.load(); conf.load();
String name = conf.getString("name"); String name = conf.getString("name");
if (name != null) { if (name != null)
{
warpPoints.put(new StringIgnoreCase(name), conf); warpPoints.put(new StringIgnoreCase(name), conf);
} }
} }
@@ -217,26 +111,32 @@ public class Warps implements IConf {
} }
} }
private class StringIgnoreCase {
private class StringIgnoreCase
{
String string; String string;
public StringIgnoreCase(String string) { public StringIgnoreCase(String string)
{
this.string = string; this.string = string;
} }
@Override @Override
public int hashCode() { public int hashCode()
{
return string.toLowerCase().hashCode(); return string.toLowerCase().hashCode();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o)
if (o instanceof String) { {
return string.equalsIgnoreCase((String) o); if (o instanceof String)
{
return string.equalsIgnoreCase((String)o);
} }
if (o instanceof StringIgnoreCase) { if (o instanceof StringIgnoreCase)
return string.equalsIgnoreCase(((StringIgnoreCase) o).string); {
return string.equalsIgnoreCase(((StringIgnoreCase)o).string);
} }
return false; return false;
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,20 +12,17 @@ public class Commandafk extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
if (parent.away.contains(user)) if (!user.toggleAfk())
{ {
user.sendMessage("§7You are no longer marked as away."); user.sendMessage("§7You are no longer marked as away.");
server.broadcastMessage("§7" + user.getDisplayName() + " is no longer AFK"); server.broadcastMessage("§7" + user.getDisplayName() + " is no longer AFK");
parent.away.remove(user); } else {
return;
}
user.sendMessage("§7You are now marked as away."); user.sendMessage("§7You are now marked as away.");
server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK"); server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK");
parent.away.add(user); }
} }
} }

View File

@@ -5,7 +5,6 @@ import net.minecraft.server.World;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.CraftWorld;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.TargetBlock; import com.earth2me.essentials.TargetBlock;
@@ -18,14 +17,9 @@ public class Commandantioch extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
/*if (!user.isOp()) charge(user);
{
user.sendMessage("§cNone shall pass.");
return;
}*/
server.broadcastMessage("...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); server.broadcastMessage("...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,");
server.broadcastMessage("who being naughty in My sight, shall snuff it."); server.broadcastMessage("who being naughty in My sight, shall snuff it.");

View File

@@ -1,6 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
@@ -13,10 +12,10 @@ public class Commandback extends EssentialsCommand
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.canAfford(this); user.canAfford(this);
user.sendMessage("§7Returning to previous location."); user.sendMessage("§7Returning to previous location.");
user.teleportBack(this.getName()); user.getTeleport().back(this.getName());
} }
} }

View File

@@ -1,43 +1,28 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Backup; import com.earth2me.essentials.Backup;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
/**
*
* @author schlex
*/
public class Commandbackup extends EssentialsCommand {
public Commandbackup() { public class Commandbackup extends EssentialsCommand
{
public Commandbackup()
{
super("backup"); super("backup");
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
Backup backup = Essentials.getStatic().backup; {
if (backup == null) return; Backup backup = Essentials.getBackup();
backup.run(); if (backup == null)
{
return;
} }
charge(sender);
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
Backup backup = Essentials.getStatic().backup;
if (backup == null) return;
user.charge(this);
backup.run(); backup.run();
user.sendMessage("Backup started"); sender.sendMessage("Backup started");
} }
} }

View File

@@ -1,9 +1,8 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand; import org.bukkit.command.CommandSender;
public class Commandbalance extends EssentialsCommand public class Commandbalance extends EssentialsCommand
@@ -14,8 +13,20 @@ public class Commandbalance extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
sender.sendMessage("§7Balance: $" + getPlayer(server, args, 0).getMoney());
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
charge(user);
user.sendMessage("§7Balance: $" + (args.length < 1 || !user.isAuthorized("essentials.balance.other") user.sendMessage("§7Balance: $" + (args.length < 1 || !user.isAuthorized("essentials.balance.other")
? user ? user
: getPlayer(server, args, 0)).getMoney()); : getPlayer(server, args, 0)).getMoney());

View File

@@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -15,16 +14,13 @@ public class Commandban extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("§cUsage: /" + commandLabel + " [player] <reason>"); throw new NotEnoughArgumentsException();
return;
} }
try
{
User p = null; User p = null;
if (server.matchPlayer(args[0]).isEmpty()) if (server.matchPlayer(args[0]).isEmpty())
{ {
@@ -33,17 +29,16 @@ public class Commandban extends EssentialsCommand
} }
else else
{ {
p = User.get(server.matchPlayer(args[0]).get(0)); p = ess.getUser(server.matchPlayer(args[0]).get(0));
p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Banned from server"); String banReason = "Banned from server";
if(args.length > 1) {
banReason = getFinalArg(args, 1);
p.setBanReason(commandLabel);
}
p.kickPlayer(banReason);
((CraftServer)server).getHandle().a(p.getName()); ((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage("§cPlayer " + p.getName() + " banned"); sender.sendMessage("§cPlayer " + p.getName() + " banned");
} }
Essentials.getStatic().loadBanList(); ess.loadBanList();
}
catch (Throwable ex)
{
ex.printStackTrace();
sender.sendMessage("Error: " + ex);
}
} }
} }

View File

@@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
public class Commandbanip extends EssentialsCommand public class Commandbanip extends EssentialsCommand
@@ -14,17 +13,16 @@ public class Commandbanip extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [address]"); throw new NotEnoughArgumentsException();
return;
} }
((CraftServer)server).getHandle().c(args[0]); ((CraftServer)server).getHandle().c(args[0]);
sender.sendMessage("§7Banned IP address."); sender.sendMessage("§7Banned IP address.");
Essentials.getStatic().loadBanList(); ess.loadBanList();
} }
} }

View File

@@ -2,8 +2,8 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.TreeType; import org.bukkit.TreeType;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Location; import org.bukkit.Location;
@@ -15,7 +15,7 @@ public class Commandbigtree extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
Object tree = new Object(); Object tree = new Object();
if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) if (args.length > 0 && args[0].equalsIgnoreCase("redwood"))
@@ -28,8 +28,7 @@ public class Commandbigtree extends EssentialsCommand
} }
else else
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [tree|redwood]"); throw new NotEnoughArgumentsException();
return;
} }
double x = user.getLocation().getX(); double x = user.getLocation().getX();
@@ -38,19 +37,33 @@ public class Commandbigtree extends EssentialsCommand
// offset tree in direction player is facing // offset tree in direction player is facing
int r = (int)user.getCorrectedYaw(); int r = (int)user.getCorrectedYaw();
if (r < 68 || r > 292) x -= 3.0D; // north if (r < 68 || r > 292) // north
else if (r > 112 && r < 248) x += 3.0D; // south {
if (r > 22 && r < 158) z -= 3.0D; // east x -= 3.0D;
else if (r > 202 && r < 338) z += 3.0D; // west }
else if (r > 112 && r < 248) // south
{
x += 3.0D;
}
if (r > 22 && r < 158) // east
{
z -= 3.0D;
}
else if (r > 202 && r < 338) // west
{
z += 3.0D;
}
Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); Location safeLocation = Util.getSafeDestination(new Location(user.getWorld(), x, y, z));
boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree);
if (success) if (success)
{ {
user.charge(this); charge(user);
user.sendMessage("Big tree spawned."); user.sendMessage("Big tree spawned.");
} }
else else
{
user.sendMessage("§cBig tree generation failure. Try again on grass or dirt."); user.sendMessage("§cBig tree generation failure. Try again on grass or dirt.");
} }
}
} }

View File

@@ -1,8 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -14,20 +12,14 @@ public class Commandbroadcast extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [msg]"); throw new NotEnoughArgumentsException();
} }
StringBuilder message = new StringBuilder(); charge(sender);
for (int i = 0; i < args.length; i++) server.broadcastMessage("[§cBroadcast§f]§a " + getFinalArg(args, 0));
{
message.append(args[i]);
message.append(' ');
}
server.broadcastMessage("[§cBroadcast§f]§a " + message.toString());
} }
} }

View File

@@ -1,32 +1,30 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.User;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class Commandburn extends EssentialsCommand public class Commandburn extends EssentialsCommand
{ {
public Commandburn() public Commandburn()
{ {
super("burn"); super("burn");
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2) if (args.length < 2)
{ {
user.sendMessage("§cUsage: /burn [player] [seconds]"); throw new NotEnoughArgumentsException();
return;
} }
User.charge(user, this); charge(sender);
for (Player p : server.matchPlayer(args[0])) for (Player p : server.matchPlayer(args[0]))
{ {
p.setFireTicks(Integer.parseInt(args[1]) * 20); p.setFireTicks(Integer.parseInt(args[1]) * 20);
user.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds."); sender.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds.");
} }
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -17,16 +16,7 @@ public class Commandclearinventory extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[]
{
getName(), "ci"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others")) if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others"))
{ {
@@ -36,11 +26,11 @@ public class Commandclearinventory extends EssentialsCommand
if (!online.isEmpty()) if (!online.isEmpty())
{ {
charge(user);
for (Player p : online) for (Player p : online)
{ {
p.getInventory().clear(); p.getInventory().clear();
user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared."); user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared.");
user.charge(this);
} }
return; return;
} }
@@ -48,12 +38,12 @@ public class Commandclearinventory extends EssentialsCommand
} }
else else
{ {
Player u = server.getPlayer(args[0]); Player p = server.getPlayer(args[0]);
if (u != null) if (p != null)
{ {
u.getInventory().clear(); charge(user);
user.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared."); p.getInventory().clear();
user.charge(this); user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared.");
} }
else else
{ {
@@ -63,14 +53,14 @@ public class Commandclearinventory extends EssentialsCommand
} }
else else
{ {
charge(user);
user.getInventory().clear(); user.getInventory().clear();
user.sendMessage("§7Inventory cleared."); user.sendMessage("§7Inventory cleared.");
user.charge(this);
} }
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,9 +12,9 @@ public class Commandcompass extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
int r = (int)user.getCorrectedYaw(); int r = (int)user.getCorrectedYaw();
String dir; String dir;
if (r < 23) dir = "N"; if (r < 23) dir = "N";

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -12,22 +11,13 @@ public class Commanddeljail extends EssentialsCommand {
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); charge(sender);
Essentials.getJail().delJail(args[0]); Essentials.getJail().delJail(args[0]);
user.sendMessage("§7Jail " + args[0] + " has been removed"); sender.sendMessage("§7Jail " + args[0] + " has been removed");
} }
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception {
super.run(server, parent, sender, commandLabel, args);
}
} }

View File

@@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commanddelwarp extends EssentialsCommand public class Commanddelwarp extends EssentialsCommand
@@ -14,27 +13,13 @@ public class Commanddelwarp extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [warp name]"); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); charge(sender);
Essentials.getWarps().delWarp(args[0]);
user.sendMessage("§7Warp removed.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("§cUsage: /" + commandLabel + " [warp name]");
return;
}
Essentials.getWarps().delWarp(args[0]); Essentials.getWarps().delWarp(args[0]);
sender.sendMessage("§7Warp removed."); sender.sendMessage("§7Warp removed.");
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,12 +12,21 @@ public class Commanddepth extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
int y = user.getLocation().getBlockY() - 63; int y = user.getLocation().getBlockY() - 63;
if (y > 0) user.sendMessage("§7You are " + y + " block(s) above sea level."); if (y > 0)
else if (y < 0) user.sendMessage("§7You are " + (-y) + " block(s) below sea level."); {
else user.sendMessage("§7You are at sea level."); user.sendMessage("§7You are " + y + " block(s) above sea level.");
}
else if (y < 0)
{
user.sendMessage("§7You are " + (-y) + " block(s) below sea level.");
}
else
{
user.sendMessage("§7You are at sea level.");
}
} }
} }

View File

@@ -15,26 +15,29 @@ public class Commandeco extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
EcoCommands cmd; EcoCommands cmd;
int amount; double amount;
try try
{ {
cmd = EcoCommands.valueOf(args[0].toUpperCase()); cmd = EcoCommands.valueOf(args[0].toUpperCase());
amount = Integer.parseInt(args[2].replaceAll("[^0-9]", "")); amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", ""));
} }
catch (Exception ex) catch (Exception ex)
{ {
sender.sendMessage("§cUsage: /eco [give|take|reset] [player] [money]"); throw new NotEnoughArgumentsException();
return;
} }
if (args[1].contentEquals("*")) if (args[1].contentEquals("*"))
{ {
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
User u = User.get(p); User u = ess.getUser(p);
switch (cmd) switch (cmd)
{ {
case GIVE: case GIVE:
@@ -46,7 +49,7 @@ public class Commandeco extends EssentialsCommand
break; break;
case RESET: case RESET:
u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break; break;
} }
} }
@@ -55,7 +58,7 @@ public class Commandeco extends EssentialsCommand
{ {
for (Player p : server.matchPlayer(args[1])) for (Player p : server.matchPlayer(args[1]))
{ {
User u = User.get(p); User u = ess.getUser(p);
switch (cmd) switch (cmd)
{ {
case GIVE: case GIVE:
@@ -67,7 +70,7 @@ public class Commandeco extends EssentialsCommand
break; break;
case RESET: case RESET:
u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break; break;
} }
} }

View File

@@ -2,8 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandessentials extends EssentialsCommand public class Commandessentials extends EssentialsCommand
@@ -14,17 +12,10 @@ public class Commandessentials extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
parent.reload(); ess.reload();
user.charge(this); charge(sender);
user.sendMessage("§7Essentials Reloaded " + parent.getDescription().getVersion()); sender.sendMessage("§7Essentials Reloaded " + ess.getDescription().getVersion());
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
parent.reload();
sender.sendMessage("Essentials Reloaded " + parent.getDescription().getVersion());
} }
} }

View File

@@ -1,29 +1,50 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class Commandext extends EssentialsCommand {
public Commandext() { public class Commandext extends EssentialsCommand
{
public Commandext()
{
super("ext"); super("ext");
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
if (args.length < 1) { {
User.charge(user, this); if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
extinguishPlayers(server, sender, args[0]);
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
charge(user);
user.setFireTicks(0); user.setFireTicks(0);
user.sendMessage("§7You extinguished yourself."); user.sendMessage("§7You extinguished yourself.");
return; return;
} }
for (Player p : server.matchPlayer(args[0])) { extinguishPlayers(server, user, commandLabel);
User.charge(user, this); }
private void extinguishPlayers(Server server, CommandSender sender, String name) throws Exception
{
for (Player p : server.matchPlayer(name))
{
charge(sender);
p.setFireTicks(0); p.setFireTicks(0);
user.sendMessage("§7You extinguished " + p.getDisplayName() + "."); sender.sendMessage("§7You extinguished " + p.getDisplayName() + ".");
} }
} }
} }

View File

@@ -1,6 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -14,11 +13,12 @@ public class Commandgc extends EssentialsCommand
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
charge(sender);
sender.sendMessage("Maximum memory: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB"); sender.sendMessage("Maximum memory: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB");
sender.sendMessage("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " MB"); sender.sendMessage("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " MB");
for (World w : parent.getServer().getWorlds()) for (World w : server.getWorlds())
{ {
sender.sendMessage( sender.sendMessage(
(w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": " (w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": "

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -14,15 +13,9 @@ public class Commandgetpos extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
return new String[] { getName(), "coords" }; charge(user);
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
Location coords = user.getLocation(); Location coords = user.getLocation();
user.sendMessage("§7X: " + coords.getBlockX() + " (-North <-> +South)"); user.sendMessage("§7X: " + coords.getBlockX() + " (-North <-> +South)");
user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)"); user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)");

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.ItemDb; import com.earth2me.essentials.ItemDb;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -19,26 +18,29 @@ public class Commandgive extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2) if (args.length < 2)
{ {
sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] [item]<:data> <amount>"); throw new NotEnoughArgumentsException();
return;
} }
String[] itemArgs = args[1].split("[^a-zA-Z0-9]"); String[] itemArgs = args[1].split("[^a-zA-Z0-9]");
ItemStack stack = ItemDb.get(itemArgs[0]); ItemStack stack = ItemDb.get(itemArgs[0]);
if(sender instanceof Player && !User.get(sender).isAuthorized("essentials.itemspawn.exempt") && !User.get(sender).canSpawnItem(stack.getTypeId())) if (sender instanceof Player
&& !ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))
{ {
sender.sendMessage(ChatColor.RED + "You are not allowed to spawn that item"); sender.sendMessage(ChatColor.RED + "You are not allowed to spawn that item");
return; return;
} }
if (itemArgs.length > 1) { if (itemArgs.length > 1)
{
stack.setDurability(Short.parseShort(itemArgs[1])); stack.setDurability(Short.parseShort(itemArgs[1]));
} }
if (args.length > 2 && Integer.parseInt(args[2]) > 0) { if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2])); stack.setAmount(Integer.parseInt(args[2]));
} }
@@ -49,9 +51,7 @@ public class Commandgive extends EssentialsCommand
User giveTo = getPlayer(server, args, 0); User giveTo = getPlayer(server, args, 0);
String itemName = stack.getType().name().toLowerCase().replace('_', ' '); String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
if (sender instanceof Player) { charge(sender);
User.get(sender).charge(this);
}
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
giveTo.getInventory().addItem(stack); giveTo.getInventory().addItem(stack);
} }

View File

@@ -1,8 +1,8 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -14,26 +14,37 @@ public class Commandgod extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
return new String[] { {
getName(), "egod" if (args.length < 1)
}; {
throw new NotEnoughArgumentsException();
}
godOtherPlayers(server, sender, args[0]);
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length > 0 && (user.isAuthorized("essentials.god.others") || user.isOp())) charge(user);
if (args.length > 0 && user.isAuthorized("essentials.god.others"))
{ {
for (Player p : server.matchPlayer(args[0])) godOtherPlayers(server, user, args[0]);
{
User u = User.get(p);
boolean enabled = u.toggleGodMode();
u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled."));
user.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + ".");
}
return; return;
} }
user.sendMessage("§7God mode " + (user.toggleGodMode() ? "enabled." : "disabled."));
user.sendMessage("§7God mode " + (user.toggleGodModeEnabled() ? "enabled." : "disabled."));
}
private void godOtherPlayers(Server server, CommandSender sender, String name)
{
for (Player p : server.matchPlayer(name))
{
User u = ess.getUser(p);
boolean enabled = u.toggleGodModeEnabled();
u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled."));
sender.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + ".");
}
} }
} }

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -15,46 +14,46 @@ public class Commandheal extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() { public void run(Server server, User user, String commandLabel, String[] args) throws Exception
return new String[] {
getName(), "eheal"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length > 0 && user.isAuthorized("essentials.heal.others")) if (args.length > 0 && user.isAuthorized("essentials.heal.others"))
{ {
if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); if (!user.isAuthorized("essentials.heal.cooldown.bypass"))
user.charge(this);
for (Player p : server.matchPlayer(args[0]))
{ {
p.setHealth(20); user.healCooldown();
user.sendMessage("§7Healed " + p.getDisplayName() + ".");
} }
charge(user);
healOtherPlayers(server, user, commandLabel);
return; return;
} }
if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); if (!user.isAuthorized("essentials.heal.cooldown.bypass"))
user.charge(this); {
user.healCooldown();
}
charge(user);
user.setHealth(20); user.setHealth(20);
user.sendMessage("§7You have been healed."); user.sendMessage("§7You have been healed.");
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [player]"); throw new NotEnoughArgumentsException();
return;
} }
for (Player p : server.matchPlayer(args[0])) healOtherPlayers(server, sender, args[0]);
}
private void healOtherPlayers(Server server, CommandSender sender, String name)
{
for (Player p : server.matchPlayer(name))
{ {
p.setHealth(20); p.setHealth(20);
sender.sendMessage("Healed " + p.getDisplayName() + "."); sender.sendMessage("§7Healed " + p.getDisplayName() + ".");
} }
} }
} }

View File

@@ -26,7 +26,7 @@ public class Commandhelp extends EssentialsCommand
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
int page; int page;
try try
@@ -38,7 +38,7 @@ public class Commandhelp extends EssentialsCommand
page = 1; page = 1;
} }
List<String> lines = getHelpLines(parent, user); List<String> lines = getHelpLines(user);
int start = (page - 1) * 9; int start = (page - 1) * 9;
int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0);
@@ -50,16 +50,16 @@ public class Commandhelp extends EssentialsCommand
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
sender.sendMessage("To view help from the console, type \"?\"."); sender.sendMessage("To view help from the console, type \"?\".");
} }
@SuppressWarnings("CallToThreadDumpStack") @SuppressWarnings("CallToThreadDumpStack")
private List<String> getHelpLines(Essentials parent, User user) throws Exception private List<String> getHelpLines(User user) throws Exception
{ {
List<String> retval = new ArrayList<String>(); List<String> retval = new ArrayList<String>();
File file = new File(parent.getDataFolder(), "help.txt"); File file = new File(ess.getDataFolder(), "help.txt");
if (file.exists()) if (file.exists())
{ {
BufferedReader rx = new BufferedReader(new FileReader(file)); BufferedReader rx = new BufferedReader(new FileReader(file));
@@ -71,7 +71,7 @@ public class Commandhelp extends EssentialsCommand
} }
boolean reported = false; boolean reported = false;
for (Plugin p : parent.getServer().getPluginManager().getPlugins()) for (Plugin p : ess.getServer().getPluginManager().getPlugins())
{ {
try try
{ {
@@ -82,7 +82,7 @@ public class Commandhelp extends EssentialsCommand
if (p.getDescription().getName().toLowerCase().contains("essentials")) if (p.getDescription().getName().toLowerCase().contains("essentials"))
{ {
String node = "essentials." + k; String node = "essentials." + k;
if (!Essentials.getSettings().isCommandDisabled(k) && user.isAuthorized(node)) if (!ess.getSettings().isCommandDisabled(k) && user.isAuthorized(node))
{ {
HashMap<String, String> v = cmds.get(k); HashMap<String, String> v = cmds.get(k);
retval.add("§c" + k + "§7: " + v.get("description")); retval.add("§c" + k + "§7: " + v.get("description"));
@@ -90,7 +90,7 @@ public class Commandhelp extends EssentialsCommand
} }
else else
{ {
if (Essentials.getSettings().showNonEssCommandsInHelp()) if (ess.getSettings().showNonEssCommandsInHelp())
{ {
HashMap<String, String> v = cmds.get(k); HashMap<String, String> v = cmds.get(k);
if (v.containsKey("permission") && v.get("permission") != null && !(v.get("permission").equals(""))) if (v.containsKey("permission") && v.get("permission") != null && !(v.get("permission").equals("")))
@@ -111,7 +111,6 @@ public class Commandhelp extends EssentialsCommand
} }
catch (NullPointerException ex) catch (NullPointerException ex)
{ {
continue; continue;
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -14,19 +13,21 @@ public class Commandhelpop extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cTo request help from an op, type §f/" + commandLabel+ "§c, followed by your question."); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); charge(user);
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
User u = User.get(p); User u = ess.getUser(p);
if (!u.isOp() && !u.isAuthorized("essentials.helpop.receive")) continue; if (!u.isAuthorized("essentials.helpop.receive"))
{
continue;
}
u.sendMessage("§c[HelpOp]§f §7" + user.getDisplayName() + ":§f " + getFinalArg(args, 0)); u.sendMessage("§c[HelpOp]§f §7" + user.getDisplayName() + ":§f " + getFinalArg(args, 0));
} }
} }

View File

@@ -1,9 +1,9 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
public class Commandhome extends EssentialsCommand public class Commandhome extends EssentialsCommand
{ {
public Commandhome() public Commandhome()
@@ -12,15 +12,15 @@ public class Commandhome extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.canAfford(this); user.canAfford(this);
user.teleportCooldown();
if(args.length > 0 && user.isAuthorized("essentials.home.others")) if(args.length > 0 && user.isAuthorized("essentials.home.others"))
{ {
user.teleportToHome(this.getName(), args[0]); User u = getPlayer(server, args, 0);
user.getTeleport().home(u, this.getName());
return; return;
} }
user.teleportToHome(this.getName()); user.getTeleport().home(this.getName());
} }
} }

View File

@@ -1,6 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
@@ -11,38 +10,45 @@ import java.util.Map;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class Commandinfo extends EssentialsCommand {
public Commandinfo() { public class Commandinfo extends EssentialsCommand
{
public Commandinfo()
{
super("info"); super("info");
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
String pageStr = args.length > 0 ? args[0].trim() : null; String pageStr = args.length > 0 ? args[0].trim() : null;
List<String> lines = new ArrayList<String>(); List<String> lines = new ArrayList<String>();
List<String> chapters = new ArrayList<String>(); List<String> chapters = new ArrayList<String>();
Map<String, Integer> bookmarks = new HashMap<String, Integer>(); Map<String, Integer> bookmarks = new HashMap<String, Integer>();
File file = new File(parent.getDataFolder(), "info.txt"); File file = new File(ess.getDataFolder(), "info.txt");
if (file.exists()) if (file.exists())
{ {
BufferedReader rx = new BufferedReader(new FileReader(file)); BufferedReader rx = new BufferedReader(new FileReader(file));
int i = 0; int i = 0;
for (String l = null; rx.ready() && (l = rx.readLine()) != null; i++) for (String l = null; rx.ready() && (l = rx.readLine()) != null; i++)
{ {
if (l.startsWith("#")) { if (l.startsWith("#"))
{
bookmarks.put(l.substring(1).toLowerCase(), i); bookmarks.put(l.substring(1).toLowerCase(), i);
chapters.add(l.substring(1)); chapters.add(l.substring(1));
} }
lines.add(l.replace('&', '§')); lines.add(l.replace('&', '§'));
} }
} else { }
else
{
sender.sendMessage("File info.txt does not exists."); sender.sendMessage("File info.txt does not exists.");
return; return;
} }
if (bookmarks.isEmpty()) { if (bookmarks.isEmpty())
{
int page = 1; int page = 1;
try try
{ {
@@ -56,6 +62,7 @@ public class Commandinfo extends EssentialsCommand {
int start = (page - 1) * 9; int start = (page - 1) * 9;
int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0);
charge(sender);
sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:"); sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < lines.size() && i < start + 9; i++) for (int i = start; i < lines.size() && i < start + 9; i++)
{ {
@@ -64,13 +71,17 @@ public class Commandinfo extends EssentialsCommand {
return; return;
} }
if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+")) { if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+"))
if (lines.get(0).startsWith("#")) { {
if (lines.get(0).startsWith("#"))
{
sender.sendMessage("Select chapter:"); sender.sendMessage("Select chapter:");
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
boolean first = true; boolean first = true;
for (String string : chapters) { for (String string : chapters)
if (!first) { {
if (!first)
{
sb.append(", "); sb.append(", ");
} }
first = false; first = false;
@@ -78,7 +89,9 @@ public class Commandinfo extends EssentialsCommand {
} }
sender.sendMessage(sb.toString()); sender.sendMessage(sb.toString());
return; return;
} else { }
else
{
int page = 1; int page = 1;
try try
{ {
@@ -94,12 +107,14 @@ public class Commandinfo extends EssentialsCommand {
for (end = 0; end < lines.size(); end++) for (end = 0; end < lines.size(); end++)
{ {
String line = lines.get(end); String line = lines.get(end);
if (line.startsWith("#")) { if (line.startsWith("#"))
{
break; break;
} }
} }
int pages = end / 9 + (end % 9 > 0 ? 1 : 0); int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
charge(sender);
sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:"); sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < end && i < start + 9; i++) for (int i = start; i < end && i < start + 9; i++)
{ {
@@ -110,7 +125,8 @@ public class Commandinfo extends EssentialsCommand {
} }
int chapterpage = 0; int chapterpage = 0;
if (args.length >= 2) { if (args.length >= 2)
{
try try
{ {
chapterpage = Integer.parseInt(args[1]) - 1; chapterpage = Integer.parseInt(args[1]) - 1;
@@ -121,7 +137,8 @@ public class Commandinfo extends EssentialsCommand {
} }
} }
if (!bookmarks.containsKey(pageStr.toLowerCase())) { if (!bookmarks.containsKey(pageStr.toLowerCase()))
{
sender.sendMessage("Unknown chapter."); sender.sendMessage("Unknown chapter.");
return; return;
} }
@@ -130,7 +147,8 @@ public class Commandinfo extends EssentialsCommand {
for (chapterend = chapterstart; chapterend < lines.size(); chapterend++) for (chapterend = chapterstart; chapterend < lines.size(); chapterend++)
{ {
String line = lines.get(chapterend); String line = lines.get(chapterend);
if (line.startsWith("#")) { if (line.startsWith("#"))
{
break; break;
} }
} }
@@ -138,7 +156,8 @@ public class Commandinfo extends EssentialsCommand {
int page = chapterpage + 1; int page = chapterpage + 1;
int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0); int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0);
sender.sendMessage("Chapter "+ pageStr +", page §c" + page + "§f of §c" + pages + "§f:"); charge(sender);
sender.sendMessage("Chapter " + pageStr + ", page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < chapterend && i < start + 9; i++) for (int i = start; i < chapterend && i < start + 9; i++)
{ {
sender.sendMessage(lines.get(i)); sender.sendMessage(lines.get(i));

View File

@@ -1,38 +1,44 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
public class Commandinvsee extends EssentialsCommand {
public Commandinvsee() { public class Commandinvsee extends EssentialsCommand
{
public Commandinvsee()
{
super("invsee"); super("invsee");
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length == 0 && user.savedInventory == null) { if (args.length < 1 && user.getSavedInventory() == null)
user.sendMessage("§cUsage: /" + commandLabel + " <user>"); {
throw new NotEnoughArgumentsException();
} }
User invUser = user; User invUser = user;
if (args.length == 1) { if (args.length == 1)
{
invUser = getPlayer(server, args, 0); invUser = getPlayer(server, args, 0);
} }
if (invUser == user && user.savedInventory != null) { if (invUser == user && user.getSavedInventory() != null)
invUser.getInventory().setContents(user.savedInventory); {
user.savedInventory = null; invUser.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
user.sendMessage("Your inventory has been restored."); user.sendMessage("Your inventory has been restored.");
return; return;
} }
user.charge(this); charge(user);
if (user.savedInventory == null) { if (user.getSavedInventory() == null)
user.savedInventory = user.getInventory().getContents(); {
user.setSavedInventory(user.getInventory().getContents());
} }
user.getInventory().setContents(invUser.getInventory().getContents()); user.getInventory().setContents(invUser.getInventory().getContents());
user.sendMessage("You see the inventory of "+invUser.getDisplayName()+"."); user.sendMessage("You see the inventory of " + invUser.getDisplayName() + ".");
user.sendMessage("Use /invsee to restore your inventory."); user.sendMessage("Use /invsee to restore your inventory.");
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.ItemDb; import com.earth2me.essentials.ItemDb;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -17,12 +16,11 @@ public class Commanditem extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [item] <amount>"); throw new NotEnoughArgumentsException();
return;
} }
String[] itemArgs = args[0].split("[^a-zA-Z0-9]"); String[] itemArgs = args[0].split("[^a-zA-Z0-9]");
ItemStack stack = ItemDb.get(itemArgs[0]); ItemStack stack = ItemDb.get(itemArgs[0]);
@@ -46,7 +44,7 @@ public class Commanditem extends EssentialsCommand
} }
String itemName = stack.getType().name().toLowerCase().replace('_', ' '); String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
user.charge(this); charge(user);
user.sendMessage("§7Giving " + stack.getAmount() + " of " + itemName + " to " + user.getDisplayName() + "."); user.sendMessage("§7Giving " + stack.getAmount() + " of " + itemName + " to " + user.getDisplayName() + ".");
user.getInventory().addItem(stack); user.getInventory().addItem(stack);
} }

View File

@@ -1,18 +1,20 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class Commandjails extends EssentialsCommand {
public Commandjails() { public class Commandjails extends EssentialsCommand
{
public Commandjails()
{
super("jails"); super("jails");
} }
@Override @Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
StringBuilder jailList = new StringBuilder(); StringBuilder jailList = new StringBuilder();
for (String j : Essentials.getJail().getJails()) for (String j : Essentials.getJail().getJails())
{ {
@@ -21,17 +23,4 @@ public class Commandjails extends EssentialsCommand {
} }
sender.sendMessage("§7" + jailList); sender.sendMessage("§7" + jailList);
} }
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
StringBuilder jailList = new StringBuilder();
for (String j : Essentials.getJail().getJails())
{
jailList.append(j);
jailList.append(' ');
}
user.sendMessage("§7" + jailList);
}
} }

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.TargetBlock; import com.earth2me.essentials.TargetBlock;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -15,16 +14,7 @@ public class Commandjump extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[]
{
getName(), "j"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
Location loc; Location loc;
Location cloc = user.getLocation(); Location cloc = user.getLocation();
@@ -45,6 +35,6 @@ public class Commandjump extends EssentialsCommand
} }
user.canAfford(this); user.canAfford(this);
user.teleportTo(loc, this.getName()); user.getTeleport().teleport(loc, this.getName());
} }
} }

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -15,18 +14,17 @@ public class Commandkick extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] <reason>"); throw new NotEnoughArgumentsException();
return;
} }
User p; User u;
try try
{ {
p = User.get(server.matchPlayer(args[0]).get(0)); u = ess.getUser(server.matchPlayer(args[0]).get(0));
} }
catch (Throwable ex) catch (Throwable ex)
{ {
@@ -35,7 +33,6 @@ public class Commandkick extends EssentialsCommand
} }
charge(sender); charge(sender);
p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server"); u.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server");
} }
} }

View File

@@ -3,8 +3,7 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandkickall extends EssentialsCommand public class Commandkickall extends EssentialsCommand
{ {
@@ -14,31 +13,20 @@ public class Commandkickall extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
charge(sender);
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
if (server.getOnlinePlayers().length == 1 && p.getName().equalsIgnoreCase(user.getName())) if (sender instanceof Player && p.getName().equalsIgnoreCase(((Player)sender).getName()))
{ {
user.sendMessage("§7Only you online..."); continue;
return;
} }
else else
{
if (!p.getName().equalsIgnoreCase(user.getName()))
{ {
p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server"); p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server");
} }
} }
} }
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
for (Player p : server.getOnlinePlayers())
{
p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server");
}
}
} }

View File

@@ -2,9 +2,7 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
public class Commandkill extends EssentialsCommand public class Commandkill extends EssentialsCommand
@@ -15,15 +13,14 @@ public class Commandkill extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("§cUsage: /kill [player]"); throw new NotEnoughArgumentsException();
return;
} }
User.charge(sender, this); charge(sender);
for (Player p : server.matchPlayer(args[0])) for (Player p : server.matchPlayer(args[0]))
{ {
p.setHealth(0); p.setHealth(0);

View File

@@ -7,6 +7,8 @@ import java.util.Map;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.GregorianCalendar;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -20,13 +22,14 @@ public class Commandkit extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception @SuppressWarnings("unchecked")
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
try try
{ {
Map<String, Object> kits = (Map<String, Object>)parent.getConfiguration().getProperty("kits"); Map<String, Object> kits = (Map<String, Object>)ess.getConfiguration().getProperty("kits");
StringBuilder list = new StringBuilder(); StringBuilder list = new StringBuilder();
for (String k : kits.keySet()) for (String k : kits.keySet())
{ {
@@ -54,7 +57,7 @@ public class Commandkit extends EssentialsCommand
try try
{ {
String kitName = args[0].toLowerCase(); String kitName = args[0].toLowerCase();
Object kit = Essentials.getSettings().getKit(kitName); Object kit = ess.getSettings().getKit(kitName);
List<String> items; List<String> items;
if (!user.isAuthorized("essentials.kit." + kitName)) if (!user.isAuthorized("essentials.kit." + kitName))
@@ -69,8 +72,13 @@ public class Commandkit extends EssentialsCommand
//System.out.println("Kit is timed"); //System.out.println("Kit is timed");
Map<String, Object> els = (Map<String, Object>)kit; Map<String, Object> els = (Map<String, Object>)kit;
items = (List<String>)els.get("items"); items = (List<String>)els.get("items");
long delay = els.containsKey("delay") ? ((Number)els.get("delay")).longValue() * 1000L : 0L; double delay = els.containsKey("delay") ? ((Number)els.get("delay")).doubleValue() : 0L;
long time = Calendar.getInstance().getTimeInMillis(); Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay*1000.0)%1000.0));
long time = c.getTimeInMillis();
Calendar now = new GregorianCalendar();
Map<String, Long> kitTimes; Map<String, Long> kitTimes;
if (!kitPlayers.containsKey(user)) if (!kitPlayers.containsKey(user))
@@ -86,15 +94,13 @@ public class Commandkit extends EssentialsCommand
{ {
kitTimes.put(kitName, time); kitTimes.put(kitName, time);
} }
else if (kitTimes.get(kitName) + delay <= time) else if (kitTimes.get(kitName) < now.getTimeInMillis())
{ {
kitTimes.put(kitName, time); kitTimes.put(kitName, time);
} }
else else
{ {
long left = kitTimes.get(kitName) + delay - time; user.sendMessage("§cYou can't use that kit again for another " + Util.formatDateDiff(kitTimes.get(kitName)) + ".");
user.sendMessage("§cYou can't use that kit again for another " + Essentials.FormatTime(left) + ".");
return; return;
} }
} }
@@ -104,9 +110,12 @@ public class Commandkit extends EssentialsCommand
items = (List<String>)kit; items = (List<String>)kit;
} }
try { try
{
user.canAfford("kit-" + kitName); user.canAfford("kit-" + kitName);
} catch (Exception ex) { }
catch (Exception ex)
{
user.sendMessage(ex.getMessage()); user.sendMessage(ex.getMessage());
return; return;
} }
@@ -118,24 +127,24 @@ public class Commandkit extends EssentialsCommand
int id = Integer.parseInt(parts[0]); int id = Integer.parseInt(parts[0]);
int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1; int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1;
short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0; short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0;
if(user.getInventory().firstEmpty() != -1) HashMap<Integer,ItemStack> overfilled = user.getInventory().addItem(new ItemStack(id, amount, data));
{ for (ItemStack itemStack : overfilled.values())
user.getInventory().addItem(new ItemStack(id, amount, data));
}
else
{ {
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
spew = true; spew = true;
user.getWorld().dropItemNaturally(user.getLocation(), new ItemStack(id, amount, data));
} }
} }
if(spew) if (spew)
{ {
user.sendMessage("§7Your inventory was full, placing kit on the floor"); user.sendMessage("§7Your inventory was full, placing kit on the floor");
} }
try { try
{
user.charge(this); user.charge(this);
user.charge("kit-" + kitName); user.charge("kit-" + kitName);
} catch (Exception ex) { }
catch (Exception ex)
{
user.sendMessage(ex.getMessage()); user.sendMessage(ex.getMessage());
} }
user.sendMessage("§7Giving kit " + args[0].toLowerCase() + "."); user.sendMessage("§7Giving kit " + args[0].toLowerCase() + ".");

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.TargetBlock;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
@@ -16,7 +15,7 @@ public class Commandlightning extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
World world = user.getWorld(); World world = user.getWorld();
@@ -26,7 +25,7 @@ public class Commandlightning extends EssentialsCommand
return; return;
} }
if(server.matchPlayer(args[0]).isEmpty()) if (server.matchPlayer(args[0]).isEmpty())
{ {
user.sendMessage("§cPlayer not found"); user.sendMessage("§cPlayer not found");
return; return;
@@ -37,7 +36,7 @@ public class Commandlightning extends EssentialsCommand
user.sendMessage("§7Smiting " + p.getDisplayName()); user.sendMessage("§7Smiting " + p.getDisplayName());
world.strikeLightning(p.getLocation()); world.strikeLightning(p.getLocation());
p.setHealth(p.getHealth() < 5 ? 0 : p.getHealth() -5); p.setHealth(p.getHealth() < 5 ? 0 : p.getHealth() -5);
if(Essentials.getSettings().warnOnSmite()) if(ess.getSettings().warnOnSmite())
{ {
p.sendMessage("§7You have just been smited"); p.sendMessage("§7You have just been smited");
} }

View File

@@ -22,23 +22,25 @@ public class Commandlist extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
User.charge(sender, this); charge(sender);
StringBuilder online = new StringBuilder(); StringBuilder online = new StringBuilder();
online.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(server.getOnlinePlayers().length); online.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(server.getOnlinePlayers().length);
online.append(ChatColor.BLUE).append(" out of a maximum ").append(ChatColor.RED).append(server.getMaxPlayers()); online.append(ChatColor.BLUE).append(" out of a maximum ").append(ChatColor.RED).append(server.getMaxPlayers());
online.append(ChatColor.BLUE).append(" players online."); online.append(ChatColor.BLUE).append(" players online.");
sender.sendMessage(online.toString()); sender.sendMessage(online.toString());
if (Essentials.getSettings().getSortListByGroups()) { if (ess.getSettings().getSortListByGroups())
{
Map<String, List<User>> sort = new HashMap<String, List<User>>(); Map<String, List<User>> sort = new HashMap<String, List<User>>();
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
User u = User.get(p); User u = ess.getUser(p);
String group = u.getGroup(); String group = u.getGroup();
List<User> list = sort.get(group); List<User> list = sort.get(group);
if (list == null) { if (list == null)
{
list = new ArrayList<User>(); list = new ArrayList<User>();
sort.put(group, list); sort.put(group, list);
} }
@@ -46,43 +48,56 @@ public class Commandlist extends EssentialsCommand
} }
String[] groups = sort.keySet().toArray(new String[0]); String[] groups = sort.keySet().toArray(new String[0]);
Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER); Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER);
for (String group : groups) { for (String group : groups)
{
StringBuilder groupString = new StringBuilder(); StringBuilder groupString = new StringBuilder();
groupString.append(group).append(": "); groupString.append(group).append(": ");
List<User> users = sort.get(group); List<User> users = sort.get(group);
Collections.sort(users); Collections.sort(users);
boolean first = true; boolean first = true;
for (User user : users) { for (User user : users)
if (!first) { {
if (!first)
{
groupString.append(", "); groupString.append(", ");
} else { }
else
{
first = false; first = false;
} }
if (parent.away.contains(user)) { if (user.isAfk())
{
groupString.append("§7[AFK]§f"); groupString.append("§7[AFK]§f");
} }
groupString.append(user.getDisplayName()); groupString.append(user.getDisplayName());
} }
sender.sendMessage(groupString.toString()); sender.sendMessage(groupString.toString());
} }
} else { }
else
{
List<User> users = new ArrayList<User>(); List<User> users = new ArrayList<User>();
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
users.add(User.get(p)); users.add(ess.getUser(p));
} }
Collections.sort(users); Collections.sort(users);
StringBuilder onlineUsers = new StringBuilder(); StringBuilder onlineUsers = new StringBuilder();
onlineUsers.append("Connected players: "); onlineUsers.append("Connected players: ");
boolean first = true; boolean first = true;
for (User user : users) { for (User user : users)
if (!first) { {
if (!first)
{
onlineUsers.append(", "); onlineUsers.append(", ");
} else { }
else
{
first = false; first = false;
} }
if (parent.away.contains(user)) { if (user.isAfk())
{
onlineUsers.append("§7[AFK]§f"); onlineUsers.append("§7[AFK]§f");
} }
onlineUsers.append(user.getDisplayName()); onlineUsers.append(user.getDisplayName());

View File

@@ -2,8 +2,9 @@ package com.earth2me.essentials.commands;
import java.util.List; import java.util.List;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class Commandmail extends EssentialsCommand public class Commandmail extends EssentialsCommand
@@ -14,21 +15,24 @@ public class Commandmail extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) if (args.length >= 1 && "read".equalsIgnoreCase(args[0]))
{ {
List<String> mail = Essentials.readMail(user); List<String> mail = user.getMails();
if (mail.isEmpty()) if (mail.isEmpty())
{ {
user.sendMessage("§cYou do not have any mail!"); user.sendMessage("§cYou do not have any mail!");
return; return;
} }
for (String s : mail) user.sendMessage(s); for (String s : mail)
{
user.sendMessage(s);
}
user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); user.sendMessage("§cTo mark your mail as read, type §c/mail clear");
return; return;
} }
if(args.length >= 3 && "send".equalsIgnoreCase(args[0])) if (args.length >= 3 && "send".equalsIgnoreCase(args[0]))
{ {
if (!user.isAuthorized("essentials.mail.send")) if (!user.isAuthorized("essentials.mail.send"))
{ {
@@ -36,14 +40,29 @@ public class Commandmail extends EssentialsCommand
return; return;
} }
user.charge(this); Player player = server.getPlayer(args[1]);
Essentials.sendMail(user, args[1], getFinalArg(args, 2)); User u;
if (player != null)
{
u = ess.getUser(player);
}
else
{
u = ess.getOfflineUser(args[1]);
}
if (u == null)
{
user.sendMessage("§cPlayer " + args[1] + " never was on this server.");
return;
}
charge(user);
u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2));
user.sendMessage("§7Mail sent!"); user.sendMessage("§7Mail sent!");
return; return;
} }
if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) if (args.length >= 1 && "clear".equalsIgnoreCase(args[0]))
{ {
Essentials.clearMail(user); user.setMails(null);
user.sendMessage("§7Mail cleared!"); user.sendMessage("§7Mail cleared!");
return; return;
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,23 +12,17 @@ public class Commandme extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "describe", "action" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (user.isMuted()) if (user.isMuted())
{ user.sendMessage("§7Your voice has been silenced"); {
user.sendMessage("§7Your voice has been silenced");
return; return;
} }
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /me [description]"); throw new NotEnoughArgumentsException();
return;
} }
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
for (int i = 0; i < args.length; i++) for (int i = 0; i < args.length; i++)
@@ -37,7 +30,7 @@ public class Commandme extends EssentialsCommand
message.append(args[i]); message.append(args[i]);
message.append(' '); message.append(' ');
} }
user.charge(this); charge(user);
server.broadcastMessage("* " + user.getDisplayName() + " " + message); server.broadcastMessage("* " + user.getDisplayName() + " " + message);
} }
} }

View File

@@ -1,8 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -14,10 +12,10 @@ public class Commandmotd extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
User.charge(sender, this); charge(sender);
for (String m : parent.getMotd(sender, "§cThere is no message of the day.")) for (String m : ess.getMotd(sender, "§cThere is no message of the day."))
{ {
sender.sendMessage(m); sender.sendMessage(m);
} }

View File

@@ -2,13 +2,12 @@ package com.earth2me.essentials.commands;
import java.util.List; import java.util.List;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.IReplyTo; import com.earth2me.essentials.IReplyTo;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class Commandmsg extends EssentialsCommand public class Commandmsg extends EssentialsCommand
{ {
public Commandmsg() public Commandmsg()
@@ -17,24 +16,17 @@ public class Commandmsg extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
return new String[] { getName(), "m", "tell", "whisper" }; if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty())
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0) throw new NotEnoughArgumentsException();
{
sender.sendMessage("§cUsage: /" + commandLabel + " [player] [message]");
return;
} }
String message = getFinalArg(args, 1); String message = getFinalArg(args, 1);
IReplyTo replyTo = sender instanceof Player?User.get((Player)sender):Console.getConsoleReplyTo(); IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
String senderName = sender instanceof Player?((Player)sender).getDisplayName():Console.NAME; String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
if (args[0].equalsIgnoreCase(Console.NAME)) if (args[0].equalsIgnoreCase(Console.NAME))
{ {
@@ -59,8 +51,8 @@ public class Commandmsg extends EssentialsCommand
{ {
sender.sendMessage("[Me -> " + p.getDisplayName() + "§f] " + message); sender.sendMessage("[Me -> " + p.getDisplayName() + "§f] " + message);
p.sendMessage("[" + senderName + " -> Me§f] " + message); p.sendMessage("[" + senderName + " -> Me§f] " + message);
replyTo.setReplyTo(User.get(p)); replyTo.setReplyTo(ess.getUser(p));
User.get(p).setReplyTo(sender); ess.getUser(p).setReplyTo(sender);
} }
} }
} }

View File

@@ -2,8 +2,8 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandmute extends EssentialsCommand public class Commandmute extends EssentialsCommand
@@ -14,51 +14,21 @@ public class Commandmute extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§7Usage: /" + commandLabel + " [player] <reason>"); throw new NotEnoughArgumentsException();
return;
} }
String[] sects2 = args[0].split(" +"); User p = getPlayer(server, args, 0);
User p; long muteTimestamp = 0;
try if (args.length > 1) {
{ String time = getFinalArg(args, 1);
p = User.get(server.matchPlayer(args[0]).get(0)); muteTimestamp = Util.parseDateDiff(time, true);
} }
catch (Exception ex) p.setMuteTimeout(muteTimestamp);
{ charge(sender);
user.sendMessage("§cThat player does not exist!"); sender.sendMessage("Player " + p.getDisplayName() + " " + (p.toggleMuted() ? "muted" : "unmuted") + (muteTimestamp > 0 ? " for" + Util.formatDateDiff(muteTimestamp) : "") + ".");
return;
}
user.sendMessage("§7Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted."));
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [player] <reason>");
return;
}
String[] sects2 = args[0].split(" +");
User p;
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
}
catch (Exception ex)
{
sender.sendMessage("§cThat player does not exist!");
return;
}
sender.sendMessage("Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted."));
} }
} }

View File

@@ -1,6 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import java.util.List;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
@@ -16,12 +15,11 @@ public class Commandnick extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " <target> [nickname]"); throw new NotEnoughArgumentsException();
return;
} }
if (args.length > 1) if (args.length > 1)
@@ -32,41 +30,20 @@ public class Commandnick extends EssentialsCommand
return; return;
} }
List<Player> matches = server.matchPlayer(args[0]); setOthersNickname(server, user, args);
if (matches.isEmpty())
{
user.sendMessage("§cThat player does not exist.");
return; return;
} }
User target = User.get(matches.get(0));
String nick = args[1];
if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick))
{
target.setDisplayName(target.getName());
parent.saveNickname(target, target.getName());
target.sendMessage("§7You no longer have a nickname.");
}
else
{
user.charge(this);
target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick);
parent.saveNickname(target, nick);
target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7.");
}
user.sendMessage("§7Nickname changed.");
}
else
{
String nick = args[0]; String nick = args[0];
if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick)) if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick))
{ {
user.setDisplayName(user.getName()); user.setDisplayName(user.getName());
parent.saveNickname(user, user.getName()); user.setNickname(null);
user.sendMessage("§7You no longer have a nickname."); user.sendMessage("§7You no longer have a nickname.");
return;
} }
else
{
if (nick.matches("[^a-zA-Z_0-9]")) if (nick.matches("[^a-zA-Z_0-9]"))
{ {
user.sendMessage("§cNicknames must be alphanumeric."); user.sendMessage("§cNicknames must be alphanumeric.");
@@ -75,7 +52,10 @@ public class Commandnick extends EssentialsCommand
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
if (user == p) continue; if (user == p)
{
continue;
}
String dn = p.getDisplayName().toLowerCase(); String dn = p.getDisplayName().toLowerCase();
String n = p.getName().toLowerCase(); String n = p.getName().toLowerCase();
String nk = nick.toLowerCase(); String nk = nick.toLowerCase();
@@ -87,41 +67,37 @@ public class Commandnick extends EssentialsCommand
} }
user.charge(this); user.charge(this);
user.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); user.setDisplayName(ess.getConfiguration().getString("nickname-prefix", "~") + nick);
parent.saveNickname(user, nick); user.setNickname(nick);
user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7."); user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7.");
} }
}
}
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2) if (args.length < 2)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [target] [nickname]"); throw new NotEnoughArgumentsException();
return;
} }
List<Player> matches = server.matchPlayer(args[0]); setOthersNickname(server, sender, args);
if (matches.isEmpty())
}
private void setOthersNickname(Server server, CommandSender sender, String[] args) throws Exception
{ {
sender.sendMessage("That player does not exist."); User target = getPlayer(server, args, 0);
return;
}
User target = User.get(matches.get(0));
String nick = args[1]; String nick = args[1];
if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick))
{ {
target.setDisplayName(target.getName()); target.setDisplayName(target.getName());
parent.saveNickname(target, target.getName()); target.setNickname(null);
target.sendMessage("§7You no longer have a nickname."); target.sendMessage("§7You no longer have a nickname.");
} }
else else
{ {
target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); target.setDisplayName(ess.getSettings().getNicknamePrefix() + nick);
parent.saveNickname(target, nick); target.setNickname(nick);
target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7."); target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7.");
} }
sender.sendMessage("Nickname changed."); sender.sendMessage("Nickname changed.");

View File

@@ -1,11 +1,8 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandpay extends EssentialsCommand public class Commandpay extends EssentialsCommand
@@ -16,27 +13,19 @@ public class Commandpay extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
int amount; double amount = Double.parseDouble(args[1].replaceAll("[^0-9\\.]", ""));
try
{
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
}
catch (Exception ex)
{
user.sendMessage("§cUsage: /" + commandLabel + " [player] [money]");
return;
}
for (Player p : server.matchPlayer(args[0])) for (Player p : server.matchPlayer(args[0]))
{ {
User u = User.get(p); User u = ess.getUser(p);
user.payUser(u, amount); user.payUser(u, amount);
} }
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,13 +12,7 @@ public class Commandping extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User player, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "pong" };
}
@Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception
{ {
player.sendMessage("Pong!"); player.sendMessage("Pong!");
} }

View File

@@ -2,8 +2,6 @@ package com.earth2me.essentials.commands;
import java.io.File; import java.io.File;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
@@ -19,7 +17,7 @@ public class Commandplugin extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
this.server = server; this.server = server;
@@ -69,7 +67,7 @@ public class Commandplugin extends EssentialsCommand
return; return;
case LIST: case LIST:
User.charge(sender, this); charge(sender);
listPlugins(sender); listPlugins(sender);
return; return;
} }
@@ -115,7 +113,9 @@ public class Commandplugin extends EssentialsCommand
{ {
final PluginManager pm = server.getPluginManager(); final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name); final Plugin plugin = pm.getPlugin(name);
if (!plugin.isEnabled()) new Thread(new Runnable() if (!plugin.isEnabled())
{
new Thread(new Runnable()
{ {
public void run() public void run()
{ {
@@ -125,6 +125,7 @@ public class Commandplugin extends EssentialsCommand
} }
} }
}).start(); }).start();
}
sender.sendMessage("§7Plugin enabled."); sender.sendMessage("§7Plugin enabled.");
return true; return true;
} }
@@ -141,7 +142,9 @@ public class Commandplugin extends EssentialsCommand
{ {
final PluginManager pm = server.getPluginManager(); final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name); final Plugin plugin = pm.getPlugin(name);
if (plugin.isEnabled()) new Thread(new Runnable() if (plugin.isEnabled())
{
new Thread(new Runnable()
{ {
public void run() public void run()
{ {
@@ -151,6 +154,7 @@ public class Commandplugin extends EssentialsCommand
} }
} }
}).start(); }).start();
}
sender.sendMessage("§7Plugin disabled."); sender.sendMessage("§7Plugin disabled.");
return true; return true;
} }

View File

@@ -1,32 +1,37 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class Commandpowertool extends EssentialsCommand {
public Commandpowertool() { public class Commandpowertool extends EssentialsCommand
{
public Commandpowertool()
{
super("powertool"); super("powertool");
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
ItemStack is = user.getItemInHand(); ItemStack is = user.getItemInHand();
if (is == null || is.getType() == Material.AIR) { if (is == null || is.getType() == Material.AIR)
{
user.sendMessage("Command can't be attached to air."); user.sendMessage("Command can't be attached to air.");
} }
String command = getFinalArg(args, 0); String command = getFinalArg(args, 0);
if (command != null && !command.isEmpty()) { if (command != null && !command.isEmpty())
user.sendMessage("Command assigned to "+is.getType().toString().toLowerCase().replaceAll("_", " ")); {
} else { user.sendMessage("Command assigned to " + is.getType().toString().toLowerCase().replaceAll("_", " "));
user.sendMessage("Command removed from "+is.getType().toString().toLowerCase().replaceAll("_", " "));
} }
else
{
user.sendMessage("Command removed from " + is.getType().toString().toLowerCase().replaceAll("_", " "));
}
charge(user);
user.setPowertool(is, command); user.setPowertool(is, command);
} }
} }

View File

@@ -1,6 +1,5 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.*;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.IReplyTo; import com.earth2me.essentials.IReplyTo;
import org.bukkit.*; import org.bukkit.*;
@@ -16,19 +15,18 @@ public class Commandr extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("§cUsage: /" + commandLabel + " [message]"); throw new NotEnoughArgumentsException();
return;
} }
String message = getFinalArg(args, 0); String message = getFinalArg(args, 0);
IReplyTo replyTo = sender instanceof Player?User.get((Player)sender):Console.getConsoleReplyTo(); IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
String senderName = sender instanceof Player?((Player)sender).getDisplayName():Console.NAME; String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
CommandSender target = replyTo.getReplyTo(); CommandSender target = replyTo.getReplyTo();
String targetName = target instanceof Player?((Player)target).getDisplayName():Console.NAME; String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
if (target == null) if (target == null)
{ {
@@ -39,10 +37,14 @@ public class Commandr extends EssentialsCommand
sender.sendMessage("[Me -> " + targetName + "] " + message); sender.sendMessage("[Me -> " + targetName + "] " + message);
target.sendMessage("[" + senderName + " -> Me] " + message); target.sendMessage("[" + senderName + " -> Me] " + message);
replyTo.setReplyTo(target); replyTo.setReplyTo(target);
if (target != sender) { if (target != sender)
if (target instanceof Player) { {
User.get((Player)target).setReplyTo(sender); if (target instanceof Player)
} else { {
ess.getUser((Player)target).setReplyTo(sender);
}
else
{
Console.getConsoleReplyTo().setReplyTo(sender); Console.getConsoleReplyTo().setReplyTo(sender);
} }
} }

View File

@@ -14,26 +14,24 @@ public class Commandrealname extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "realnick" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /whois [nickname]"); throw new NotEnoughArgumentsException();
return;
} }
String whois = args[0].toLowerCase(); String whois = args[0].toLowerCase();
user.charge(this); user.charge(this);
for (Player p : server.getOnlinePlayers()) for (Player p : server.getOnlinePlayers())
{ {
User u = User.get(p); User u = ess.getUser(p);
String dn = u.getDisplayName().toLowerCase(); String dn = u.getDisplayName().toLowerCase();
if (!whois.equals(dn) && !whois.equals(parent.getSettings().getNicknamePrefix() + dn) && !whois.equals(u.getName().toLowerCase())) continue; if (!whois.equals(dn)
&& !whois.equals(ess.getSettings().getNicknamePrefix() + dn)
&& !whois.equals(u.getName().toLowerCase()))
{
continue;
}
user.sendMessage(u.getDisplayName() + " is " + u.getName()); user.sendMessage(u.getDisplayName() + " is " + u.getName());
} }
} }

View File

@@ -2,36 +2,20 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandreloadall extends EssentialsCommand public class Commandreloadall extends EssentialsCommand
{ {
public Commandreloadall() public Commandreloadall()
{ {
super("reloadall"); super("reloadall");
} }
@Override @Override
public String[] getTriggers() public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
return new String[] { getName(), "rel", "pr" }; charge(sender);
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
server.reload(); server.reload();
user.sendMessage("§7Reloaded all plugins."); sender.sendMessage("§7Reloaded all plugins.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
server.reload();
sender.sendMessage("Reloaded all plugins.");
} }
} }

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.*;
public class Commandrules extends EssentialsCommand public class Commandrules extends EssentialsCommand
@@ -12,10 +12,10 @@ public class Commandrules extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
for (String m : parent.getLines(user, "rules", "§cThere are no rules specified yet.")) for (String m : ess.getLines(user, "rules", "§cThere are no rules specified yet."))
{ {
user.sendMessage(m); user.sendMessage(m);
} }

View File

@@ -0,0 +1,38 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandseen extends EssentialsCommand
{
public Commandseen()
{
super("seen");
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
try
{
User u = getPlayer(server, args, 0);
sender.sendMessage("Player " + u.getDisplayName() + " is online since" + Util.formatDateDiff(u.getLastLogin()));
}
catch (NoSuchFieldException e)
{
User u = ess.getOfflineUser(args[0]);
if (u == null)
{
return;
}
sender.sendMessage("Player " + u.getDisplayName() + " is offline since" + Util.formatDateDiff(u.getLastLogout()));
}
}
}

View File

@@ -17,60 +17,73 @@ public class Commandsell extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) { if (args.length < 1)
user.sendMessage("§cUsage: /sell [itemname|id|hand] [-][amount]"); {
return; throw new NotEnoughArgumentsException();
} }
ItemStack is; ItemStack is;
if (args[0].equalsIgnoreCase("hand")) { if (args[0].equalsIgnoreCase("hand"))
{
is = user.getItemInHand(); is = user.getItemInHand();
} else { }
else
{
is = ItemDb.get(args[0]); is = ItemDb.get(args[0]);
} }
if(is.getType() == Material.AIR) { if (is.getType() == Material.AIR)
{
throw new Exception("You really tried to sell Air? Put an item in your hand."); throw new Exception("You really tried to sell Air? Put an item in your hand.");
} }
int id = is.getTypeId(); int id = is.getTypeId();
int amount = 0; int amount = 0;
if (args.length > 1) { if (args.length > 1)
{
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
if (args[1].startsWith("-")) { if (args[1].startsWith("-"))
{
amount = -amount; amount = -amount;
} }
} }
double worth = Essentials.getWorth().getPrice(is); double worth = Essentials.getWorth().getPrice(is);
boolean stack = args.length > 1 && args[1].endsWith("s"); boolean stack = args.length > 1 && args[1].endsWith("s");
boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); boolean requireStack = ess.getConfiguration().getBoolean("trade-in-stacks-" + id, false);
if (Double.isNaN(worth)) { if (Double.isNaN(worth))
{
throw new Exception("That item cannot be sold to the server."); throw new Exception("That item cannot be sold to the server.");
} }
if (requireStack && !stack) { if (requireStack && !stack)
{
throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc.");
} }
int max = 0; int max = 0;
for (ItemStack s : user.getInventory().getContents()) for (ItemStack s : user.getInventory().getContents())
{ {
if (s == null) { if (s == null)
{
continue; continue;
} }
if (s.getTypeId() != is.getTypeId()) { if (s.getTypeId() != is.getTypeId())
{
continue; continue;
} }
if (s.getDurability() != is.getDurability()) { if (s.getDurability() != is.getDurability())
{
continue; continue;
} }
max += s.getAmount(); max += s.getAmount();
} }
if (stack) { if (stack)
{
amount *= 64; amount *= 64;
} }
if (amount < 1) { if (amount < 1)
{
amount += max; amount += max;
} }
@@ -87,7 +100,7 @@ public class Commandsell extends EssentialsCommand
return; return;
} }
user.charge(this); charge(user);
InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability())); InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability()));
user.updateInventory(); user.updateInventory();
user.giveMoney(worth * amount); user.giveMoney(worth * amount);

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,10 +12,10 @@ public class Commandsethome extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.setHome(); user.setHome(args.length > 0 && args[0].equalsIgnoreCase("default"));
user.charge(this); charge(user);
user.sendMessage("§7Home set."); user.sendMessage("§7Home set.");
} }
} }

View File

@@ -13,14 +13,13 @@ public class Commandsetjail extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); charge(user);
Essentials.getJail().setJail(user.getLocation(), args[0]); Essentials.getJail().setJail(user.getLocation(), args[0]);
user.sendMessage("§7Jail " + args[0] + " has been set"); user.sendMessage("§7Jail " + args[0] + " has been set");

View File

@@ -14,15 +14,14 @@ public class Commandsetwarp extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /setwarp [warp name]"); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); charge(user);
Location loc = user.getLocation(); Location loc = user.getLocation();
Essentials.getWarps().setWarp(args[0], loc); Essentials.getWarps().setWarp(args[0], loc);
user.sendMessage("§7Warp set."); user.sendMessage("§7Warp set.");

View File

@@ -15,16 +15,16 @@ public class Commandsetworth extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if(args.length < 2) if (args.length < 2)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " [itemname|id] [price]"); throw new NotEnoughArgumentsException();
return;
} }
ItemStack stack = ItemDb.get(args[0]); ItemStack stack = ItemDb.get(args[0]);
charge(user);
Essentials.getWorth().setPrice(stack, Double.parseDouble(args[1])); Essentials.getWorth().setPrice(stack, Double.parseDouble(args[1]));
user.charge(this);
user.sendMessage("§7Worth value set"); user.sendMessage("§7Worth value set");
} }
} }

View File

@@ -1,8 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@@ -18,25 +16,27 @@ public class Commandspawner extends EssentialsCommand
} }
@Override @Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [mob]"); throw new NotEnoughArgumentsException();
return;
} }
Block target = user.getTarget().getTargetBlock(); Block target = user.getTarget().getTargetBlock();
if (target.getType() != Material.MOB_SPAWNER) if (target.getType() != Material.MOB_SPAWNER)
{
throw new Exception("Target block must be a mob spawner."); throw new Exception("Target block must be a mob spawner.");
}
charge(user);
try try
{ {
user.charge(this);
((CreatureSpawner)target).setCreatureType(CreatureType.fromName(args[0])); ((CreatureSpawner)target).setCreatureType(CreatureType.fromName(args[0]));
} }
catch (Throwable ex) catch (Throwable ex)
{ {
throw new Exception("Error while changing mob spawner.");
} }
} }
} }

View File

@@ -29,22 +29,12 @@ public class Commandspawnmob extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[]
{
getName(), "mob"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /spawnmob [mob]<:data><,mount<:data>> <quantity>"); throw new NotEnoughArgumentsException();
user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep Wolf"); //TODO: user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep Wolf");
return;
} }
@@ -53,16 +43,19 @@ public class Commandspawnmob extends EssentialsCommand
String mobType = parts[0]; String mobType = parts[0];
mobType = mobType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mobType); mobType = mobType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mobType);
String mobData = null; String mobData = null;
if (parts.length == 2) { if (parts.length == 2)
{
mobData = parts[1]; mobData = parts[1];
} }
String mountType = null; String mountType = null;
String mountData = null; String mountData = null;
if (mountparts.length > 1) { if (mountparts.length > 1)
{
parts = mountparts[1].split(":"); parts = mountparts[1].split(":");
mountType = parts[0]; mountType = parts[0];
mountType = mountType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mountType); mountType = mountType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mountType);
if (parts.length == 2) { if (parts.length == 2)
{
mountData = parts[1]; mountData = parts[1];
} }
} }
@@ -79,7 +72,7 @@ public class Commandspawnmob extends EssentialsCommand
user.sendMessage("Invalid mob type."); user.sendMessage("Invalid mob type.");
return; return;
} }
user.charge(this); charge(user);
WorldServer world = ((CraftWorld)user.getWorld()).getHandle(); WorldServer world = ((CraftWorld)user.getWorld()).getHandle();
try try
{ {
@@ -90,11 +83,14 @@ public class Commandspawnmob extends EssentialsCommand
user.sendMessage("Unable to spawn mob."); user.sendMessage("Unable to spawn mob.");
return; return;
} }
int[] ignore = {8, 9}; int[] ignore =
{
8, 9
};
Location loc = (new TargetBlock(user, 300, 0.2, ignore)).getTargetBlock().getLocation(); Location loc = (new TargetBlock(user, 300, 0.2, ignore)).getTargetBlock().getLocation();
Block block = user.getWorld().getBlockAt(loc); Block block = user.getWorld().getBlockAt(loc);
while (!(block.getType() == Material.AIR || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER )) while (!(block.getType() == Material.AIR || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER))
{ {
loc.setY(loc.getY() + 1); loc.setY(loc.getY() + 1);
block = user.getWorld().getBlockAt(loc); block = user.getWorld().getBlockAt(loc);
@@ -123,17 +119,19 @@ public class Commandspawnmob extends EssentialsCommand
spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle()); spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle());
world.addEntity(spawnedMount.getHandle()); world.addEntity(spawnedMount.getHandle());
} }
if (mobData != null) { if (mobData != null)
{
changeMobData(mob.name, spawnedMob, mobData, user); changeMobData(mob.name, spawnedMob, mobData, user);
} }
if (spawnedMount != null && mountData != null) { if (spawnedMount != null && mountData != null)
{
changeMobData(mobMount.name, spawnedMount, mountData, user); changeMobData(mobMount.name, spawnedMount, mountData, user);
} }
if (args.length == 2) if (args.length == 2)
{ {
int mobCount = Integer.parseInt(args[1]); int mobCount = Integer.parseInt(args[1]);
int serverLimit = Essentials.getSettings().getSpawnMobLimit(); int serverLimit = ess.getSettings().getSpawnMobLimit();
if(mobCount > serverLimit) if (mobCount > serverLimit)
{ {
mobCount = serverLimit; mobCount = serverLimit;
user.sendMessage("Mob quantity limited to server limit"); user.sendMessage("Mob quantity limited to server limit");
@@ -161,10 +159,12 @@ public class Commandspawnmob extends EssentialsCommand
spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle()); spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle());
world.addEntity(spawnedMount.getHandle()); world.addEntity(spawnedMount.getHandle());
} }
if (mobData != null) { if (mobData != null)
{
changeMobData(mob.name, spawnedMob, mobData, user); changeMobData(mob.name, spawnedMob, mobData, user);
} }
if (spawnedMount != null && mountData != null) { if (spawnedMount != null && mountData != null)
{
changeMobData(mobMount.name, spawnedMount, mountData, user); changeMobData(mobMount.name, spawnedMount, mountData, user);
} }
} }
@@ -194,8 +194,10 @@ public class Commandspawnmob extends EssentialsCommand
return s.toUpperCase().charAt(0) + s.toLowerCase().substring(1); return s.toUpperCase().charAt(0) + s.toLowerCase().substring(1);
} }
private void changeMobData(String type, CraftEntity spawned, String data, User user) throws Exception { private void changeMobData(String type, CraftEntity spawned, String data, User user) throws Exception
if ("Slime".equalsIgnoreCase(type)) { {
if ("Slime".equalsIgnoreCase(type))
{
try try
{ {
((CraftSlime)spawned).setSize(Integer.parseInt(data)); ((CraftSlime)spawned).setSize(Integer.parseInt(data));
@@ -205,7 +207,8 @@ public class Commandspawnmob extends EssentialsCommand
throw new Exception("Malformed size."); throw new Exception("Malformed size.");
} }
} }
if ("Sheep".equalsIgnoreCase(type)) { if ("Sheep".equalsIgnoreCase(type))
{
try try
{ {
((CraftSheep)spawned).setColor(DyeColor.valueOf(data.toUpperCase())); ((CraftSheep)spawned).setColor(DyeColor.valueOf(data.toUpperCase()));
@@ -215,16 +218,18 @@ public class Commandspawnmob extends EssentialsCommand
throw new Exception("Malformed color."); throw new Exception("Malformed color.");
} }
} }
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("tamed")) { if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("tamed"))
EntityWolf wolf = ((CraftWolf) spawned).getHandle(); {
EntityWolf wolf = ((CraftWolf)spawned).getHandle();
wolf.d(true); wolf.d(true);
wolf.a((PathEntity) null); wolf.a((PathEntity)null);
wolf.setSitting(true); wolf.setSitting(true);
wolf.health = 20; wolf.health = 20;
wolf.a(user.getName()); wolf.a(user.getName());
wolf.world.a(wolf, (byte) 7); wolf.world.a(wolf, (byte)7);
} }
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("angry")) { if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("angry"))
{
((CraftWolf)spawned).setAngry(true); ((CraftWolf)spawned).setAngry(true);
} }
if ("Creeper".equalsIgnoreCase(type) && data.equalsIgnoreCase("powered")) { if ("Creeper".equalsIgnoreCase(type) && data.equalsIgnoreCase("powered")) {

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,11 +12,11 @@ public class Commandsuicide extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
user.setHealth(0); user.setHealth(0);
user.sendMessage("§cGoodbye Cruel World..."); user.sendMessage("§cGoodbye Cruel World...");
server.broadcastMessage("§7" + user.getDisplayName() + " took their own life" ); server.broadcastMessage("§7" + user.getDisplayName() + " took their own life");
} }
} }

View File

@@ -0,0 +1,52 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtempban extends EssentialsCommand
{
public Commandtempban()
{
super("tempban");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
User p = null;
try
{
p = getPlayer(server, args, 0);
}
catch (NoSuchFieldException ex)
{
p = ess.getOfflineUser(args[0]);
}
if (p == null)
{
sender.sendMessage("§cPlayer " + args[0] + " not found");
}
String time = getFinalArg(args, 1);
long banTimestamp = Util.parseDateDiff(time, true);
p = ess.getUser(server.matchPlayer(args[0]).get(0));
String banReason = "Temporary banned from server for " + Util.formatDateDiff(banTimestamp);
p.setBanReason(banReason);
p.setBanTimeout(banTimestamp);
p.kickPlayer(banReason);
((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage("§cPlayer " + p.getName() + " banned");
Essentials.getStatic().loadBanList();
}
}

View File

@@ -1,8 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
@@ -15,13 +13,12 @@ public class Commandthunder extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /" + commandLabel + " <true/false> [duration]"); throw new NotEnoughArgumentsException();
return;
} }
user.charge(this); user.charge(this);
@@ -33,13 +30,11 @@ public class Commandthunder extends EssentialsCommand
world.setThundering(setThunder ? true : false); world.setThundering(setThunder ? true : false);
world.setThunderDuration(Integer.parseInt(args[1]) * 20); world.setThunderDuration(Integer.parseInt(args[1]) * 20);
user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world for " + args[1] + " seconds"); user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world for " + args[1] + " seconds");
return;
} }
else else
{ {
world.setThundering(setThunder ? true : false); world.setThundering(setThunder ? true : false);
user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world"); user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world");
return;
} }
} }

View File

@@ -15,49 +15,47 @@ public class Commandtime extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
World world = user.getWorld();
long time = world.getTime();
time = time - time % 24000;
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /time [day|night]"); throw new NotEnoughArgumentsException();
return;
} }
if ("day".equalsIgnoreCase(args[0])) World world = user.getWorld();
charge(user);
setWorldTime(world, args[0]);
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
for (World world : server.getWorlds())
{
setWorldTime(world, args[0]);
}
sender.sendMessage("Time set in all worlds.");
}
private void setWorldTime(World world, String timeString) throws Exception
{
long time = world.getTime();
time = time - time % 24000;
if ("day".equalsIgnoreCase(timeString))
{ {
user.charge(this);
world.setTime(time + 24000); world.setTime(time + 24000);
return; return;
} }
if ("night".equalsIgnoreCase(args[0])) if ("night".equalsIgnoreCase(timeString))
{ {
user.charge(this);
world.setTime(time + 37700); world.setTime(time + 37700);
return; return;
} }
throw new Exception("/time only supports day/night."); throw new Exception("/time only supports day/night.");
} }
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
for (World world : server.getWorlds())
{
long time = world.getTime();
time = time - time % 24000;
if (args.length < 1)
{
sender.sendMessage("Usage: /time [day|night]");
return;
}
if ("day".equalsIgnoreCase(args[0])) world.setTime(time + 24000);
else if ("night".equalsIgnoreCase(args[0])) world.setTime(time + 37700);
else throw new Exception("/time only supports day/night.");
}
sender.sendMessage("Time set in all worlds.");
}
} }

View File

@@ -4,6 +4,7 @@ import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtogglejail extends EssentialsCommand public class Commandtogglejail extends EssentialsCommand
@@ -14,55 +15,67 @@ public class Commandtogglejail extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1 || args.length > 2) if (args.length < 1)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); throw new NotEnoughArgumentsException();
return;
} }
User p; User p = getPlayer(server, args, 0);
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
}
catch (Exception ex)
{
sender.sendMessage("§cThat player does not exist.");
return;
}
if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) if (p.isAuthorized("essentials.jail.exempt"))
{ {
sender.sendMessage("§cYou may not jail that person"); sender.sendMessage("§cYou may not jail that person");
return; return;
} }
if (args.length == 2 && !p.isJailed()) { if (args.length >= 2 && !p.isJailed())
User.charge(sender, this); {
sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); charge(sender);
p.setJailed(true);
p.sendMessage("§7You have been jailed"); p.sendMessage("§7You have been jailed");
p.currentJail = null; p.setJail(null);
Essentials.getJail().sendToJail(p, args[1]); Essentials.getJail().sendToJail(p, args[1]);
p.currentJail = (args[1]); p.setJail(args[1]);
long timeDiff = 0;
if (args.length > 2)
{
String time = getFinalArg(args, 2);
timeDiff = Util.parseDateDiff(time, true);
p.setJailTimeout(timeDiff);
}
sender.sendMessage("§7Player " + p.getName() + " jailed" + (timeDiff > 0 ? " for" + Util.formatDateDiff(timeDiff) : "") + ".");
return; return;
} }
if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.getJail()))
sender.sendMessage("§cPerson is already in jail "+ p.currentJail); {
sender.sendMessage("§cPerson is already in jail " + p.getJail());
return; return;
} }
if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (args.length >= 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.getJail()))
if (!p.isJailed()) { {
sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); String time = getFinalArg(args, 2);
long timeDiff = Util.parseDateDiff(time, true);
p.setJailTimeout(timeDiff);
sender.sendMessage("Jail time extend to " + Util.formatDateDiff(timeDiff));
return; return;
} }
sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed."));
if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.getJail())))
{
if (!p.isJailed())
{
throw new NotEnoughArgumentsException();
}
p.setJailed(false);
p.setJailTimeout(0);
p.sendMessage("§7You have been released"); p.sendMessage("§7You have been released");
p.currentJail = ""; p.setJail(null);
p.teleportBack(); p.getTeleport().back();
sender.sendMessage("§7Player " + p.getName() + " unjailed.");
} }
} }
} }

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -14,13 +13,13 @@ public class Commandtop extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
int topX = user.getLocation().getBlockX(); int topX = user.getLocation().getBlockX();
int topZ = user.getLocation().getBlockZ(); int topZ = user.getLocation().getBlockZ();
int topY = user.getWorld().getHighestBlockYAt(topX, topZ); int topY = user.getWorld().getHighestBlockYAt(topX, topZ);
user.charge(this); charge(user);
user.teleportTo(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName()); user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName());
user.sendMessage("§7Teleporting to top."); user.sendMessage("§7Teleporting to top.");
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -14,48 +13,51 @@ public class Commandtp extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
switch (args.length) switch (args.length)
{ {
case 0: case 0:
user.sendMessage("§cUsage: /" + commandLabel + " <target> [to-player]"); throw new NotEnoughArgumentsException();
return;
case 1: case 1:
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
user.teleportCooldown(); if (!p.isTeleportEnabled())
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); {
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
user.sendMessage("§7Teleporting..."); user.sendMessage("§7Teleporting...");
user.canAfford(this); user.canAfford(this);
user.teleportTo(p, this.getName()); user.getTeleport().teleport(p, this.getName());
break; break;
case 2: case 2:
if (!user.isAuthorized("essentials.tpohere")) throw new Exception("You need access to /tpohere to teleport other players."); if (!user.isAuthorized("essentials.tpohere"))
{
throw new Exception("You need access to /tpohere to teleport other players.");
}
user.sendMessage("§7Teleporting..."); user.sendMessage("§7Teleporting...");
user.charge(this); charge(user);
User target = getPlayer(server, args, 0); User target = getPlayer(server, args, 0);
User toPlayer = getPlayer(server, args, 1); User toPlayer = getPlayer(server, args, 1);
target.teleportToNow(toPlayer); target.getTeleport().now(toPlayer);
target.sendMessage("§7" + user.getDisplayName() + "§7 teleported you to " + toPlayer.getDisplayName() + "§7."); target.sendMessage("§7" + user.getDisplayName() + "§7 teleported you to " + toPlayer.getDisplayName() + "§7.");
break; break;
} }
} }
@Override @Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 2) if (args.length < 2)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [target] [to-player]"); throw new NotEnoughArgumentsException();
return;
} }
sender.sendMessage("§7Teleporting..."); sender.sendMessage("§7Teleporting...");
User target = getPlayer(server, args, 0); User target = getPlayer(server, args, 0);
User toPlayer = getPlayer(server, args, 1); User toPlayer = getPlayer(server, args, 1);
target.teleportToNow(toPlayer); target.getTeleport().now(toPlayer);
target.sendMessage("§7{Console}§7 teleported you to " + toPlayer.getDisplayName() + "§7."); target.sendMessage("§7{Console}§7 teleported you to " + toPlayer.getDisplayName() + "§7.");
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,19 +12,20 @@ public class Commandtpa extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception public void run(Server server, User player, String commandLabel, String[] args) throws Exception
{ {
if(args.length < 1) if (args.length < 1)
{ {
player.sendMessage("§cUsage: /tpa [playername]"); throw new NotEnoughArgumentsException();
return;
} }
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
player.charge(this); player.charge(this);
parent.tpcRequests.put(p, player); p.requestTeleport(player, false);
parent.tpcHere.put(p, false);
p.sendMessage("§c" + player.getDisplayName() + "§c has requested to teleport to you."); p.sendMessage("§c" + player.getDisplayName() + "§c has requested to teleport to you.");
p.sendMessage("§7To teleport, type §c/tpaccept§7."); p.sendMessage("§7To teleport, type §c/tpaccept§7.");
p.sendMessage("§7To deny this request, type §c/tpdeny§7."); p.sendMessage("§7To deny this request, type §c/tpdeny§7.");

View File

@@ -1,9 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandtpaccept extends EssentialsCommand public class Commandtpaccept extends EssentialsCommand
@@ -14,27 +12,29 @@ public class Commandtpaccept extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
User p = parent.tpcRequests.get(user); User p = user.getTeleportRequest();
if (p == null) throw new Exception("You do not have a pending request."); if (p == null)
parent.tpcRequests.remove(user); {
throw new Exception("You do not have a pending request.");
if (parent.tpcHere.get(user)) }
if (user.isTeleportRequestHere())
{ {
user.teleportCooldown();
user.canAfford(this); user.canAfford(this);
user.sendMessage("§7Teleport request accepted."); user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted."); p.sendMessage("§7Teleport request accepted.");
user.teleportTo(p, this.getName()); user.getTeleport().teleport(p, this.getName());
} }
else else
{ {
user.canAfford(this); user.canAfford(this);
user.sendMessage("§7Teleport request accepted."); user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted."); p.sendMessage("§7Teleport request accepted.");
p.teleportTo(user, this.getName()); user.getTeleport().teleport(user, this.getName());
} }
user.requestTeleport(null, false);
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,19 +12,20 @@ public class Commandtpahere extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /tpahere [playername]"); throw new NotEnoughArgumentsException();
return;
} }
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
user.charge(this); user.charge(this);
parent.tpcRequests.put(p, user); p.requestTeleport(user, true);
parent.tpcHere.put(p, true);
p.sendMessage("§c" + user.getDisplayName() + "§c has requested that you teleport to him/her."); p.sendMessage("§c" + user.getDisplayName() + "§c has requested that you teleport to him/her.");
p.sendMessage("§7To teleport, type §c/tpaccept§7."); p.sendMessage("§7To teleport, type §c/tpaccept§7.");
user.sendMessage("§7Request sent to " + p.getDisplayName() + "§c."); user.sendMessage("§7Request sent to " + p.getDisplayName() + "§c.");

View File

@@ -1,8 +1,8 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -14,31 +14,41 @@ public class Commandtpall extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.charge(this); if (sender instanceof Player)
user.sendMessage("§7Teleporting...");
for (Player player : server.getOnlinePlayers()) {
User p = User.get(player);
if (p == user) {
continue;
}
p.teleportToNow(user);
}
}
else
{ {
charge(sender);
teleportAllPlayers(server, sender, ess.getUser(sender));
return;
}
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
user.charge(this); charge(sender);
user.sendMessage("§7Teleporting..."); teleportAllPlayers(server, sender, p);
for (Player player : server.getOnlinePlayers()) { }
User u = User.get(player);
if (p == u) { private void teleportAllPlayers(Server server, CommandSender sender, User p)
{
sender.sendMessage("§7Teleporting all players...");
for (Player player : server.getOnlinePlayers())
{
User u = ess.getUser(player);
if (p == u)
{
continue; continue;
} }
u.teleportToNow(p); try
{
u.getTeleport().now(p);
}
catch (Exception ex)
{
sender.sendMessage("Error: "+ex.getMessage());
} }
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,25 +12,26 @@ public class Commandtpdeny extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
User p = parent.tpcRequests.get(user); User p = user.getTeleportRequest();
if (p == null) throw new Exception("You do not have a pending request."); if (p == null)
parent.tpcRequests.remove(user); {
throw new Exception("You do not have a pending request.");
}
if (parent.tpcHere.get(user)) if (user.isTeleportRequestHere())
{ {
user.charge(this); user.charge(this);
user.sendMessage("§7Teleport request denied."); user.sendMessage("§7Teleport request denied.");
p.sendMessage("§7Teleport request denied."); p.sendMessage("§7Teleport request denied.");
parent.tpcHere.remove(user);
} }
else else
{ {
user.charge(this); user.charge(this);
user.sendMessage("§7Teleport request denied."); user.sendMessage("§7Teleport request denied.");
p.sendMessage("§7Teleport request denied."); p.sendMessage("§7Teleport request denied.");
parent.tpcRequests.remove(user);
} }
user.requestTeleport(null, false);
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,22 +12,15 @@ public class Commandtphere extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[]
{
getName(), "telehere", "s"
};
}
@Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception
{ {
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); if (!p.isTeleportEnabled())
player.charge(this); {
p.teleportTo(player); throw new Exception(p.getDisplayName() + " has teleportation disabled.");
player.sendMessage("§7Teleporting..."); }
p.getTeleport().teleport(user, commandLabel);
user.sendMessage("§7Teleporting...");
p.sendMessage("§7Teleporting..."); p.sendMessage("§7Teleporting...");
} }
} }

View File

@@ -1,9 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandtpo extends EssentialsCommand public class Commandtpo extends EssentialsCommand
@@ -14,21 +12,17 @@ public class Commandtpo extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§c Usage: /tpo [playername]"); throw new NotEnoughArgumentsException();
}
else
{
//Just basically the old tp command
User p = getPlayer(server, args, 0);
user.teleportCooldown();
user.charge(this);
user.teleportToNow(p);
user.sendMessage("§7Teleporting...");
} }
//Just basically the old tp command
User p = getPlayer(server, args, 0);
charge(user);
user.getTeleport().now(p);
user.sendMessage("§7Teleporting...");
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,19 +12,17 @@ public class Commandtpohere extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§c Usage: /tpohere [playername]"); throw new NotEnoughArgumentsException();
} }
else
{
//Just basically the old tphere command //Just basically the old tphere command
User p = getPlayer(server, args, 0); User p = getPlayer(server, args, 0);
user.charge(this); charge(user);
p.teleportToNow(user); p.getTeleport().now(user);
user.sendMessage("§7Teleporting..."); user.sendMessage("§7Teleporting...");
} }
}
} }

View File

@@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -14,29 +13,19 @@ public class Commandtppos extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[]
{
getName(), "tpp"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 3) if (args.length < 3)
{ {
user.sendMessage("§cUsage: /tppos [x] [y] [z]"); throw new NotEnoughArgumentsException();
return;
} }
int x = Integer.parseInt(args[0]); int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]); int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]); int z = Integer.parseInt(args[2]);
Location l = new Location(user.getWorld(),x,y,z); Location l = new Location(user.getWorld(), x, y, z);
user.canAfford(this); user.canAfford(this);
user.teleportCooldown();
user.sendMessage("§7Teleporting..."); user.sendMessage("§7Teleporting...");
user.teleportTo(user.getSafeDestination(l), this.getName()); user.getTeleport().teleport(l, this.getName());
} }
} }

View File

@@ -1,7 +1,6 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
@@ -13,9 +12,9 @@ public class Commandtptoggle extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
user.charge(this); charge(user);
user.sendMessage("§7Teleportation " + (user.toggleTeleEnabled() ? "enabled." : "disabled.")); user.sendMessage("§7Teleportation " + (user.toggleTeleportEnabled() ? "enabled." : "disabled."));
} }
} }

View File

@@ -3,8 +3,9 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.TreeType; import org.bukkit.TreeType;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtree extends EssentialsCommand public class Commandtree extends EssentialsCommand
{ {
@@ -14,13 +15,12 @@ public class Commandtree extends EssentialsCommand
} }
@Override @Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{ {
Object tree = new Object(); Object tree = new Object();
if (args.length < 1) if (args.length < 1)
{ {
user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); throw new NotEnoughArgumentsException();
return;
} }
else if (args[0].equalsIgnoreCase("birch")) else if (args[0].equalsIgnoreCase("birch"))
{ {
@@ -36,8 +36,7 @@ public class Commandtree extends EssentialsCommand
} }
else else
{ {
user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); throw new NotEnoughArgumentsException();
return;
} }
double x = user.getLocation().getX(); double x = user.getLocation().getX();
@@ -46,12 +45,24 @@ public class Commandtree extends EssentialsCommand
// offset tree in direction player is facing // offset tree in direction player is facing
int r = (int)user.getCorrectedYaw(); int r = (int)user.getCorrectedYaw();
if (r < 68 || r > 292) x -= 3.0D; // north if (r < 68 || r > 292) // north
else if (r > 112 && r < 248) x += 3.0D; // south {
if (r > 22 && r < 158) z -= 3.0D; // east x -= 3.0D;
else if (r > 202 && r < 338) z += 3.0D; // west }
else if (r > 112 && r < 248) // south
{
x += 3.0D;
}
if (r > 22 && r < 158) // east
{
z -= 3.0D;
}
else if (r > 202 && r < 338) // west
{
z += 3.0D;
}
Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); Location safeLocation = Util.getSafeDestination(new Location(user.getWorld(), x, y, z));
boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree);
if (success) if (success)
{ {
@@ -59,6 +70,8 @@ public class Commandtree extends EssentialsCommand
user.sendMessage("§7Tree spawned."); user.sendMessage("§7Tree spawned.");
} }
else else
{
user.sendMessage("§cTree generation failure. Try again on grass or dirt."); user.sendMessage("§cTree generation failure. Try again on grass or dirt.");
} }
}
} }

View File

@@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
public class Commandunban extends EssentialsCommand public class Commandunban extends EssentialsCommand
@@ -14,22 +13,15 @@ public class Commandunban extends EssentialsCommand
} }
@Override @Override
public String[] getTriggers() public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "pardon" };
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{ {
if (args.length < 1) if (args.length < 1)
{ {
sender.sendMessage("Usage: /" + commandLabel + " [player]"); throw new NotEnoughArgumentsException();
return;
} }
((CraftServer)server).getHandle().b(args[0]); ((CraftServer)server).getHandle().b(args[0]);
sender.sendMessage("Unbanned player."); sender.sendMessage("Unbanned player.");
Essentials.getStatic().loadBanList(); ess.loadBanList();
} }
} }

Some files were not shown because too many files have changed in this diff Show More