This commit is contained in:
ZeroEpoch1969 2019-12-15 22:31:47 -07:00
parent 3b51b23ac2
commit e7881f72a8
No known key found for this signature in database
GPG key ID: A7BAB4E14F089CF3
83 changed files with 169 additions and 5473 deletions

View file

@ -1,45 +0,0 @@
---
name: Help!
about: Encountered a problem with EssentialsX? Not sure how to fix it?
---
<!-- EssentialsX help guide
Don't write inside the arrows as they will be hidden when you post your issue.
Want faster support? Come join our Discord server to get help sooner:
https://discord.gg/F7gexAQ
If you're happy to wait (or you were sent here from Discord), read on:
1. Fill out the template.
This will help us understand what problem you've encountered and help us
find a solution.
2. Check the Common Issues page.
Read through the wiki page to see if you've encountered a regular issue:
https://essentialsx.github.io/#/Common-Issues
3. Delete this line and all above lines before posting your issue! -->
### Information
Full output of `/ess version`:
<!-- Replace this with the command output -->
**Server log:** <!-- Upload `logs/latest.log` to https://gist.github.com/ -->
**EssentialsX config** <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/ -->
### Help request
**Problem**
<!-- What problem did you encounter? -->
**What I have tried**
<!-- What have you tried so far? -->
**Screenshots**
<!-- If relevant, include any screenshots here. -->

View file

@ -1,58 +0,0 @@
---
name: Report a bug
about: Report an EssentialsX bug. Only use this if you're 100% sure there's something wrong with EssentialsX - otherwise, try "Help!".
---
<!-- EssentialsX bug reporting guide
Don't put anything inside this block, as it won't be included in the issue.
If you are reporting a bug, please follow the following steps:
1. Fill out the template in full.
Run the commands in the console. Don't just put "latest" as a version,
or we will ignore it.
2. When linking files, do not attach them to the post!
Copy and paste any logs into https://gist.github.com/, then paste a
link to them in the relevant parts of the template. Avoid using
Hastebin or Pastebin, as this makes providing support more difficult.
**DO NOT drag files into this box!**
3. If you are reporting a performance issue, please include a link to a
Timings and/or profiler report.
4. If you are reporting a bug with commands or something else in-game,
please include screenshots to help us diagnose the problem.
5. Make sure not to write between the arrows, as anything there will be
hidden.
6. Delete this line and all above lines before posting your issue! -->
### Information
**Full output of `/ess version`**:
```
<!-- Run the command in your console, and copy and paste the whole output here -->
```
**Server log**: <!-- Upload `logs/latest.log` to https://gist.github.com/, replace this with link -->
**EssentialsX config**: <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/, replace this with link -->
### Details
**Description**
<!-- Replace this with a brief summary of the bug. -->
**Steps to reproduce**
<!-- Replace this with exactly what you did to cause the bug. -->
**Expected behavior**
<!-- Replace this with what you expected to happen. -->
**Screenshots**
<!-- Replace this with screenshots, if necessary. -->

View file

@ -1,45 +0,0 @@
---
name: Request a feature
about: Suggest a feature you want to see in EssentialsX!
---
<!-- EssentialsX feature request guide
Fill out the template. Don't write inside the arrows as they will be hidden
when you post your issue.
Not sure if your feature fits in EssentialsX? Feel free to ask on our Discord
server: https://discord.gg/F7gexAQ
If you have a feature suggestion for EssentialsX, read the following tips:
1. Fill out the template.
This will help us understand what you're requesting and why you want us
to add it.
2. Keep it simple.
Make sure it's easy to understand what you're requesting. A good way is
to keep it to one request per GitHub issue, as we can then easily track
feature requests.
3. Check whether it has already been asked or added.
You can search the issue tracker to see if your feature has already been
requested at https://github.com/EssentialsX/Essentials/issues. You can
also check the wiki at https://essentialsx.github.io/ to see if the
feature was recently added.
4. Ask yourself: "Does this belong in EssentialsX?"
There are lots of features that we reject because most servers won't
need or use them. If your feature is very specific or already exists in
another plugin, it might not be a good fit for EssentialsX.
5. Delete this line and all above lines before posting your issue! -->
### Feature request
**Feature description**
<!-- What feature are you suggesting? -->
**How the feature is useful**
<!-- How is the feature useful to players, server owners and/or developers? -->

View file

@ -14,6 +14,14 @@
<build>
<finalName>EssentialsX-${full.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@ -72,7 +80,7 @@
<version>2.17.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<!--<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8_R1Provider</artifactId>
<version>2.17.1</version>
@ -95,7 +103,7 @@
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependency>-->
<dependency>
<groupId>net.ess3</groupId>
<artifactId>LegacyProvider</artifactId>
@ -114,5 +122,10 @@
<version>2.17.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.rayzr522</groupId>
<artifactId>jsonmessage</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>

View file

@ -48,8 +48,8 @@ import net.ess3.nms.legacy.LegacySpawnerProvider;
import net.ess3.nms.refl.ReflSpawnEggProvider;
import net.ess3.nms.updatedmeta.BasePotionDataProvider;
import net.ess3.nms.updatedmeta.BlockMetaSpawnerProvider;
import net.ess3.nms.v1_8_R1.v1_8_R1SpawnerProvider;
import net.ess3.nms.v1_8_R2.v1_8_R2SpawnerProvider;
//import net.ess3.nms.v1_8_R1.v1_8_R1SpawnerProvider;
//import net.ess3.nms.v1_8_R2.v1_8_R2SpawnerProvider;
import net.ess3.providers.ProviderFactory;
import org.bukkit.Bukkit;
import org.bukkit.Server;
@ -145,7 +145,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
i18n.onEnable();
i18n.updateLocale("en");
Console.setInstance(this);
LOGGER.log(Level.INFO, tl("usingTempFolderForTesting"));
LOGGER.log(Level.INFO, dataFolder.toString());
settings = new Settings(this);
@ -231,8 +231,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
spawnerProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
BlockMetaSpawnerProvider.class,
v1_8_R2SpawnerProvider.class,
v1_8_R1SpawnerProvider.class,
//v1_8_R2SpawnerProvider.class,
//v1_8_R1SpawnerProvider.class,
LegacySpawnerProvider.class
), "mob spawner").getProvider();
spawnEggProvider = new ProviderFactory<>(getLogger(),

View file

@ -0,0 +1,79 @@
package com.earth2me.essentials;
import com.earth2me.essentials.User;
import com.google.common.base.Function;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
public class TFMHandler
{
private static Logger logger;
private static Function<Player, Boolean> adminProvider;
public static void setLogger(Logger logger)
{
TFMHandler.logger = logger;
}
public static Plugin getTFM()
{
final Plugin tfm = Bukkit.getPluginManager().getPlugin("TotalFreedomMod");
if (tfm == null)
{
logger.warning("Could not resolve plugin: TotalFreedomMod");
}
return tfm;
}
public boolean isAdmin(User user)
{
return isAdmin(user.getBase());
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
public boolean isAdmin(Player player)
{
if (adminProvider == null)
{
final Plugin tfm = getTFM();
if (tfm == null)
{
return false;
}
Object provider = null;
for (RegisteredServiceProvider<?> serv : Bukkit.getServicesManager().getRegistrations(tfm))
{
if (Function.class.isAssignableFrom(serv.getService()))
{
provider = serv.getProvider();
}
}
if (provider == null)
{
warning("Could not obtain admin service provider!");
return false;
}
adminProvider = (Function<Player, Boolean>)provider;
}
return adminProvider.apply(player);
}
public static void warning(String warning)
{
logger.warning(warning);
}
public static void info(String info)
{
logger.info(info);
}
}

View file

@ -17,7 +17,7 @@ public class Commandafk extends EssentialsCommand {
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
if (args.length > 0 && user.isAuthorized("essentials.afk.others")) {
if (args.length > 0 && getTFMHandler().isAdmin(user)) {
User afkUser = user; // if no player found, but message specified, set command executor to target user
String message;
try {
@ -80,7 +80,7 @@ public class Commandafk extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.afk.others")) {
if (args.length == 1 && getTFMHandler().isAdmin(user)) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -27,8 +27,7 @@ public class Commandclearinventory extends EssentialsCommand {
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
parseCommand(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.clearinventory.others"),
user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple"));
parseCommand(server, user.getSource(), commandLabel, args, getTFMHandler().isAdmin(user), getTFMHandler().isAdmin(user));
}
@Override
@ -150,10 +149,10 @@ public class Commandclearinventory extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (user.isAuthorized("essentials.clearinventory.others")) {
if (getTFMHandler().isAdmin(user)) {
if (args.length == 1) {
List<String> options = getPlayers(server, user);
if (user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")) {
if (getTFMHandler().isAdmin(user)) {
// Assume that nobody will have the 'all' permission without the 'others' permission
options.add("*");
}

View file

@ -35,7 +35,7 @@ public class Commanddelhome extends EssentialsCommand {
expandedArg = args;
}
if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others"))) {
if (expandedArg.length > 1 && (user == null || getTFMHandler().isAdmin(user))) {
user = getPlayer(server, expandedArg, 0, true, true);
name = expandedArg[1];
} else if (user == null) {
@ -55,7 +55,7 @@ public class Commanddelhome extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
User user = ess.getUser(sender.getPlayer());
boolean canDelOthers = (user == null || user.isAuthorized("essentials.delhome.others"));
boolean canDelOthers = (user == null || getTFMHandler().isAdmin(user));
if (args.length == 1) {
if (canDelOthers) {

View file

@ -13,7 +13,7 @@ public class Commandenderchest extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length > 0 && user.isAuthorized("essentials.enderchest.others")) {
if (args.length > 0 && getTFMHandler().isAdmin(user)) {
final User invUser = getPlayer(server, user, args, 0);
user.getBase().closeInventory();
user.getBase().openInventory(invUser.getBase().getEnderChest());
@ -28,7 +28,7 @@ public class Commandenderchest extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.enderchest.others")) {
if (args.length == 1 && getTFMHandler().isAdmin(user)) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -25,25 +25,25 @@ public class Commandexp extends EssentialsCommand {
if (args.length == 0) {
showExp(user.getSource(), user);
} else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) {
if (args.length == 3 && getTFMHandler().isAdmin(user)) {
expMatch(server, user.getSource(), args[1], args[2], false);
} else {
setExp(user.getSource(), user, args[1], false);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) {
if (args.length == 3 && getTFMHandler().isAdmin(user)) {
expMatch(server, user.getSource(), args[1], args[2], true);
} else {
setExp(user.getSource(), user, args[1], true);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.take.others")) {
if (args.length == 3 && getTFMHandler().isAdmin(user)) {
expMatch(server, user.getSource(), args[1], "-" + args[2], true);
} else {
setExp(user.getSource(), user, "-" + args[1], true);
}
} else if (args.length < 3 && args[0].equalsIgnoreCase("reset") && user.isAuthorized("essentials.exp.reset")) {
if (args.length == 2 && user.isAuthorized("essentials.exp.reset.others")) {
if (args.length == 2 && getTFMHandler().isAdmin(user)) {
expMatch(server, user.getSource(), args[1], "0", false);
} else {
setExp(user.getSource(), user, "0", false);
@ -186,12 +186,12 @@ public class Commandexp extends EssentialsCommand {
} else {
return Collections.emptyList();
}
} else if (args[0].equalsIgnoreCase("show") && user.isAuthorized("essentials.exp.others")) {
} else if (args[0].equalsIgnoreCase("show") && getTFMHandler().isAdmin(user)) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
} else if (args.length == 3 && (args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set.others")) || (args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give.others"))) {
} else if (args.length == 3 && (args[0].equalsIgnoreCase("set") && getTFMHandler().isAdmin(user)) || (args[0].equalsIgnoreCase("give") && getTFMHandler().isAdmin(user))) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -39,7 +39,7 @@ public class Commandgamemode extends EssentialsCommand {
GameMode gameMode;
if (args.length == 0) {
gameMode = matchGameMode(commandLabel);
} else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) {
} else if (args.length > 1 && args[1].trim().length() > 2 && getTFMHandler().isAdmin(user)) {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[1]);
return;
@ -47,7 +47,7 @@ public class Commandgamemode extends EssentialsCommand {
try {
gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH));
} catch (NotEnoughArgumentsException e) {
if (user.isAuthorized("essentials.gamemode.others")) {
if (getTFMHandler().isAdmin(user)) {
gameMode = matchGameMode(commandLabel);
gamemodeOtherPlayers(server, user.getSource(), gameMode, args[0]);
return;
@ -148,12 +148,12 @@ public class Commandgamemode extends EssentialsCommand {
isDirectGamemodeCommand = false;
}
if (args.length == 1) {
if (user.isAuthorized("essentials.gamemode.others") && isDirectGamemodeCommand) {
if (getTFMHandler().isAdmin(user) && isDirectGamemodeCommand) {
return getPlayers(server, user);
} else {
return STANDARD_OPTIONS;
}
} else if (args.length == 2 && user.isAuthorized("essentials.gamemode.others") && !isDirectGamemodeCommand) {
} else if (args.length == 2 && getTFMHandler().isAdmin(user) && !isDirectGamemodeCommand) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -78,7 +78,7 @@ public class Commandmail extends EssentialsCommand {
return;
}
if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) {
if (!user.isAuthorized("essentials.mail.sendall")) {
if (!getTFMHandler().isAdmin(user)) {
throw new Exception(tl("noPerm", "essentials.mail.sendall"));
}
ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(),
@ -156,7 +156,7 @@ public class Commandmail extends EssentialsCommand {
if (user.isAuthorized("essentials.mail.send")) {
options.add("send");
}
if (user.isAuthorized("essentials.mail.sendall")) {
if (getTFMHandler().isAdmin(user)) {
options.add("sendall");
}
return options;

View file

@ -32,7 +32,7 @@ public class Commandmsg extends EssentialsLoopCommand {
throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced"));
}
message = FormatUtil.formatMessage(user, "essentials.msg", message);
canWildcard = user.isAuthorized("essentials.msg.multiple");
canWildcard = getTFMHandler().isAdmin(user);
} else {
message = FormatUtil.replaceFormat(message);
canWildcard = true;

View file

@ -29,7 +29,7 @@ public class Commandnick extends EssentialsLoopCommand {
throw new Exception(tl("nickDisplayName"));
}
if (args.length > 1 && user.isAuthorized("essentials.nick.others")) {
if (args.length > 1 && getTFMHandler().isAdmin(user)) {
final String[] nickname = formatNickname(user, args[1]).split(" ");
loopOfflinePlayers(server, user.getSource(), false, true, args[0], nickname);
user.sendMessage(tl("nickChanged"));
@ -124,7 +124,7 @@ public class Commandnick extends EssentialsLoopCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.nick.others")) {
if (args.length == 1 && getTFMHandler().isAdmin(user)) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -45,7 +45,7 @@ public class Commandptime extends EssentialsCommand {
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.ptime.others")) {
if (user != null && (!users.contains(user) || users.size() > 1) && !getTFMHandler().isAdmin(user)) {
user.sendMessage(tl("pTimeOthersPermission"));
return;
}
@ -192,7 +192,7 @@ public class Commandptime extends EssentialsCommand {
if (args.length == 1) {
return Lists.newArrayList("get", "reset", "sunrise", "day", "morning", "noon", "afternoon", "sunset", "night", "midnight");
} else if (args.length == 2 && (getAliases.contains(args[0]) || user == null || user.isAuthorized("essentials.ptime.others"))) {
} else if (args.length == 2 && (getAliases.contains(args[0]) || user == null || getTFMHandler().isAdmin(user))) {
return getPlayers(server, sender);
} else {
return Collections.emptyList();

View file

@ -53,7 +53,7 @@ public class Commandpweather extends EssentialsCommand {
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.pweather.others")) {
if (user != null && (!users.contains(user) || users.size() > 1) && !getTFMHandler().isAdmin(user)) {
user.sendMessage(tl("pWeatherOthersPermission"));
return;
}
@ -157,7 +157,7 @@ public class Commandpweather extends EssentialsCommand {
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1) {
return Lists.newArrayList("get", "reset", "storm", "sun");
} else if (args.length == 2 && (getAliases.contains(args[0]) || user == null || user.isAuthorized("essentials.pweather.others"))) {
} else if (args.length == 2 && (getAliases.contains(args[0]) || user == null || getTFMHandler().isAdmin(user))) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -11,6 +11,7 @@ import org.bukkit.BanEntry;
import org.bukkit.BanList;
import org.bukkit.Location;
import org.bukkit.Server;
import me.rayzr522.jsonmessage.JSONMessage;
import java.util.ArrayList;
import java.util.Date;
@ -33,7 +34,7 @@ public class Commandseen extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
seen(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.ip"), user.isAuthorized("essentials.seen.location"), user.isAuthorized("essentials.seen.ipsearch"));
seen(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.seen.banreason"), getTFMHandler().isAdmin(user), user.isAuthorized("essentials.seen.location"), getTFMHandler().isAdmin(user));
}
protected void seen(final Server server, final CommandSource sender, final String commandLabel, final String[] args,
@ -129,7 +130,14 @@ public class Commandseen extends EssentialsCommand {
sender.sendMessage(tl("whoisGeoLocation", location));
}
if (showIp) {
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
if (sender.isPlayer()) {
JSONMessage.create(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()))
.tooltip("Click to lookup their IP address.")
.runCommand("/seen " + user.getBase().getAddress().getAddress().toString().replace("/", ""))
.send(sender.getPlayer());
} else {
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
}
}
}

View file

@ -52,7 +52,7 @@ public class Commandtp extends EssentialsCommand {
user.sendMessage(tl("teleporting", locpos.getWorld().getName(), locpos.getBlockX(), locpos.getBlockY(), locpos.getBlockZ()));
break;
case 4:
if (!user.isAuthorized("essentials.tp.others")) {
if (!getTFMHandler().isAdmin(user)) {
throw new Exception(tl("noPerm", "essentials.tp.others"));
}
if (!user.isAuthorized("essentials.tp.position")) {
@ -75,7 +75,7 @@ public class Commandtp extends EssentialsCommand {
break;
case 2:
default:
if (!user.isAuthorized("essentials.tp.others")) {
if (!getTFMHandler().isAdmin(user)) {
throw new Exception(tl("noPerm", "essentials.tp.others"));
}
final User target = getPlayer(server, user, args, 0);
@ -125,7 +125,7 @@ public class Commandtp extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
// Don't handle coords
if (args.length == 1 || (args.length == 2 && user.isAuthorized("essentials.tp.others"))) {
if (args.length == 1 || (args.length == 2 && getTFMHandler().isAdmin(user))) {
return getPlayers(server, user);
} else {
return Collections.emptyList();

View file

@ -39,7 +39,7 @@ public class Commandwarp extends EssentialsCommand {
if (args.length > 0) {
//TODO: Remove 'otherplayers' permission.
User otherUser = null;
if (args.length == 2 && (user.isAuthorized("essentials.warp.otherplayers") || user.isAuthorized("essentials.warp.others"))) {
if (args.length == 2 && getTFMHandler().isAdmin(user)) {
otherUser = getPlayer(server, user, args, 1);
warpUser(user, otherUser, args[0]);
throw new NoChargeException();
@ -117,7 +117,7 @@ public class Commandwarp extends EssentialsCommand {
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.warp.list")) {
return getAvailableWarpsFor(user);
} else if (args.length == 2 && (user.isAuthorized("essentials.warp.otherplayers") || user.isAuthorized("essentials.warp.others"))) {
} else if (args.length == 2 && getTFMHandler().isAdmin(user)) {
//TODO: Remove 'otherplayers' permission.
return getPlayers(server, user);
} else {

View file

@ -46,7 +46,7 @@ public class Commandwhois extends EssentialsCommand {
if (!ess.getSettings().isEcoDisabled()) {
sender.sendMessage(tl("whoisMoney", NumberUtil.displayCurrency(user.getMoney(), ess)));
}
if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.whois.ip")) {
if (!sender.isPlayer() || getTFMHandler().isAdmin(user)) {
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
}
final String location = user.getGeoLocation();

View file

@ -14,6 +14,7 @@ import net.ess3.api.IEssentials;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import com.earth2me.essentials.TFMHandler;
import org.bukkit.util.StringUtil;
@ -34,11 +35,16 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
protected transient IEssentials ess;
protected transient IEssentialsModule module;
protected static final Logger logger = Logger.getLogger("Essentials");
protected static final TFMHandler tfmHandler = new TFMHandler();
protected EssentialsCommand(final String name) {
this.name = name;
}
public static TFMHandler getTFMHandler() {
return tfmHandler;
}
@Override
public void setEssentials(final IEssentials ess) {
this.ess = ess;

View file

@ -21,12 +21,12 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand {
protected void handleToggleWithArgs(Server server, User user, String[] args) throws Exception {
if (args.length == 1) {
Boolean toggle = matchToggleArgument(args[0]);
if (toggle == null && user.isAuthorized(othersPermission)) {
if (toggle == null && getTFMHandler().isAdmin(user)) {
toggleOtherPlayers(server, user.getSource(), args);
} else {
togglePlayer(user.getSource(), user, toggle);
}
} else if (args.length == 2 && user.isAuthorized(othersPermission)) {
} else if (args.length == 2 && getTFMHandler().isAdmin(user)) {
toggleOtherPlayers(server, user.getSource(), args);
} else {
togglePlayer(user.getSource(), user, null);
@ -51,7 +51,7 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand {
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(args[0]);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
@ -64,6 +64,10 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand {
togglePlayer(sender, player, false);
}
} else {
if (!getTFMHandler().isAdmin(sender.getPlayer()))
{
player = ess.getUser(sender.getPlayer());
}
togglePlayer(sender, player, null);
}
}
@ -78,12 +82,12 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
if (user.isAuthorized(othersPermission)) {
if (getTFMHandler().isAdmin(user)) {
return getPlayers(server, user);
} else {
return Lists.newArrayList("enable", "disable");
}
} else if (args.length == 2 && user.isAuthorized(othersPermission)) {
} else if (args.length == 2 && getTFMHandler().isAdmin(user)) {
return Lists.newArrayList("enable", "disable");
} else {
return Collections.emptyList();

View file

@ -2,6 +2,7 @@ package com.earth2me.essentials.messaging;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.TFMHandler;
import com.earth2me.essentials.User;
import java.lang.ref.WeakReference;
@ -35,6 +36,8 @@ public class SimpleMessageRecipient implements IMessageRecipient {
private long lastMessageMs;
private WeakReference<IMessageRecipient> replyRecipient;
private final TFMHandler tfmHandler = new TFMHandler();
protected static User getUser(IMessageRecipient recipient) {
if (recipient instanceof SimpleMessageRecipient) {
return ((SimpleMessageRecipient) recipient).parent instanceof User ? (User) ((SimpleMessageRecipient) recipient).parent : null;
@ -121,7 +124,7 @@ public class SimpleMessageRecipient implements IMessageRecipient {
boolean afk = false;
boolean isLastMessageReplyRecipient = ess.getSettings().isLastMessageReplyRecipient();
if (user != null) {
if (user.isIgnoreMsg() && sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { // Don't ignore console and senders with permission
if (user.isIgnoreMsg() && sender instanceof IUser && !tfmHandler.isAdmin(((IUser) sender).getBase())) { // Don't ignore console and senders with permission
return MessageResponse.MESSAGES_IGNORED;
}
afk = user.isAfk();

View file

@ -13,18 +13,10 @@ commands:
description: Marks you as away-from-keyboard.
usage: /<command> [player/message...]
aliases: [eafk,away,eaway]
antioch:
description: 'A little surprise for operators.'
usage: /<command> [message]
aliases: [eantioch,grenade,egrenade,tnt,etnt]
back:
description: Teleports you to your location prior to tp/spawn/warp.
usage: /<command> [player]
aliases: [eback,return,ereturn]
backup:
description: Runs the backup if configured.
usage: /<command>
aliases: [ebackup]
balance:
description: States the current balance of a player.
usage: /<command> [player]
@ -33,14 +25,6 @@ commands:
description: Gets the top balance values.
usage: /<command> <page>
aliases: [ebalancetop,baltop,ebaltop]
ban:
description: Bans a player.
usage: /<command> <player> [reason]
aliases: [eban]
banip:
description: Bans an IP address.
usage: /<command> <address>
aliases: [ebanip]
book:
description: Allows reopening and editing of sealed books.
usage: /<command> [title|author [name]]
@ -49,14 +33,6 @@ commands:
description: Breaks the block you are looking at.
usage: /<command>
aliases: [ebreak]
broadcast:
description: Broadcasts a message to the entire server.
usage: /<command> <msg>
aliases: [bc,ebc,bcast,ebcast,ebroadcast,shout,eshout]
broadcastworld:
description: Broadcasts a message to a world.
usage: /<command> <world> <msg>
aliases: [bcw,ebcw,bcastw,ebcastw,ebroadcastworld,shoutworld,eshoutworld]
bigtree:
description: Spawn a big tree where you are looking.
usage: /<command> <tree|redwood|jungle|darkoak>
@ -92,10 +68,6 @@ commands:
description: Removes a home.
usage: /<command> [player:]<name>
aliases: [edelhome,remhome,eremhome,rmhome,ermhome]
deljail:
description: Removes a jail.
usage: /<command> <jailname>
aliases: [edeljail,remjail,eremjail,rmjail,ermjail]
delkit:
description: Deletes the specified kit.
usage: /<command> <kit>
@ -144,10 +116,6 @@ commands:
description: Take off, and soar!
usage: /<command> [player] [on|off]
aliases: [efly]
fireball:
description: Throw a fireball.
usage: /<command> [small|large|dragon|arrow|skull|egg|snowball|expbottle|splashpotion|lingeringpotion] [speed]
aliases: [efireball,fireentity,efireentity,fireskull,efireskull]
firework:
description: Allows you to modify a stack of fireworks.
usage: /<command> <<meta param>|power [amount]|clear|fire [amount]>
@ -184,10 +152,6 @@ commands:
description: Views a list of available commands.
usage: /<command> [search term] [page]
aliases: [ehelp]
helpop:
description: Message online admins.
usage: /<command> <message>
aliases: [ac,eac,amsg,eamsg,ehelpop]
home:
description: Teleport to your home.
usage: /<command> [player:][name]
@ -216,22 +180,10 @@ commands:
description: Names an item.
usage: /<command> [name]
aliases: [iname, einame, eitemname, itemrename, irename, eitemrename, eirename]
jails:
description: List all jails.
usage: /<command>
aliases: [ejails]
jump:
description: Jumps to the nearest block in the line of sight.
usage: /<command>
aliases: [j,ej,ejump,jumpto,ejumpto]
kick:
description: Kicks a specified player with a reason.
usage: /<command> <player> [reason]
aliases: [ekick]
kickall:
description: Kicks all players off the server except the issuer.
usage: /<command> [reason]
aliases: [ekickall]
kill:
description: Kills specified player.
usage: /<command> <player>
@ -276,10 +228,6 @@ commands:
description: Blocks receiving all private messages.
usage: /<command> [player] [on|off]
aliases: [emsgtoggle]
mute:
description: Mutes or unmutes a player.
usage: /<command> <player> [datediff] [reason]
aliases: [emute,silence,esilence]
near:
description: Lists the players near by or around a player.
usage: /<command> [playername] [radius]
@ -288,10 +236,6 @@ commands:
description: Change your nickname or that of another player.
usage: /<command> [player] <nickname|off>
aliases: [enick,nickname,enickname]
nuke:
description: May death rain upon them.
usage: /<command> [player]
aliases: [enuke]
pay:
description: Pays another player from your balance.
usage: /<command> <player> <amount>
@ -312,14 +256,6 @@ commands:
description: Adds custom potion effects to a potion.
usage: /<command> <clear|apply|effect:<effect> power:<power> duration:<duration>>
aliases: [epotion,elixer,eelixer]
powertool:
description: Assigns a command to the item in hand.
usage: /<command> [l:|a:|r:|c:|d:][command] [arguments] - {player} can be replaced by name of a clicked player.
aliases: [epowertool,pt,ept]
powertooltoggle:
description: Enables or disables all current powertools.
usage: /<command>
aliases: [epowertooltoggle,ptt,eptt,pttoggle,epttoggle]
ptime:
description: Adjust player's client time. Add @ prefix to fix.
usage: /<command> [list|reset|day|night|dawn|17:30|4pm|4000ticks] [player|*]
@ -368,10 +304,6 @@ commands:
description: Set your home to your current location.
usage: /<command> [[player:]name]
aliases: [esethome,createhome,ecreatehome]
setjail:
description: Creates a jail where you specified named [jailname].
usage: /<command> <jailname>
aliases: [esetjail,createjail,ecreatejail]
setwarp:
description: Creates a new warp.
usage: /<command> <warp>
@ -404,18 +336,10 @@ commands:
description: Change your speed limits.
usage: /<command> [type] <speed> [player]
aliases: [flyspeed,eflyspeed,fspeed,efspeed,espeed,walkspeed,ewalkspeed,wspeed,ewspeed]
sudo:
description: Make another user perform a command.
usage: /<command> <player> <command [args]>
aliases: [esudo]
suicide:
description: Causes you to perish.
usage: /<command>
aliases: [esuicide]
tempban:
description: Temporary ban a user.
usage: /<command> <playername> <datediff> <reason>
aliases: [etempban]
thunder:
description: Enable/disable thunder.
usage: /<command> <true/false> [duration]
@ -424,10 +348,6 @@ commands:
description: Display/Change the world time. Defaults to current world.
usage: /<command> [day|night|dawn|17:30|4pm|4000ticks] [worldname|all]
aliases: [day,eday,night,enight,etime]
togglejail:
description: Jails/Unjails a player, TPs them to the jail specified.
usage: /<command> <player> <jailname> [datediff]
aliases: [jail,ejail,tjail,etjail,etogglejail,unjail,eunjail]
top:
description: Teleport to the highest block at your current position.
usage: /<command>
@ -492,30 +412,14 @@ commands:
description: Spawn a tree where you are looking.
usage: /<command> <tree|birch|redwood|redmushroom|brownmushroom|jungle|junglebush|swamp>
aliases: [etree]
unban:
description: Unbans the specified player.
usage: /<command> <player>
aliases: [pardon,eunban,epardon]
unbanip:
description: Unbans the specified IP address.
usage: /<command> <address>
aliases: [eunbanip,pardonip,epardonip]
unlimited:
description: Allows the unlimited placing of items.
usage: /<command> <list|item|clear> [player]
aliases: [eunlimited,ul,unl,eul,eunl]
vanish:
description: Hide yourself from other players.
usage: /<command> [player] [on|off]
aliases: [v,ev,evanish]
warp:
description: List all warps or warp to the specified location.
usage: /<command> <pagenumber|warp> [player]
aliases: [ewarp,warps,ewarps]
weather:
description: Sets the weather.
usage: /<command> <storm/sun> [duration]
aliases: [rain,erain,sky,esky,storm,estorm,sun,esun,eweather]
whois:
description: Determine the username behind a nickname.
usage: /<command> <nickname>

View file

@ -1,145 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.NoLoanPermittedException;
import com.earth2me.essentials.api.UserDoesNotExistException;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import net.ess3.api.Economy;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.InvalidDescriptionException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class EconomyTest {
private final transient Essentials ess;
private static final String NPCNAME = "npc1";
private static final String PLAYERNAME = "testPlayer1";
private static final String PLAYERNAME2 = "testPlayer2";
private final FakeServer server;
public EconomyTest() {
this.server = new FakeServer();
server.createWorld("testWorld", Environment.NORMAL);
ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
Assert.fail("InvalidDescriptionException");
} catch (IOException ex) {
Assert.fail("IOException");
}
server.addPlayer(new OfflinePlayer(PLAYERNAME, ess.getServer()));
server.addPlayer(new OfflinePlayer(PLAYERNAME2, ess.getServer()));
}
// only one big test, since we use static instances
@Test
public void testEconomy() {
// test NPC
Assert.assertFalse("NPC does not exists", Economy.playerExists(NPCNAME));
Assert.assertTrue("Create NPC", Economy.createNPC(NPCNAME));
Assert.assertTrue("NPC exists", Economy.playerExists(NPCNAME));
Assert.assertNotNull("NPC can be accessed", ess.getOfflineUser(NPCNAME));
try {
Economy.removeNPC(NPCNAME);
} catch (UserDoesNotExistException ex) {
Assert.fail(ex.getMessage());
}
Assert.assertFalse("NPC can be removed", Economy.playerExists(NPCNAME));
//test Math
try {
Assert.assertTrue("Player exists", Economy.playerExists(PLAYERNAME));
Economy.resetBalance(PLAYERNAME);
Assert.assertEquals("Player has no money", 0.0, Economy.getMoney(PLAYERNAME), 0);
Economy.add(PLAYERNAME, 10.0);
Assert.assertEquals("Add money", 10.0, Economy.getMoney(PLAYERNAME),0);
Economy.subtract(PLAYERNAME, 5.0);
Assert.assertEquals("Subtract money", 5.0, Economy.getMoney(PLAYERNAME),0);
Economy.multiply(PLAYERNAME, 2.0);
Assert.assertEquals("Multiply money", 10.0, Economy.getMoney(PLAYERNAME),0);
Economy.divide(PLAYERNAME, 2.0);
Assert.assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME),0);
Economy.setMoney(PLAYERNAME, 10.0);
Assert.assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME),0);
} catch (NoLoanPermittedException | UserDoesNotExistException ex) {
Assert.fail(ex.getMessage());
}
//test Format
Assert.assertEquals("Format $1,000", "$1,000", Economy.format(1000.0));
Assert.assertEquals("Format $10", "$10", Economy.format(10.0));
Assert.assertEquals("Format $10.10", "$10.10", Economy.format(10.10));
Assert.assertEquals("Format $10.10", "$10.10", Economy.format(10.1000001));
Assert.assertEquals("Format $10.10", "$10.10", Economy.format(10.1099999));
//test Exceptions
try {
Assert.assertTrue("Player exists", Economy.playerExists(PLAYERNAME));
Economy.resetBalance(PLAYERNAME);
Assert.assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME),0);
Economy.subtract(PLAYERNAME, 5.0);
Assert.fail("Did not throw exception");
} catch (NoLoanPermittedException ignored) {
} catch (UserDoesNotExistException ex) {
Assert.fail(ex.getMessage());
}
try {
Economy.resetBalance("UnknownPlayer");
Assert.fail("Did not throw exception");
} catch (NoLoanPermittedException ex) {
Assert.fail(ex.getMessage());
} catch (UserDoesNotExistException ignored) {}
}
private void runCommand(String command, User user, String args) throws Exception {
runCommand(command, user, args.split("\\s+"));
}
private void runCommand(String command, User user, String[] args) throws Exception {
IEssentialsCommand cmd;
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader()
.loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, user, command, null, args);
} catch (NoChargeException ignored) {}
}
private void runConsoleCommand(String command, String args) throws Exception {
runConsoleCommand(command, args.split("\\s+"));
}
private void runConsoleCommand(String command, String[] args) throws Exception {
IEssentialsCommand cmd;
CommandSender sender = server.getConsoleSender();
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader()
.loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, new CommandSource(sender), command, null, args);
} catch (NoChargeException ignored) {}
}
@Test
public void testNegativePayCommand() {
User user1 = ess.getUser(PLAYERNAME);
try {
runCommand("pay", user1, PLAYERNAME2 + " -123");
} catch (Exception e) {
Assert.assertEquals(I18n.tl("payMustBePositive"), e.getMessage());
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,120 +0,0 @@
package com.earth2me.essentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.InvalidDescriptionException;
import org.junit.Test;
import java.io.IOException;
public class MessagingTest {
private final OfflinePlayer base1;
private final Essentials ess;
private final FakeServer server;
public MessagingTest() {
server = new FakeServer();
server.createWorld("testWorld", Environment.NORMAL);
ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
fail("InvalidDescriptionException");
} catch (IOException ex) {
fail("IOException");
}
base1 = server.createPlayer("testPlayer1");
server.addPlayer(base1);
ess.getUser(base1);
}
private void runCommand(String command, User user, String args) throws Exception {
runCommand(command, user, args.split("\\s+"));
}
private void runCommand(String command, User user, String[] args) throws Exception {
IEssentialsCommand cmd;
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader()
.loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, user, command, null, args);
} catch (NoChargeException ignored) {}
}
private void runConsoleCommand(String command, String args) throws Exception {
runConsoleCommand(command, args.split("\\s+"));
}
private void runConsoleCommand(String command, String[] args) throws Exception {
IEssentialsCommand cmd;
CommandSender sender = server.getConsoleSender();
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader()
.loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, new CommandSource(sender), command, null, args);
} catch (NoChargeException ignored) {}
}
@Test(expected = Exception.class) // I really don't like this, but see note below about console reply
public void testNullLastMessageReplyRecipient() throws Exception {
User user1 = ess.getUser(base1);
Console console = Console.getInstance();
if (ess.getSettings().isLastMessageReplyRecipient()) {
assertNull(console.getReplyRecipient()); // console never messaged or received messages from anyone.
if (ess.getSettings().isLastMessageReplyRecipient()) {
runCommand("r", user1, "This is me sending you a message using /r without you replying!");
}
// Not really much of a strict test, but just "testing" console output.
user1.setAfk(true);
// Console replies using "/r Hey, son!"
//
// This throws Exception because the console hasnt messaged anyone.
runConsoleCommand("r", "Hey, son!");
} else {
throw new Exception(); // Needed to prevent build failures.
}
}
@Test
public void testNonNullLastMessageReplyRecipient() throws Exception {
User user1 = ess.getUser(base1);
Console console = Console.getInstance();
if (ess.getSettings().isLastMessageReplyRecipient()) {
assertNull(console.getReplyRecipient()); // console never messaged or received messages from anyone.
// user1 messages console saying "Hey, master!"
runCommand("msg", user1, console.getName() + " Hey, master!");
// console should now have its reply-recipient as user1, since the console doesn't have a previous recipient.
assertEquals(user1, console.getReplyRecipient());
if (ess.getSettings().isLastMessageReplyRecipient()) {
runCommand("r", user1, "This is me sending you a message using /r without you replying!");
}
// Not really much of a strict test, but just "testing" console output.
user1.setAfk(true);
runConsoleCommand("r", "Hey, son!");
}
}
}

View file

@ -1,54 +0,0 @@
package com.earth2me.essentials;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.plugin.InvalidDescriptionException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class StorageTest {
private Essentials ess;
private FakeServer server;
private World world;
public StorageTest() {
server = new FakeServer();
world = server.createWorld("testWorld", Environment.NORMAL);
ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
Assert.fail("InvalidDescriptionException");
} catch (IOException ex) {
Assert.fail("IOException");
}
}
@Test
public void testOldUserdata() {
ExecuteTimer ext = new ExecuteTimer();
ext.start();
OfflinePlayer base1 = server.createPlayer("testPlayer1");
server.addPlayer(base1);
ext.mark("fake user created");
UserData user = ess.getUser(base1);
ext.mark("load empty user");
for (int j = 0; j < 1; j++) {
user.setHome("home", new Location(world, j, j, j));
}
ext.mark("change home 1 times");
user.save();
ext.mark("write user");
user.save();
ext.mark("write user (cached)");
user.reloadConfig();
ext.mark("reloaded file");
user.reloadConfig();
ext.mark("reloaded file (cached)");
System.out.println(ext.end());
}
}

View file

@ -1,172 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import junit.framework.TestCase;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.InvalidDescriptionException;
import java.io.IOException;
public class ToggleTest extends TestCase {
private final OfflinePlayer base1;
private final Essentials ess;
private final FakeServer server;
public ToggleTest(String testName) {
super(testName);
server = new FakeServer();
server.createWorld("testWorld", Environment.NORMAL);
ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
fail("InvalidDescriptionException");
} catch (IOException ex) {
fail("IOException");
}
base1 = server.createPlayer("testPlayer1");
server.addPlayer(base1);
ess.getUser(base1);
}
private void runCommand(String command, User user, String[] args) throws Exception {
IEssentialsCommand cmd;
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, user, command, null, args);
} catch (NoChargeException ignored) {}
}
private void runConsoleCommand(String command, String[] args) throws Exception {
IEssentialsCommand cmd;
CommandSender sender = server.getConsoleSender();
try {
cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
cmd.setEssentials(ess);
cmd.run(server, new CommandSource(sender), command, null, args);
} catch (NoChargeException ignored) {}
}
public void testFlyToggle() throws Exception {
User user = ess.getUser(base1);
assertFalse(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{"on"});
assertTrue(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{"on"});
assertTrue(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{"off"});
assertFalse(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{"off"});
assertFalse(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{});
assertTrue(user.getBase().getAllowFlight());
runCommand("fly", user, new String[]{});
assertFalse(user.getBase().getAllowFlight());
}
public void testFlyDisOnToggle() throws Exception {
User user = ess.getUser(base1);
user.getBase().setAllowFlight(true);
user.getBase().setFlying(true);
assertTrue(user.getBase().isFlying());
runCommand("fly", user, new String[]{});
assertFalse(user.getBase().getAllowFlight());
assertFalse(user.getBase().isFlying());
}
public void testGodToggle() throws Exception {
User user = ess.getUser(base1);
assertFalse(user.isGodModeEnabled());
runCommand("god", user, new String[]{"on"});
assertTrue(user.isGodModeEnabled());
runCommand("god", user, new String[]{"on"});
assertTrue(user.isGodModeEnabled());
runCommand("god", user, new String[]{"off"});
assertFalse(user.isGodModeEnabled());
runCommand("god", user, new String[]{"off"});
assertFalse(user.isGodModeEnabled());
runCommand("god", user, new String[]{});
assertTrue(user.isGodModeEnabled());
runCommand("god", user, new String[]{});
assertFalse(user.isGodModeEnabled());
}
public void testConsoleToggle() throws Exception {
User user = ess.getUser(base1);
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "on"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "on"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "off"});
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "off"});
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName()});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName()});
assertFalse(user.getBase().getAllowFlight());
}
public void testAliasesToggle() throws Exception {
User user = ess.getUser(base1);
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "enable"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "enable"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "disable"});
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "disable"});
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "1"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "1"});
assertTrue(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "0"});
assertFalse(user.getBase().getAllowFlight());
runConsoleCommand("fly", new String[]{base1.getName(), "0"});
assertFalse(user.getBase().getAllowFlight());
}
}

View file

@ -1,77 +0,0 @@
package com.earth2me.essentials;
import junit.framework.TestCase;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.World.Environment;
import org.bukkit.plugin.InvalidDescriptionException;
import java.io.IOException;
import java.math.BigDecimal;
public class UserTest extends TestCase {
private final OfflinePlayer base1;
private final Essentials ess;
private final FakeServer server;
public UserTest(String testName) {
super(testName);
server = new FakeServer();
server.createWorld("testWorld", Environment.NORMAL);
ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
fail("InvalidDescriptionException");
} catch (IOException ex) {
fail("IOException");
}
base1 = server.createPlayer("testPlayer1");
server.addPlayer(base1);
ess.getUser(base1);
}
private void should(String what) {
System.out.println(getName() + " should " + what);
}
public void testUpdate() {
OfflinePlayer base1alt = server.createPlayer(base1.getName());
assertEquals(base1alt, ess.getUser(base1alt).getBase());
}
public void testHome() {
User user = ess.getUser(base1);
Location loc = base1.getLocation();
user.setHome("home", loc);
OfflinePlayer base2 = server.createPlayer(base1.getName());
User user2 = ess.getUser(base2);
Location home = user2.getHome(loc);
assertNotNull(home);
assertEquals(loc.getWorld().getName(), home.getWorld().getName());
assertEquals(loc.getX(), home.getX());
assertEquals(loc.getY(), home.getY());
assertEquals(loc.getZ(), home.getZ());
assertEquals(loc.getYaw(), home.getYaw());
assertEquals(loc.getPitch(), home.getPitch());
}
public void testMoney() {
should("properly set, take, give, and get money");
User user = ess.getUser(base1);
BigDecimal i = new BigDecimal("100.5");
try {
user.setMoney(i);
user.takeMoney(new BigDecimal(50));
i = i.subtract(BigDecimal.valueOf(50));
user.giveMoney(new BigDecimal(25));
i = i.add(BigDecimal.valueOf(25));
} catch (MaxMoneyException ex) {
fail();
}
assertEquals(user.getMoney(), i);
}
}

View file

@ -1,226 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.VersionUtil;
import junit.framework.TestCase;
import org.bukkit.World.Environment;
import org.bukkit.plugin.InvalidDescriptionException;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
public class UtilTest extends TestCase {
public UtilTest() {
FakeServer server = new FakeServer();
server.createWorld("testWorld", Environment.NORMAL);
Essentials ess = new Essentials(server);
try {
ess.setupForTesting(server);
} catch (InvalidDescriptionException ex) {
fail("InvalidDescriptionException");
} catch (IOException ex) {
fail("IOException");
}
}
public void testSafeLocation() {
Set<String> testSet = new HashSet<>();
int count = 0;
int x, y, z, origX, origY, origZ;
x = y = z = origX = origY = origZ = 0;
int i = 0;
while (true) {
testSet.add(x + ":" + y + ":" + z);
count++;
i++;
if (i >= LocationUtil.VOLUME.length) {
break;
}
x = origX + LocationUtil.VOLUME[i].x;
y = origY + LocationUtil.VOLUME[i].y;
z = origZ + LocationUtil.VOLUME[i].z;
}
assertTrue(testSet.contains("0:0:0"));
assertTrue(testSet.contains("3:3:3"));
assertEquals(testSet.size(), count);
int diameter = LocationUtil.RADIUS * 2 + 1;
assertEquals(diameter * diameter * diameter, count);
}
public void testFDDnow() {
Calendar c = new GregorianCalendar();
String resp = DateUtil.formatDateDiff(c, c);
assertEquals(resp, "now");
}
public void testFDDfuture() {
Calendar a, b;
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 1);
assertEquals("1 second", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 2);
assertEquals("2 seconds", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 3);
assertEquals("3 seconds", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 1, 0);
assertEquals("1 minute", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 2, 0);
assertEquals("2 minutes", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 3, 0);
assertEquals("3 minutes", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 11, 0, 0);
assertEquals("1 hour", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 12, 0, 0);
assertEquals("2 hours", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 13, 0, 0);
assertEquals("3 hours", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 2, 10, 0, 0);
assertEquals("1 day", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 3, 10, 0, 0);
assertEquals("2 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 4, 10, 0, 0);
assertEquals("3 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.MARCH, 1, 10, 0, 0);
assertEquals("1 month", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.APRIL, 1, 10, 0, 0);
assertEquals("2 months", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.MAY, 1, 10, 0, 0);
assertEquals("3 months", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2011, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("1 year", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2012, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("2 years", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2013, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("3 years", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2011, Calendar.MAY, 5, 23, 38, 12);
assertEquals("1 year 3 months 4 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.OCTOBER, 17, 23, 45, 45);
b = new GregorianCalendar(2015, Calendar.APRIL, 7, 10, 0, 0);
assertEquals("4 years 5 months 20 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2011, Calendar.MAY, 31, 10, 0, 0);
b = new GregorianCalendar(2011, Calendar.MAY, 31, 10, 5, 0);
assertEquals("5 minutes", DateUtil.formatDateDiff(a, b));
}
public void testFDDpast() {
Calendar a, b;
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 59, 59);
assertEquals("1 second", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 59, 58);
assertEquals("2 seconds", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 59, 57);
assertEquals("3 seconds", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 59, 0);
assertEquals("1 minute", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 58, 0);
assertEquals("2 minutes", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 57, 0);
assertEquals("3 minutes", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 9, 0, 0);
assertEquals("1 hour", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 8, 0, 0);
assertEquals("2 hours", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 7, 0, 0);
assertEquals("3 hours", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 5, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 4, 10, 0, 0);
assertEquals("1 day", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 5, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 3, 10, 0, 0);
assertEquals("2 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 5, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.FEBRUARY, 2, 10, 0, 0);
assertEquals("3 days", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.JUNE, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.MAY, 1, 10, 0, 0);
assertEquals("1 month", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.JUNE, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.APRIL, 1, 10, 0, 0);
assertEquals("2 months", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.JUNE, 1, 10, 0, 0);
b = new GregorianCalendar(2010, Calendar.MARCH, 1, 10, 0, 0);
assertEquals("3 months", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2009, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("1 year", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2008, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("2 years", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2007, Calendar.FEBRUARY, 1, 10, 0, 0);
assertEquals("3 years", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.FEBRUARY, 1, 10, 0, 0);
b = new GregorianCalendar(2009, Calendar.MAY, 5, 23, 38, 12);
assertEquals("8 months 26 days 10 hours", DateUtil.formatDateDiff(a, b));
a = new GregorianCalendar(2010, Calendar.OCTOBER, 17, 23, 45, 45);
b = new GregorianCalendar(2000, Calendar.APRIL, 7, 10, 0, 0);
assertEquals("10 years 6 months 10 days", DateUtil.formatDateDiff(a, b));
}
public void testVer() {
VersionUtil.BukkitVersion v;
v = VersionUtil.BukkitVersion.fromString("1.13.2-R0.1");
assertEquals(v.getMajor(), 1);
assertEquals(v.getMinor(), 13);
assertEquals(v.getPatch(), 2);
assertEquals(v.getRevision(), 0.1);
assertEquals(v.getPrerelease(), -1);
v = VersionUtil.BukkitVersion.fromString("1.9-R1.4"); // not real
assertEquals(v.getMajor(), 1);
assertEquals(v.getMinor(), 9);
assertEquals(v.getPatch(), 0);
assertEquals(v.getRevision(), 1.4);
assertEquals(v.getPrerelease(), -1);
v = VersionUtil.BukkitVersion.fromString("1.14-pre5");
assertEquals(v.getMajor(), 1);
assertEquals(v.getMinor(), 14);
assertEquals(v.getPatch(), 0);
assertEquals(v.getRevision(), 0.0);
assertEquals(v.getPrerelease(), 5);
v = VersionUtil.BukkitVersion.fromString("1.13.2-pre1-R0.1"); // not real
assertEquals(v.getMajor(), 1);
assertEquals(v.getMinor(), 13);
assertEquals(v.getPatch(), 2);
assertEquals(v.getRevision(), 0.1);
assertEquals(v.getPrerelease(), 1);
v = VersionUtil.BukkitVersion.fromString("1.14.3-SNAPSHOT");
assertEquals(v.getMajor(), 1);
assertEquals(v.getMinor(), 14);
assertEquals(v.getPatch(), 3);
assertEquals(v.getRevision(), 0.0);
assertEquals(v.getPrerelease(), -1);
}
}

View file

@ -1,108 +0,0 @@
package com.earth2me.essentials.utils;
import net.ess3.api.IUser;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class FormatUtilTest {
@Test
public void testFormatCase() {
checkFormatPerms("&aT&Aest", "&aT&Aest");
checkFormatPerms("§aT§Aest", "Test");
checkFormatPerms("&aT&Aest", "§aT§Aest", "color");
checkFormatPerms("§aT§Aest", "§aT§Aest", "color");
}
@Test
public void testFormatCategoryPerms() {
checkFormatPerms("Test", "Test");
checkFormatPerms("Test", "Test", "color", "format");
checkFormatPerms("&1C&2o&3l&4o&5r&6m&7a&8t&9i&ac", "&1C&2o&3l&4o&5r&6m&7a&8t&9i&ac"); // Unchanged
checkFormatPerms("§1C§2o§3l§4o§5r§6m§7a§8t§9i§ac", "Colormatic"); // Removed
checkFormatPerms("&1C&2o&3l&4o&5r&6m&7a&8t&9i&ac", "§1C§2o§3l§4o§5r§6m§7a§8t§9i§ac", "color"); // Converted
checkFormatPerms("§1C§2o§3l§4o§5r§6m§7a§8t§9i§ac", "§1C§2o§3l§4o§5r§6m§7a§8t§9i§ac", "color"); // Unchanged
checkFormatPerms("&kFUNKY LOL", "§kFUNKY LOL", "magic"); // Converted
checkFormatPerms("§kFUNKY LOL", "§kFUNKY LOL", "magic"); // Unchanged
// Magic isn't included in the format group
checkFormatPerms("&kFUNKY LOL", "&kFUNKY LOL"); // Unchanged
checkFormatPerms("§kFUNKY LOL", "FUNKY LOL"); // Removed
checkFormatPerms("&kFUNKY LOL", "&kFUNKY LOL", "format"); // Unchanged
checkFormatPerms("§kFUNKY LOL", "FUNKY LOL", "format"); // Removed
checkFormatPerms("&f&ltest", "&f&ltest");
checkFormatPerms("§f§ltest", "test");
checkFormatPerms("&f&ltest", "§f&ltest", "color");
checkFormatPerms("§f§ltest", "§ftest", "color");
checkFormatPerms("&f&ltest", "&f§ltest", "format");
checkFormatPerms("§f§ltest", "§ltest", "format");
checkFormatPerms("&f&ltest", "§f§ltest", "color", "format");
checkFormatPerms("§f§ltest", "§f§ltest", "color", "format");
}
@Test
public void testFormatCodePerms() {
checkFormatPerms("&1Te&2st", "&1Te&2st");
checkFormatPerms("§1Te§2st", "Test");
checkFormatPerms("&1Te&2st", "§1Te&2st", "dark_blue");
checkFormatPerms("§1Te§2st", "§1Test", "dark_blue");
checkFormatPerms("&1Te&2st", "&1Te§2st", "dark_green");
checkFormatPerms("§1Te§2st", "Te§2st", "dark_green");
checkFormatPerms("&1Te&2st", "§1Te§2st", "dark_blue", "dark_green");
checkFormatPerms("§1Te§2st", "§1Te§2st", "dark_blue", "dark_green");
// Obfuscated behaves the same as magic
checkFormatPerms("&kFUNKY LOL", "§kFUNKY LOL", "obfuscated");
checkFormatPerms("§kFUNKY LOL", "§kFUNKY LOL", "obfuscated");
}
@Test
public void testFormatAddRemovePerms() {
checkFormatPerms("&1Te&2st&ling", "&1Te§2st&ling", "color", "-dark_blue");
checkFormatPerms("§1Te§2st§ling", "Te§2sting", "color", "-dark_blue");
// Nothing happens when negated without being previously present
checkFormatPerms("&1Te&2st&ling", "&1Te§2st&ling", "color", "-dark_blue", "-bold");
checkFormatPerms("§1Te§2st§ling", "Te§2sting", "color", "-dark_blue", "-bold");
}
@Test
public void testFormatEscaping() {
// Don't do anything to non-format codes
checkFormatPerms("True & false", "True & false");
checkFormatPerms("True && false", "True && false");
// Formats are only unescaped if you have the right perms
checkFormatPerms("This is &&a message", "This is &&a message");
checkFormatPerms("This is &&a message", "This is &a message", "color");
// Can't put an & before a non-escaped format
checkFormatPerms("This is &&&a message", "This is &&&a message");
checkFormatPerms("This is &&&a message", "This is &&a message", "color");
}
private void checkFormatPerms(String input, String expectedOutput, String... perms) {
IUser user = mock(IUser.class);
for (String perm : perms) {
if (perm.startsWith("-")) {
// Negated perms
perm = perm.substring(1);
when(user.isAuthorized("essentials.chat." + perm)).thenReturn(false);
} else {
when(user.isAuthorized("essentials.chat." + perm)).thenReturn(true);
}
when(user.isPermissionSet("essentials.chat." + perm)).thenReturn(true);
}
assertEquals(expectedOutput, FormatUtil.formatString(user, "essentials.chat", input));
}
}

View file

@ -1,25 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.17.1</version>
</parent>
<artifactId>EssentialsXAntiBuild</artifactId>
<build>
<finalName>EssentialsXAntiBuild-${full.version}</finalName>
</build>
<dependencies>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>EssentialsX</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View file

@ -1,65 +0,0 @@
package com.earth2me.essentials.antibuild;
public enum AntiBuildConfig {
disable_build("protect.disable.build", true),
disable_use("protect.disable.use", true),
alert_on_placement("protect.alert.on-placement"),
alert_on_use("protect.alert.on-use"),
alert_on_break("protect.alert.on-break"),
blacklist_placement("protect.blacklist.placement"),
blacklist_usage("protect.blacklist.usage"),
blacklist_break("protect.blacklist.break"),
blacklist_piston("protect.blacklist.piston"),
blacklist_dispenser("protect.blacklist.dispenser");
private final String configName;
private final String defValueString;
private final boolean defValueBoolean;
private final boolean isList;
private final boolean isString;
AntiBuildConfig(final String configName) {
this(configName, null, false, true, false);
}
AntiBuildConfig(final String configName, final boolean defValueBoolean) {
this(configName, null, defValueBoolean, false, false);
}
AntiBuildConfig(final String configName, final String defValueString, final boolean defValueBoolean, final boolean isList, final boolean isString) {
this.configName = configName;
this.defValueString = defValueString;
this.defValueBoolean = defValueBoolean;
this.isList = isList;
this.isString = isString;
}
/**
* @return the configName
*/
public String getConfigName() {
return configName;
}
/**
* @return the default value String
*/
public String getDefaultValueString() {
return defValueString;
}
/**
* @return the default value boolean
*/
public boolean getDefaultValueBoolean() {
return defValueBoolean;
}
public boolean isString() {
return isString;
}
public boolean isList() {
return isList;
}
}

View file

@ -1,63 +0,0 @@
package com.earth2me.essentials.antibuild;
import com.earth2me.essentials.metrics.Metrics;
import org.bukkit.Material;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild {
private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<>(AntiBuildConfig.class);
private final transient Map<AntiBuildConfig, List<Material>> settingsList = new EnumMap<>(AntiBuildConfig.class);
private transient EssentialsConnect ess = null;
private transient Metrics metrics = null;
@Override
public void onEnable() {
final PluginManager pm = this.getServer().getPluginManager();
final Plugin essPlugin = pm.getPlugin("Essentials");
if (essPlugin == null || !essPlugin.isEnabled()) {
return;
}
ess = new EssentialsConnect(essPlugin, this);
final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this);
pm.registerEvents(blockListener, this);
if (metrics == null) {
metrics = new Metrics(this);
}
}
@Override
public boolean checkProtectionItems(final AntiBuildConfig list, final Material mat) {
final List<Material> itemList = settingsList.get(list);
return itemList != null && !itemList.isEmpty() && itemList.contains(mat);
}
@Override
public EssentialsConnect getEssentialsConnect() {
return ess;
}
@Override
public Map<AntiBuildConfig, Boolean> getSettingsBoolean() {
return settingsBoolean;
}
@Override
public Map<AntiBuildConfig, List<Material>> getSettingsList() {
return settingsList;
}
@Override
public boolean getSettingBool(final AntiBuildConfig protectConfig) {
final Boolean bool = settingsBoolean.get(protectConfig);
return bool == null ? protectConfig.getDefaultValueBoolean() : bool;
}
}

View file

@ -1,298 +0,0 @@
package com.earth2me.essentials.antibuild;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsAntiBuildListener implements Listener {
private static final Logger logger = Logger.getLogger("EssentialsAntiBuild");
final private transient IAntiBuild prot;
final private transient IEssentials ess;
EssentialsAntiBuildListener(final IAntiBuild parent) {
this.prot = parent;
this.ess = prot.getEssentialsConnect().getEssentials();
if (isEntityPickupEvent()) {
ess.getServer().getPluginManager().registerEvents(new EntityPickupItemListener(), prot);
} else {
ess.getServer().getPluginManager().registerEvents(new PlayerPickupItemListener(), prot);
}
}
private static boolean isEntityPickupEvent() {
try {
Class.forName("org.bukkit.event.entity.EntityPickupItemEvent");
return true;
} catch (ClassNotFoundException ignored) {
return false;
}
}
private boolean metaPermCheck(final User user, final String action, final Block block) {
if (block == null) {
if (ess.getSettings().isDebug()) {
logger.log(Level.INFO, "AntiBuild permission check failed, invalid block.");
}
return false;
}
return metaPermCheck(user, action, block.getType(), block.getData());
}
public boolean metaPermCheck(final User user, final String action, final Material material) {
final String blockPerm = "essentials.build." + action + "." + material;
return user.isAuthorized(blockPerm);
}
private boolean metaPermCheck(final User user, final String action, final Material material, final short data) {
final String blockPerm = "essentials.build." + action + "." + material;
final String dataPerm = blockPerm + ":" + data;
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
if (user.getBase().isPermissionSet(dataPerm)) {
return user.isAuthorized(dataPerm);
} else {
if (ess.getSettings().isDebug()) {
logger.log(Level.INFO, "DataValue perm on " + user.getName() + " is not directly set: " + dataPerm);
}
}
}
return user.isAuthorized(blockPerm);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(final BlockPlaceEvent event) {
final User user = ess.getUser(event.getPlayer());
final Block block = event.getBlockPlaced();
final Material type = block.getType();
if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "place", block)) {
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildPlace", type.toString()));
}
event.setCancelled(true);
return;
}
if (prot.checkProtectionItems(AntiBuildConfig.blacklist_placement, type) && !user.isAuthorized("essentials.protect.exemptplacement")) {
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildPlace", type.toString()));
}
event.setCancelled(true);
return;
}
if (prot.checkProtectionItems(AntiBuildConfig.alert_on_placement, type) && !user.isAuthorized("essentials.protect.alerts.notrigger")) {
prot.getEssentialsConnect().alert(user, type.toString(), tl("alertPlaced"));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(final BlockBreakEvent event) {
final User user = ess.getUser(event.getPlayer());
final Block block = event.getBlock();
final Material type = block.getType();
if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "break", block)) {
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildBreak", type.toString()));
}
event.setCancelled(true);
return;
}
if (prot.checkProtectionItems(AntiBuildConfig.blacklist_break, type) && !user.isAuthorized("essentials.protect.exemptbreak")) {
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildBreak", type.toString()));
}
event.setCancelled(true);
return;
}
if (prot.checkProtectionItems(AntiBuildConfig.alert_on_break, type) && !user.isAuthorized("essentials.protect.alerts.notrigger")) {
prot.getEssentialsConnect().alert(user, type.toString(), tl("alertBroke"));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onHangingBreak(final HangingBreakByEntityEvent event) {
final Entity entity = event.getRemover();
if (entity instanceof Player) {
final User user = ess.getUser((Player) entity);
final EntityType type = event.getEntity().getType();
final boolean warn = ess.getSettings().warnOnBuildDisallow();
if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (type == EntityType.PAINTING && !metaPermCheck(user, "break", Material.PAINTING)) {
if (warn) {
user.sendMessage(tl("antiBuildBreak", Material.PAINTING.toString()));
}
event.setCancelled(true);
} else if (type == EntityType.ITEM_FRAME && !metaPermCheck(user, "break", Material.ITEM_FRAME)) {
if (warn) {
user.sendMessage(tl("antiBuildBreak", Material.ITEM_FRAME.toString()));
}
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPistonExtend(final BlockPistonExtendEvent event) {
for (Block block : event.getBlocks()) {
if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getType())) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPistonRetract(final BlockPistonRetractEvent event) {
if (!event.isSticky()) {
return;
}
final Block block = event.getBlock();
if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getType())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerInteract(final PlayerInteractEvent event) {
// Do not return if cancelled, because the interact event has 2 cancelled states.
final User user = ess.getUser(event.getPlayer());
final ItemStack item = event.getItem();
if (item != null && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getType()) && !user.isAuthorized("essentials.protect.exemptusage")) {
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildUse", item.getType().toString()));
}
event.setCancelled(true);
return;
}
if (item != null && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getType()) && !user.isAuthorized("essentials.protect.alerts.notrigger")) {
prot.getEssentialsConnect().alert(user, item.getType().toString(), tl("alertUsed"));
}
if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (event.hasItem() && !metaPermCheck(user, "interact", item.getType(), item.getDurability())) {
event.setCancelled(true);
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildUse", item.getType().toString()));
}
return;
}
if (event.hasBlock() && !metaPermCheck(user, "interact", event.getClickedBlock())) {
event.setCancelled(true);
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildInteract", event.getClickedBlock().getType().toString()));
}
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onCraftItemEvent(final CraftItemEvent event) {
HumanEntity entity = event.getWhoClicked();
if (entity instanceof Player) {
final User user = ess.getUser((Player) entity);
final ItemStack item = event.getRecipe().getResult();
if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (!metaPermCheck(user, "craft", item.getType(), item.getDurability())) {
event.setCancelled(true);
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildCraft", item.getType().toString()));
}
}
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerDropItem(final PlayerDropItemEvent event) {
final User user = ess.getUser(event.getPlayer());
final ItemStack item = event.getItemDrop().getItemStack();
if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (!metaPermCheck(user, "drop", item.getType(), item.getDurability())) {
event.setCancelled(true);
user.getBase().updateInventory();
if (ess.getSettings().warnOnBuildDisallow()) {
user.sendMessage(tl("antiBuildDrop", item.getType().toString()));
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockDispense(final BlockDispenseEvent event) {
final ItemStack item = event.getItem();
if (prot.checkProtectionItems(AntiBuildConfig.blacklist_dispenser, item.getType())) {
event.setCancelled(true);
}
}
private class EntityPickupItemListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerPickupItem(EntityPickupItemEvent event) {
if (!(event.getEntity() instanceof Player)) return;
final User user = ess.getUser((Player) event.getEntity());
final ItemStack item = event.getItem().getItemStack();
if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (!metaPermCheck(user, "pickup", item.getType(), item.getDurability())) {
event.setCancelled(true);
event.getItem().setPickupDelay(50);
}
}
}
}
private class PlayerPickupItemListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
final User user = ess.getUser(event.getPlayer());
final ItemStack item = event.getItem().getItemStack();
if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) {
if (!metaPermCheck(user, "pickup", item.getType(), item.getDurability())) {
event.setCancelled(true);
event.getItem().setPickupDelay(50);
}
}
}
}
}

View file

@ -1,62 +0,0 @@
package com.earth2me.essentials.antibuild;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
class EssentialsConnect {
private static final Logger logger = Logger.getLogger("EssentialsAntiBuild");
private final transient IEssentials ess;
private final transient IAntiBuild protect;
EssentialsConnect(Plugin essPlugin, Plugin essProtect) {
if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) {
logger.log(Level.WARNING, tl("versionMismatchAll"));
}
ess = (IEssentials) essPlugin;
protect = (IAntiBuild) essProtect;
AntiBuildReloader pr = new AntiBuildReloader();
pr.reloadConfig();
ess.addReloadListener(pr);
}
IEssentials getEssentials() {
return ess;
}
void alert(final User user, final String item, final String type) {
final Location loc = user.getLocation();
final String warnMessage = tl("alertFormat", user.getName(), type, item, loc.getWorld().getName() + "," + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ());
logger.log(Level.WARNING, warnMessage);
for (Player p : ess.getServer().getOnlinePlayers()) {
final User alertUser = ess.getUser(p);
if (alertUser.isAuthorized("essentials.protect.alerts")) {
alertUser.sendMessage(warnMessage);
}
}
}
private class AntiBuildReloader implements IConf {
@Override
public void reloadConfig() {
for (AntiBuildConfig protectConfig : AntiBuildConfig.values()) {
if (protectConfig.isList()) {
protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName()));
} else {
protect.getSettingsBoolean().put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean()));
}
}
}
}
}

View file

@ -1,20 +0,0 @@
package com.earth2me.essentials.antibuild;
import org.bukkit.Material;
import org.bukkit.plugin.Plugin;
import java.util.List;
import java.util.Map;
public interface IAntiBuild extends Plugin {
boolean checkProtectionItems(final AntiBuildConfig list, final Material mat);
boolean getSettingBool(final AntiBuildConfig protectConfig);
EssentialsConnect getEssentialsConnect();
Map<AntiBuildConfig, Boolean> getSettingsBoolean();
Map<AntiBuildConfig, List<Material>> getSettingsList();
}

View file

@ -1,10 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsAntiBuild
main: com.earth2me.essentials.antibuild.EssentialsAntiBuild
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: ${full.version}
website: http://tiny.cc/EssentialsCommands
description: Provides build protection.
authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits, Iaccidentally]
depend: [Essentials]
api-version: 1.13

View file

@ -1,25 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.17.1</version>
</parent>
<artifactId>EssentialsXChat</artifactId>
<build>
<finalName>EssentialsXChat-${full.version}</finalName>
</build>
<dependencies>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>EssentialsX</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View file

@ -1,43 +0,0 @@
package com.earth2me.essentials.chat;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
class ChatStore {
private final User user;
private final String type;
private final Trade charge;
private long radius;
ChatStore(final IEssentials ess, final User user, final String type) {
this.user = user;
this.type = type;
this.charge = new Trade(getLongType(), ess);
}
User getUser() {
return user;
}
Trade getCharge() {
return charge;
}
String getType() {
return type;
}
final String getLongType() {
return type.length() == 0 ? "chat" : "chat-" + type;
}
long getRadius() {
return radius;
}
void setRadius(long radius) {
this.radius = radius;
}
}

View file

@ -1,47 +0,0 @@
package com.earth2me.essentials.chat;
import com.earth2me.essentials.metrics.Metrics;
import net.ess3.api.IEssentials;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsChat extends JavaPlugin {
private transient Metrics metrics = null;
@Override
public void onEnable() {
final PluginManager pluginManager = getServer().getPluginManager();
final IEssentials ess = (IEssentials) pluginManager.getPlugin("Essentials");
if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) {
getLogger().log(Level.WARNING, tl("versionMismatchAll"));
}
if (!ess.isEnabled()) {
this.setEnabled(false);
return;
}
final Map<AsyncPlayerChatEvent, ChatStore> chatStore = Collections.synchronizedMap(new HashMap<>());
final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, chatStore);
final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, chatStore);
final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, chatStore);
pluginManager.registerEvents(playerListenerLowest, this);
pluginManager.registerEvents(playerListenerNormal, this);
pluginManager.registerEvents(playerListenerHighest, this);
if (metrics == null) {
metrics = new Metrics(this);
}
}
}

View file

@ -1,75 +0,0 @@
package com.earth2me.essentials.chat;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import org.bukkit.Server;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.Map;
import java.util.logging.Logger;
public abstract class EssentialsChatPlayer implements Listener {
static final Logger logger = Logger.getLogger("EssentialsChat");
transient IEssentials ess;
final transient Server server;
private final transient Map<AsyncPlayerChatEvent, ChatStore> chatStorage;
EssentialsChatPlayer(final Server server, final IEssentials ess, final Map<AsyncPlayerChatEvent, ChatStore> chatStorage) {
this.ess = ess;
this.server = server;
this.chatStorage = chatStorage;
}
public abstract void onPlayerChat(final AsyncPlayerChatEvent event);
boolean isAborted(final AsyncPlayerChatEvent event) {
return event.isCancelled();
}
String getChatType(final String message) {
if (message.length() == 0) {
//Ignore empty chat events generated by plugins
return "";
}
final char prefix = message.charAt(0);
if (prefix == ess.getSettings().getChatShout()) {
return "shout";
} else if (prefix == ess.getSettings().getChatQuestion()) {
return "question";
} else {
return "";
}
}
ChatStore getChatStore(final AsyncPlayerChatEvent event) {
return chatStorage.get(event);
}
void setChatStore(final AsyncPlayerChatEvent event, final ChatStore chatStore) {
chatStorage.put(event, chatStore);
}
ChatStore delChatStore(final AsyncPlayerChatEvent event) {
return chatStorage.remove(event);
}
private void charge(final User user, final Trade charge) throws ChargeException {
charge.charge(user);
}
boolean charge(final AsyncPlayerChatEvent event, final ChatStore chatStore) {
try {
charge(chatStore.getUser(), chatStore.getCharge());
} catch (ChargeException e) {
ess.showError(chatStore.getUser().getSource(), e, "\\ chat " + chatStore.getLongType());
event.setCancelled(true);
return false;
}
return true;
}
}

View file

@ -1,28 +0,0 @@
package com.earth2me.essentials.chat;
import net.ess3.api.IEssentials;
import org.bukkit.Server;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.Map;
public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer {
EssentialsChatPlayerListenerHighest(final Server server, final IEssentials ess, final Map<AsyncPlayerChatEvent, ChatStore> chatStorage) {
super(server, ess, chatStorage);
}
@EventHandler(priority = EventPriority.HIGHEST)
@Override
public void onPlayerChat(final AsyncPlayerChatEvent event) {
final ChatStore chatStore = delChatStore(event);
if (isAborted(event) || chatStore == null) {
return;
}
// This file should handle charging the user for the action before returning control back
charge(event, chatStore);
}
}

View file

@ -1,63 +0,0 @@
package com.earth2me.essentials.chat;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.scoreboard.Team;
import java.util.Locale;
import java.util.Map;
public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer {
EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess, final Map<AsyncPlayerChatEvent, ChatStore> chatStorage) {
super(server, ess, chatStorage);
}
@EventHandler(priority = EventPriority.LOWEST)
@Override
public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (isAborted(event)) {
return;
}
final User user = ess.getUser(event.getPlayer());
if (user == null) {
event.setCancelled(true);
return;
}
final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage()));
setChatStore(event, chatStore);
// This listener should apply the general chat formatting only...then return control back the event handler
event.setMessage(FormatUtil.formatMessage(user, "essentials.chat", event.getMessage()));
String group = user.getGroup();
String world = user.getWorld().getName();
Player player = user.getBase();
String prefix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(player));
String suffix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(player));
Team team = player.getScoreboard().getPlayerTeam(player);
String format = ess.getSettings().getChatFormat(group);
format = format.replace("{0}", group);
format = format.replace("{1}", world);
format = format.replace("{2}", world.substring(0, 1).toUpperCase(Locale.ENGLISH));
format = format.replace("{3}", team == null ? "" : team.getPrefix());
format = format.replace("{4}", team == null ? "" : team.getSuffix());
format = format.replace("{5}", team == null ? "" : team.getDisplayName());
format = format.replace("{6}", prefix);
format = format.replace("{7}", suffix);
format = format.replace("{8}", player.getName());
synchronized (format) {
event.setFormat(format);
}
}
}

View file

@ -1,119 +0,0 @@
package com.earth2me.essentials.chat;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import net.ess3.api.events.LocalChatSpyEvent;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.*;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer {
EssentialsChatPlayerListenerNormal(final Server server, final IEssentials ess, final Map<AsyncPlayerChatEvent, ChatStore> chatStorage) {
super(server, ess, chatStorage);
}
@EventHandler(priority = EventPriority.NORMAL)
@Override
public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (isAborted(event)) {
return;
}
// This file should handle detection of the local chat features; if local chat is enabled, we need to handle it here
long radius = ess.getSettings().getChatRadius();
if (radius < 1) {
return;
}
radius *= radius;
final ChatStore chatStore = getChatStore(event);
final User user = chatStore.getUser();
chatStore.setRadius(radius);
if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) {
final StringBuilder permission = new StringBuilder();
permission.append("essentials.chat.").append(chatStore.getType());
if (user.isAuthorized(permission.toString())) {
event.setMessage(event.getMessage().substring(1));
event.setFormat(tl(chatStore.getType() + "Format", event.getFormat()));
return;
}
user.sendMessage(tl("notAllowedTo" + chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH) + chatStore.getType().substring(1)));
event.setCancelled(true);
return;
}
final Location loc = user.getLocation();
final World world = loc.getWorld();
if (!charge(event, chatStore)) {
return;
}
Set<Player> outList = event.getRecipients();
Set<Player> spyList = new HashSet<>();
try {
outList.add(event.getPlayer());
} catch (UnsupportedOperationException ex) {
if (ess.getSettings().isDebug()) {
logger.log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex);
}
return;
}
final String format = event.getFormat();
event.setFormat(tl("chatTypeLocal").concat(event.getFormat()));
logger.info(tl("localFormat", user.getName(), event.getMessage()));
final Iterator<Player> it = outList.iterator();
while (it.hasNext()) {
final Player onlinePlayer = it.next();
final User onlineUser = ess.getUser(onlinePlayer);
if (!onlineUser.equals(user)) {
boolean abort = false;
final Location playerLoc = onlineUser.getLocation();
if (playerLoc.getWorld() != world) {
abort = true;
} else {
final double delta = playerLoc.distanceSquared(loc);
if (delta > chatStore.getRadius()) {
abort = true;
}
}
if (abort) {
if (onlineUser.isAuthorized("essentials.chat.spy")) {
spyList.add(onlinePlayer);
}
it.remove();
}
}
}
if (outList.size() < 2) {
user.sendMessage(tl("localNoOne"));
}
LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), format, event.getMessage(), spyList);
server.getPluginManager().callEvent(spyEvent);
if (!spyEvent.isCancelled()) {
for (Player onlinePlayer : spyEvent.getRecipients()) {
onlinePlayer.sendMessage(String.format(spyEvent.getFormat(), user.getDisplayName(), spyEvent.getMessage()));
}
}
}
}

View file

@ -1,10 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsChat
main: com.earth2me.essentials.chat.EssentialsChat
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: ${full.version}
website: http://tiny.cc/EssentialsCommands
description: Provides chat control features for Essentials. Requires Permissions.
authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits, md_5, Okamosy, Iaccidentally]
depend: [Essentials]
api-version: 1.13

View file

@ -1,62 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.17.1</version>
</parent>
<artifactId>EssentialsXGeoIP</artifactId>
<build>
<finalName>EssentialsXGeoIP-${full.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>javatar:javatar</include>
<include>com.maxmind.geoip2:geoip2</include>
<include>com.maxmind.db:maxmind-db</include>
<include>com.fasterxml.jackson.core:*</include>
</includes>
</artifactSet>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>EssentialsX</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>javatar</groupId>
<artifactId>javatar</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
</project>

View file

@ -1,39 +0,0 @@
package com.earth2me.essentials.geoip;
import com.earth2me.essentials.metrics.Metrics;
import net.ess3.api.IEssentials;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsGeoIP extends JavaPlugin {
private transient Metrics metrics = null;
@Override
public void onEnable() {
final PluginManager pm = getServer().getPluginManager();
final IEssentials ess = (IEssentials) pm.getPlugin("Essentials");
if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) {
getLogger().log(Level.WARNING, tl("versionMismatchAll"));
}
if (!ess.isEnabled()) {
this.setEnabled(false);
return;
}
final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess);
pm.registerEvents(playerListener, this);
getLogger().log(Level.INFO, "This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/.");
if (metrics == null) {
metrics = new Metrics(this);
}
}
}

View file

@ -1,230 +0,0 @@
package com.earth2me.essentials.geoip;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.User;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.exception.*;
import net.ess3.api.IEssentials;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.Date;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.Arrays;
import com.ice.tar.TarInputStream;
import com.ice.tar.TarEntry;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsGeoIPPlayerListener implements Listener, IConf {
private DatabaseReader mmreader = null; // initialize maxmind geoip2 reader
private static final Logger logger = Logger.getLogger("EssentialsGeoIP");
private File databaseFile;
private File dataFolder;
private final EssentialsConf config;
private final transient IEssentials ess;
EssentialsGeoIPPlayerListener(File dataFolder, IEssentials ess) {
this.ess = ess;
this.dataFolder = dataFolder;
this.config = new EssentialsConf(new File(dataFolder, "config.yml"));
config.setTemplateName("/config.yml", EssentialsGeoIP.class);
reloadConfig();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(final PlayerJoinEvent event) {
ess.runTaskAsynchronously(() -> delayedJoin(event.getPlayer()));
}
private void delayedJoin(Player player) {
User u = ess.getUser(player);
if (u.isAuthorized("essentials.geoip.hide") || player.getAddress() == null) {
return;
}
InetAddress address = player.getAddress().getAddress();
StringBuilder sb = new StringBuilder();
try {
if (config.getBoolean("database.show-cities", false)) {
CityResponse response = mmreader.city(address);
if (response == null) {
return;
}
String city;
String region;
String country;
city = response.getCity().getName();
region = response.getMostSpecificSubdivision().getName();
country = response.getCountry().getName();
if (city != null) {
sb.append(city).append(", ");
}
if (region != null) {
sb.append(region).append(", ");
}
sb.append(country);
} else {
CountryResponse response = mmreader.country(address);
sb.append(response.getCountry().getName());
}
} catch (AddressNotFoundException ex) {
if (checkIfLocal(address)) {
for (Player online : player.getServer().getOnlinePlayers()) {
User user = ess.getUser(online);
if (user.isAuthorized("essentials.geoip.show")) {
user.sendMessage(tl("geoipCantFind", u.getDisplayName()));
}
}
return;
}
// GeoIP2 API forced this when address not found in their DB. jar will not complied without this.
// TODO: Maybe, we can set a new custom msg about addr-not-found in messages.properties.
logger.log(Level.INFO, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage());
} catch (IOException | GeoIp2Exception ex) {
// GeoIP2 API forced this when address not found in their DB. jar will not complied without this.
logger.log(Level.SEVERE, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage());
}
if (config.getBoolean("show-on-whois", true)) {
u.setGeoLocation(sb.toString());
}
if (config.getBoolean("show-on-login", true) && !u.isHidden()) {
for (Player onlinePlayer : player.getServer().getOnlinePlayers()) {
User user = ess.getUser(onlinePlayer);
if (user.isAuthorized("essentials.geoip.show")) {
user.sendMessage(tl("geoipJoinFormat", u.getDisplayName(), sb.toString()));
}
}
}
}
@Override
public final void reloadConfig() {
config.load();
// detect and update the old config.yml. migrate from legacy GeoIP to GeoIP2.
if (!config.isSet("enable-locale")) {
config.set("database.download-url", "https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz");
config.set("database.download-url-city", "https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz");
config.set("database.update.enable", true);
config.set("database.update.by-every-x-days", 30);
config.set("enable-locale", true);
config.save();
// delete old GeoIP.dat fiiles
File oldDatFile = new File(dataFolder, "GeoIP.dat");
File oldDatFileCity = new File(dataFolder, "GeoIP-City.dat");
oldDatFile.delete();
oldDatFileCity.delete();
}
if (config.getBoolean("database.show-cities", false)) {
databaseFile = new File(dataFolder, "GeoIP2-City.mmdb");
} else {
databaseFile = new File(dataFolder, "GeoIP2-Country.mmdb");
}
if (!databaseFile.exists()) {
if (config.getBoolean("database.download-if-missing", true)) {
downloadDatabase();
} else {
logger.log(Level.SEVERE, tl("cantFindGeoIpDB"));
return;
}
} else if (config.getBoolean("database.update.enable", true)) {
// try to update expired mmdb files
long diff = new Date().getTime() - databaseFile.lastModified();
if (diff/24/3600/1000>config.getLong("database.update.by-every-x-days", 30)) {
downloadDatabase();
}
}
try {
// locale setting
if (config.getBoolean("enable-locale")) {
// Get geolocation based on Essentials' locale. If the locale is not avaliable, use "en".
String locale = ess.getI18n().getCurrentLocale().toString().replace('_', '-');
mmreader = new DatabaseReader.Builder(databaseFile).locales(Arrays.asList(locale,"en")).build();
} else {
mmreader = new DatabaseReader.Builder(databaseFile).build();
}
} catch (IOException ex) {
logger.log(Level.SEVERE, tl("cantReadGeoIpDB"), ex);
}
}
private void downloadDatabase() {
try {
String url;
if (config.getBoolean("database.show-cities", false)) {
url = config.getString("database.download-url-city");
} else {
url = config.getString("database.download-url");
}
if (url == null || url.isEmpty()) {
logger.log(Level.SEVERE, tl("geoIpUrlEmpty"));
return;
}
logger.log(Level.INFO, tl("downloadingGeoIp"));
URL downloadUrl = new URL(url);
URLConnection conn = downloadUrl.openConnection();
conn.setConnectTimeout(10000);
conn.connect();
InputStream input = conn.getInputStream();
OutputStream output = new FileOutputStream(databaseFile);
byte[] buffer = new byte[2048];
if (url.endsWith(".gz")) {
input = new GZIPInputStream(input);
if (url.endsWith(".tar.gz")) {
// The new GeoIP2 uses tar.gz to pack the db file along with some other txt. So it makes things a bit complicated here.
String filename;
TarInputStream tarInputStream = new TarInputStream(input);
TarEntry entry;
while ((entry = tarInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
filename = entry.getName();
if (filename.substring(filename.length() - 5).equalsIgnoreCase(".mmdb")) {
input = tarInputStream;
break;
}
}
}
}
}
int length = input.read(buffer);
while (length >= 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
output.close();
input.close();
} catch (MalformedURLException ex) {
logger.log(Level.SEVERE, tl("geoIpUrlInvalid"), ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, tl("connectionFailed"), ex);
}
}
private boolean checkIfLocal(InetAddress address) {
if (address.isAnyLocalAddress() || address.isLoopbackAddress()) {
return true;
}
// Double checks if address is defined on any interface
try {
return NetworkInterface.getByInetAddress(address) != null;
} catch (SocketException e) {
return false;
}
}
}

View file

@ -1,16 +0,0 @@
database:
show-cities: false
download-if-missing: true
# Url for country
download-url: "https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz"
# Url for cities
download-url-city: "https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz"
update:
enable: true
by-every-x-days: 30
show-on-login: true
show-on-whois: true
# "enable-locale" enables locale on geolocation display.
# Language is determined by Essentials/config.yml "locale" section.
# Not all languages are supported. See https://dev.maxmind.com/geoip/geoip2/web-services/#Languages
enable-locale: true

View file

@ -1,10 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsGeoIP
main: com.earth2me.essentials.geoip.EssentialsGeoIP
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: ${full.version}
website: http://tiny.cc/EssentialsCommands
description: Shows the country or city of a user on login and /whois.
authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, kjiang]
depend: [Essentials]
api-version: 1.13

View file

@ -1,25 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.17.1</version>
</parent>
<artifactId>EssentialsXProtect</artifactId>
<build>
<finalName>EssentialsXProtect-${full.version}</finalName>
</build>
<dependencies>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>EssentialsX</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View file

@ -1,64 +0,0 @@
package com.earth2me.essentials.protect;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.PluginEnableEvent;
public class EmergencyListener implements Listener {
private EssentialsProtect plugin;
EmergencyListener(final EssentialsProtect essProtPlugin) {
plugin = essProtPlugin;
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockBurn(final BlockBurnEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockIgnite(final BlockIgniteEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockFromTo(final BlockFromToEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(final BlockBreakEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event) {
event.getPlayer().sendMessage("Essentials Protect is in emergency mode. Check your log for errors.");
}
@EventHandler(priority = EventPriority.LOW)
public void onEntityExplode(final EntityExplodeEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onEntityDamage(final EntityDamageEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onPluginEnabled(final PluginEnableEvent event) {
if (event.getPlugin().getName().equals("Essentials")) {
plugin.disableEmergencyMode();
}
}
}

View file

@ -1,47 +0,0 @@
package com.earth2me.essentials.protect;
import com.earth2me.essentials.IConf;
import net.ess3.api.IEssentials;
import org.bukkit.plugin.Plugin;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
class EssentialsConnect {
private static final Logger logger = Logger.getLogger("EssentialsProtect");
private final IEssentials ess;
private final IProtect protect;
EssentialsConnect(Plugin essPlugin, Plugin essProtect) {
if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) {
logger.log(Level.WARNING, tl("versionMismatchAll"));
}
ess = (IEssentials) essPlugin;
protect = (IProtect) essProtect;
ProtectReloader pr = new ProtectReloader();
pr.reloadConfig();
ess.addReloadListener(pr);
}
IEssentials getEssentials() {
return ess;
}
private class ProtectReloader implements IConf {
@Override
public void reloadConfig() {
for (ProtectConfig protectConfig : ProtectConfig.values()) {
if (protectConfig.isList()) {
protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName()));
} else if (protectConfig.isString()) {
protect.getSettingsString().put(protectConfig, ess.getSettings().getProtectString(protectConfig.getConfigName()));
} else {
protect.getSettingsBoolean().put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean()));
}
}
}
}
}

View file

@ -1,114 +0,0 @@
package com.earth2me.essentials.protect;
import com.earth2me.essentials.metrics.Metrics;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class EssentialsProtect extends JavaPlugin implements IProtect {
private final Map<ProtectConfig, Boolean> settingsBoolean = new EnumMap<>(ProtectConfig.class);
private final Map<ProtectConfig, String> settingsString = new EnumMap<>(ProtectConfig.class);
private final Map<ProtectConfig, List<Material>> settingsList = new EnumMap<>(ProtectConfig.class);
private EssentialsConnect ess = null;
private transient Metrics metrics = null;
private final EmergencyListener emListener = new EmergencyListener(this);
@Override
public void onEnable() {
final PluginManager pm = this.getServer().getPluginManager();
final Plugin essPlugin = pm.getPlugin("Essentials");
if (essPlugin == null || !essPlugin.isEnabled()) {
enableEmergencyMode(pm);
return;
}
initialize(pm, essPlugin);
if (metrics == null) {
metrics = new Metrics(this);
}
}
private void initialize(final PluginManager pm, final Plugin essPlugin) {
getLogger().log(Level.INFO, "Continuing to enable Protect.");
ess = new EssentialsConnect(essPlugin, this);
final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this);
pm.registerEvents(blockListener, this);
final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this);
pm.registerEvents(entityListener, this);
final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this);
pm.registerEvents(weatherListener, this);
}
private void enableEmergencyMode(final PluginManager pm) {
pm.registerEvents(emListener, this);
for (Player player : getServer().getOnlinePlayers()) {
player.sendMessage("Essentials Protect is in emergency mode. Check your log for errors.");
}
getLogger().log(Level.SEVERE, "Essentials not installed or failed to load. Essentials Protect is in emergency mode now.");
}
void disableEmergencyMode() {
final PluginManager pm = this.getServer().getPluginManager();
final Plugin essPlugin = pm.getPlugin("Essentials");
if (essPlugin == null || !essPlugin.isEnabled()) {
getLogger().log(Level.SEVERE, "Tried to disable emergency mode, but Essentials still isn't enabled!");
return;
}
HandlerList.unregisterAll(emListener);
for (Player player : getServer().getOnlinePlayers()) {
player.sendMessage("Essentials Protect is no longer in emergency mode.");
}
getLogger().log(Level.SEVERE, "Essentials was loaded late! Essentials Protect is no longer in emergency mode.");
initialize(pm, essPlugin);
}
@Override
public EssentialsConnect getEssentialsConnect() {
return ess;
}
@Override
public Map<ProtectConfig, Boolean> getSettingsBoolean() {
return settingsBoolean;
}
@Override
public Map<ProtectConfig, String> getSettingsString() {
return settingsString;
}
@Override
public Map<ProtectConfig, List<Material>> getSettingsList() {
return settingsList;
}
@Override
public boolean getSettingBool(final ProtectConfig protectConfig) {
final Boolean bool = settingsBoolean.get(protectConfig);
return bool == null ? protectConfig.getDefaultValueBoolean() : bool;
}
@Override
public String getSettingString(final ProtectConfig protectConfig) {
final String str = settingsString.get(protectConfig);
return str == null ? protectConfig.getDefaultValueString() : str;
}
}

View file

@ -1,93 +0,0 @@
package com.earth2me.essentials.protect;
import com.earth2me.essentials.utils.EnumUtil;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.world.PortalCreateEvent;
import java.util.Set;
public class EssentialsProtectBlockListener implements Listener {
private static final Set<Material> WATER_TYPES = EnumUtil.getAllMatching(Material.class, "WATER", "STATIONARY_WATER");
private static final Set<Material> LAVA_TYPES = EnumUtil.getAllMatching(Material.class, "LAVA", "STATIONARY_LAVA");
final private IProtect prot;
EssentialsProtectBlockListener(final IProtect parent) {
this.prot = parent;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.getBlock().getType() == Material.OBSIDIAN || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_fire_spread));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL)) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_flint_fire));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_fire_spread));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lightning_fire_spread));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FIREBALL)) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_fireball_fire));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromTo(final BlockFromToEvent event) {
final Block block = event.getBlock();
if (WATER_TYPES.contains(block.getType())) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_flow));
return;
}
if (LAVA_TYPES.contains(block.getType())) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_flow));
return;
}
if (block.getType() == Material.AIR) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBurn(final BlockBurnEvent event) {
if (prot.getSettingBool(ProtectConfig.prevent_fire_spread)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPortalLight(PortalCreateEvent event) {
if (event.getReason() == PortalCreateEvent.CreateReason.FIRE) {
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation));
}
}
}

View file

@ -1,226 +0,0 @@
package com.earth2me.essentials.protect;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import org.bukkit.entity.*;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityTargetEvent.TargetReason;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import java.util.Locale;
public class EssentialsProtectEntityListener implements Listener {
private final IProtect prot;
private final IEssentials ess;
EssentialsProtectEntityListener(final IProtect prot) {
this.prot = prot;
this.ess = prot.getEssentialsConnect().getEssentials();
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(final EntityDamageEvent event) {
final Entity target = event.getEntity();
if (target instanceof Villager && prot.getSettingBool(ProtectConfig.prevent_villager_death)) {
event.setCancelled(true);
return;
}
User user = null;
if (target instanceof Player) {
user = ess.getUser((Player) target);
}
final DamageCause cause = event.getCause();
if (event instanceof EntityDamageByBlockEvent) {
if (prot.getSettingBool(ProtectConfig.disable_contactdmg) && cause == DamageCause.CONTACT && !(target instanceof Player && shouldBeDamaged(user, "contact"))) {
event.setCancelled(true);
return;
}
if (prot.getSettingBool(ProtectConfig.disable_lavadmg) && cause == DamageCause.LAVA && !(target instanceof Player && shouldBeDamaged(user, "lava"))) {
event.setCancelled(true);
return;
}
if (prot.getSettingBool(ProtectConfig.prevent_tnt_explosion) && cause == DamageCause.BLOCK_EXPLOSION && !(target instanceof Player && shouldBeDamaged(user, "tnt"))) {
event.setCancelled(true);
return;
}
}
if (event instanceof EntityDamageByEntityEvent) {
final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent) event;
final Entity eAttack = edEvent.getDamager();
User attacker = null;
if (eAttack instanceof Player) {
attacker = ess.getUser((Player) eAttack);
}
//Creeper explode prevention
if (eAttack instanceof Creeper && (prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) || prot.getSettingBool(ProtectConfig.prevent_creeper_playerdmg)) && !(target instanceof Player && shouldBeDamaged(user, "creeper"))) {
event.setCancelled(true);
return;
}
if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) && prot.getSettingBool(ProtectConfig.prevent_fireball_playerdmg) && !(target instanceof Player && shouldBeDamaged(user, "fireball"))) {
event.setCancelled(true);
return;
}
if (event.getEntity() instanceof WitherSkull && prot.getSettingBool(ProtectConfig.prevent_witherskull_playerdmg) && !(target instanceof Player && shouldBeDamaged(user, "witherskull"))) {
event.setCancelled(true);
return;
}
if (eAttack instanceof TNTPrimed && prot.getSettingBool(ProtectConfig.prevent_tnt_playerdmg) && !(target instanceof Player && shouldBeDamaged(user, "tnt"))) {
event.setCancelled(true);
return;
}
if (eAttack instanceof ExplosiveMinecart && prot.getSettingBool(ProtectConfig.prevent_tntminecart_playerdmg) && !(target instanceof Player && shouldBeDamaged(user, "tnt-minecart"))) {
event.setCancelled(true);
return;
}
// PVP Settings
if (target instanceof Player && eAttack instanceof Player && prot.getSettingBool(ProtectConfig.disable_pvp) && !user.getName().equalsIgnoreCase(attacker.getName()) && (!user.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp"))) {
event.setCancelled(true);
return;
}
if (edEvent.getDamager() instanceof Projectile && target instanceof Player && ((prot.getSettingBool(ProtectConfig.disable_projectiles) && !shouldBeDamaged(user, "projectiles")) || (((Projectile) edEvent.getDamager()).getShooter() instanceof Player && prot.getSettingBool(ProtectConfig.disable_pvp) && (!user.isAuthorized("essentials.protect.pvp") || !ess.getUser((Player) ((Projectile) edEvent.getDamager()).getShooter()).isAuthorized("essentials.protect.pvp"))))) {
event.setCancelled(true);
return;
}
}
if (target instanceof Player) {
if (cause == DamageCause.FALL && prot.getSettingBool(ProtectConfig.disable_fall) && !shouldBeDamaged(user, "fall")) {
event.setCancelled(true);
return;
}
if (cause == DamageCause.SUFFOCATION && prot.getSettingBool(ProtectConfig.disable_suffocate) && !shouldBeDamaged(user, "suffocation")) {
event.setCancelled(true);
return;
}
if ((cause == DamageCause.FIRE || cause == DamageCause.FIRE_TICK) && prot.getSettingBool(ProtectConfig.disable_firedmg) && !shouldBeDamaged(user, "fire")) {
event.setCancelled(true);
return;
}
if (cause == DamageCause.DROWNING && prot.getSettingBool(ProtectConfig.disable_drown) && !shouldBeDamaged(user, "drowning")) {
event.setCancelled(true);
return;
}
if (cause == DamageCause.LIGHTNING && prot.getSettingBool(ProtectConfig.disable_lightning) && !shouldBeDamaged(user, "lightning")) {
event.setCancelled(true);
return;
}
if (cause == DamageCause.WITHER && prot.getSettingBool(ProtectConfig.disable_wither) && !shouldBeDamaged(user, "wither")) {
event.setCancelled(true);
}
}
}
private boolean shouldBeDamaged(final User user, final String type) {
return (user.isAuthorized("essentials.protect.damage.".concat(type)) && !user.isAuthorized("essentials.protect.damage.disable"));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityExplode(final EntityExplodeEvent event) {
if (event.getEntity() == null) {
return;
}
Entity entity = event.getEntity();
final int maxHeight = ess.getSettings().getProtectCreeperMaxHeight();
if (entity instanceof EnderDragon && prot.getSettingBool(ProtectConfig.prevent_enderdragon_blockdmg)) {
event.setCancelled(true);
if (prot.getSettingBool(ProtectConfig.enderdragon_fakeexplosions)) {
event.getLocation().getWorld().createExplosion(event.getLocation(), 0F);
}
return;
}
if (entity instanceof Wither && prot.getSettingBool(ProtectConfig.prevent_wither_spawnexplosion)) {
event.setCancelled(true);
} else if (entity instanceof Creeper && (prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) || prot.getSettingBool(ProtectConfig.prevent_creeper_blockdmg) || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))) {
//Nicccccccccce plaaacccccccccce..
event.setCancelled(true);
event.getLocation().getWorld().createExplosion(event.getLocation(), 0F);
} else if (entity instanceof TNTPrimed && prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)) {
event.setCancelled(true);
} else if (entity instanceof Fireball && prot.getSettingBool(ProtectConfig.prevent_fireball_explosion)) {
event.setCancelled(true);
} else if ((entity instanceof WitherSkull) && prot.getSettingBool(ProtectConfig.prevent_witherskull_explosion)) {
event.setCancelled(true);
} else if ((entity instanceof ExplosiveMinecart) && prot.getSettingBool(ProtectConfig.prevent_tntminecart_explosion)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCreatureSpawn(final CreatureSpawnEvent event) {
if (event.getEntity() instanceof Player) {
return;
}
final EntityType creature = event.getEntityType();
if (creature == null) {
return;
}
final String creatureName = creature.toString().toLowerCase(Locale.ENGLISH);
if (creatureName.isEmpty()) {
return;
}
if (ess.getSettings().getProtectPreventSpawn(creatureName)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityTarget(final EntityTargetEvent event) {
if (!(event.getTarget() instanceof Player)) {
return;
}
final User user = ess.getUser((Player) event.getTarget());
if ((event.getReason() == TargetReason.CLOSEST_PLAYER || event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY || event.getReason() == TargetReason.TARGET_ATTACKED_NEARBY_ENTITY || event.getReason() == TargetReason.RANDOM_TARGET || event.getReason() == TargetReason.DEFEND_VILLAGE || event.getReason() == TargetReason.TARGET_ATTACKED_OWNER || event.getReason() == TargetReason.OWNER_ATTACKED_TARGET) && prot.getSettingBool(ProtectConfig.prevent_entitytarget) && !user.isAuthorized("essentials.protect.entitytarget.bypass")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) && prot.getSettingBool(ProtectConfig.prevent_fireball_fire)) {
event.setFire(false);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (event.getEntityType() == EntityType.ENDERMAN && prot.getSettingBool(ProtectConfig.prevent_enderman_pickup)) {
event.setCancelled(true);
return;
}
if (event.getEntityType() == EntityType.WITHER && prot.getSettingBool(ProtectConfig.prevent_wither_blockreplace)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPaintingBreak(HangingBreakByEntityEvent event) {
if ((event.getCause() == HangingBreakEvent.RemoveCause.ENTITY) && ((event.getRemover() instanceof Creeper) && prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) || (((event.getRemover() instanceof Fireball) || (event.getRemover() instanceof SmallFireball)) && prot.getSettingBool(ProtectConfig.prevent_fireball_explosion)) || ((event.getRemover() instanceof TNTPrimed) && prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)) || ((event.getRemover() instanceof WitherSkull) && prot.getSettingBool(ProtectConfig.prevent_witherskull_explosion)))) {
event.setCancelled(true);
}
}
}

View file

@ -1,38 +0,0 @@
package com.earth2me.essentials.protect;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
public class EssentialsProtectWeatherListener implements Listener {
private final IProtect prot;
EssentialsProtectWeatherListener(final IProtect prot) {
this.prot = prot;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWeatherChange(final WeatherChangeEvent event) {
if (prot.getSettingBool(ProtectConfig.disable_weather_storm) && event.toWeatherState()) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLightningStrike(final LightningStrikeEvent event) {
if (prot.getSettingBool(ProtectConfig.disable_weather_lightning)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onThunderChange(final ThunderChangeEvent event) {
if (prot.getSettingBool(ProtectConfig.disable_weather_thunder) && event.toThunderState()) {
event.setCancelled(true);
}
}
}

View file

@ -1,22 +0,0 @@
package com.earth2me.essentials.protect;
import org.bukkit.Material;
import org.bukkit.plugin.Plugin;
import java.util.List;
import java.util.Map;
public interface IProtect extends Plugin {
boolean getSettingBool(final ProtectConfig protectConfig);
String getSettingString(final ProtectConfig protectConfig);
EssentialsConnect getEssentialsConnect();
Map<ProtectConfig, Boolean> getSettingsBoolean();
Map<ProtectConfig, String> getSettingsString();
Map<ProtectConfig, List<Material>> getSettingsList();
}

View file

@ -1,92 +0,0 @@
package com.earth2me.essentials.protect;
public enum ProtectConfig {
disable_contactdmg("protect.disable.contactdmg", false),
disable_lavadmg("protect.disable.lavadmg", false),
disable_pvp("protect.disable.pvp", false),
disable_projectiles("protect.disable.projectiles", false),
disable_fall("protect.disable.fall", false),
disable_suffocate("protect.disable.suffocate", false),
disable_firedmg("protect.disable.firedmg", false),
disable_lightning("protect.disable.lightning", false),
disable_drown("protect.disable.drown", false),
disable_wither("protect.disable.wither", false),
disable_weather_storm("protect.disable.weather.storm", false),
disable_weather_lightning("protect.disable.weather.lightning", false),
disable_weather_thunder("protect.disable.weather.thunder", false),
prevent_fire_spread("protect.prevent.fire-spread", true),
prevent_flint_fire("protect.prevent.flint-fire", false),
prevent_lava_fire_spread("protect.prevent.lava-fire-spread", true),
prevent_lightning_fire_spread("protect.prevent.lightning-fire-spread", true),
prevent_water_flow("protect.prevent.water-flow", false),
prevent_lava_flow("protect.prevent.lava-flow", false),
prevent_water_bucket_flow("protect.prevent.water-bucket-flow", false),
prevent_portal_creation("protect.prevent.portal-creation", false),
prevent_block_on_rail("protect.protect.prevent-block-on-rails", false),
prevent_tnt_explosion("protect.prevent.tnt-explosion", false),
prevent_tnt_playerdmg("protect.prevent.tnt-playerdamage", false),
prevent_tntminecart_explosion("protect.prevent.tnt-minecart-explosion", false),
prevent_tntminecart_playerdmg("protect.prevent.tnt-minecart-playerdamage", false),
prevent_fireball_explosion("protect.prevent.fireball-explosion", false),
prevent_fireball_fire("protect.prevent.fireball-fire", false),
prevent_fireball_playerdmg("protect.prevent.fireball-playerdamage", false),
prevent_witherskull_explosion("protect.prevent.witherskull-explosion", false),
prevent_witherskull_playerdmg("protect.prevent.witherskull-playerdamage", false),
prevent_wither_spawnexplosion("protect.prevent.wither-spawnexplosion", false),
prevent_wither_blockreplace("protect.prevent.wither-blockreplace", false),
prevent_creeper_explosion("protect.prevent.creeper-explosion", true),
prevent_creeper_playerdmg("protect.prevent.creeper-playerdamage", false),
prevent_creeper_blockdmg("protect.prevent.creeper-blockdamage", false),
prevent_enderman_pickup("protect.prevent.enderman-pickup", false),
prevent_villager_death("protect.prevent.villager-death", false),
prevent_enderdragon_blockdmg("protect.prevent.enderdragon-blockdamage", true),
prevent_entitytarget("protect.prevent.entitytarget", false),
enderdragon_fakeexplosions("protect.enderdragon-fakeexplosions", false);
private final String configName;
private final String defValueString;
private final boolean defValueBoolean;
private final boolean isList;
private final boolean isString;
ProtectConfig(final String configName, final boolean defValueBoolean) {
this(configName, null, defValueBoolean, false, false);
}
ProtectConfig(final String configName, final String defValueString, final boolean defValueBoolean, final boolean isList, final boolean isString) {
this.configName = configName;
this.defValueString = defValueString;
this.defValueBoolean = defValueBoolean;
this.isList = isList;
this.isString = isString;
}
/**
* @return the configName
*/
public String getConfigName() {
return configName;
}
/**
* @return the default value String
*/
public String getDefaultValueString() {
return defValueString;
}
/**
* @return the default value boolean
*/
public boolean getDefaultValueBoolean() {
return defValueBoolean;
}
public boolean isString() {
return isString;
}
public boolean isList() {
return isList;
}
}

View file

@ -1,10 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsProtect
main: com.earth2me.essentials.protect.EssentialsProtect
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: ${full.version}
website: http://tiny.cc/EssentialsCommands
description: Provides protection for various parts of the world.
authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits]
softdepend: [Essentials]
api-version: 1.13

View file

@ -23,7 +23,7 @@ public class Commandspawn extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
if (args.length > 0 && user.isAuthorized("essentials.spawn.others")) {
if (args.length > 0 && getTFMHandler().isAdmin(user)) {
final User otherUser = getPlayer(server, user, args, 0);
respawn(user.getSource(), user, otherUser, charge);
if (!otherUser.equals(user)) {

View file

@ -1,50 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.17.1</version>
</parent>
<artifactId>EssentialsXXMPP</artifactId>
<build>
<finalName>EssentialsXXMPP-${full.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>EssentialsX</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack</artifactId>
<version>3.2.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,23 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import org.bukkit.Server;
public class Commandsetxmpp extends EssentialsCommand {
public Commandsetxmpp() {
super("setxmpp");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
EssentialsXMPP.getInstance().setAddress(user.getBase(), args[0]);
user.sendMessage("XMPP address set to " + args[0]);
}
}

View file

@ -1,33 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import org.bukkit.Server;
public class Commandxmpp extends EssentialsCommand {
public Commandxmpp() {
super("xmpp");
}
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException {
if (args.length < 2) {
throw new NotEnoughArgumentsException();
}
final String address = EssentialsXMPP.getInstance().getAddress(args[0]);
if (address == null) {
sender.sendMessage("§cThere are no players matching that name.");
} else {
final String message = getFinalArg(args, 1);
final String senderName = sender.isPlayer() ? ess.getUser(sender.getPlayer()).getDisplayName() : Console.NAME;
sender.sendMessage("[" + senderName + ">" + address + "] " + message);
if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) {
sender.sendMessage("§cError sending message.");
}
}
}
}

View file

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

View file

@ -1,137 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.metrics.Metrics;
import net.ess3.api.IUser;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP {
private static EssentialsXMPP instance = null;
private transient UserManager users;
private transient XMPPManager xmpp;
private transient IEssentials ess;
private transient Metrics metrics = null;
static IEssentialsXMPP getInstance() {
return instance;
}
@Override
public void onEnable() {
instance = this;
final PluginManager pluginManager = getServer().getPluginManager();
ess = (IEssentials) pluginManager.getPlugin("Essentials");
if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) {
getLogger().log(Level.WARNING, tl("versionMismatchAll"));
}
if (!ess.isEnabled()) {
this.setEnabled(false);
return;
}
final EssentialsXMPPPlayerListener playerListener = new EssentialsXMPPPlayerListener(ess);
pluginManager.registerEvents(playerListener, this);
users = new UserManager(this.getDataFolder());
xmpp = new XMPPManager(this);
ess.addReloadListener(users);
ess.addReloadListener(xmpp);
if (metrics == null) {
metrics = new Metrics(this);
metrics.addCustomChart(new Metrics.SimplePie("config-valid", () -> xmpp.isConfigValid() ? "yes" : "no"));
}
}
@Override
public void onDisable() {
if (xmpp != null) {
xmpp.disconnect();
}
instance = null;
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) {
return ess.onCommandEssentials(sender, command, commandLabel, args, EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", null);
}
@Override
public void setAddress(final Player user, final String address) {
final String username = user.getName().toLowerCase(Locale.ENGLISH);
instance.users.setAddress(username, address);
}
@Override
public String getAddress(final String name) {
return instance.users.getAddress(name);
}
@Override
public IUser getUserByAddress(final String address) {
String username = instance.users.getUserByAddress(address);
return username == null ? null : ess.getUser(username);
}
@Override
public boolean toggleSpy(final Player user) {
final String username = user.getName().toLowerCase(Locale.ENGLISH);
final boolean spy = !instance.users.isSpy(username);
instance.users.setSpy(username, spy);
return spy;
}
@Override
public String getAddress(final Player user) {
return instance.users.getAddress(user.getName());
}
@Override
public boolean sendMessage(final Player user, final String message) {
return instance.xmpp.sendMessage(instance.users.getAddress(user.getName()), message);
}
@Override
public boolean sendMessage(final String address, final String message) {
return instance.xmpp.sendMessage(address, message);
}
static void updatePresence() {
instance.xmpp.updatePresence();
}
@Override
public List<String> getSpyUsers() {
return instance.users.getSpyUsers();
}
@Override
public void broadcastMessage(final IUser sender, final String message, final String xmppAddress) {
ess.broadcastMessage(sender, message);
try {
for (String address : getSpyUsers()) {
if (!address.equalsIgnoreCase(xmppAddress)) {
sendMessage(address, message);
}
}
} catch (Exception ignored) {}
}
@Override
public IEssentials getEss() {
return ess;
}
}

View file

@ -1,59 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.List;
class EssentialsXMPPPlayerListener implements Listener {
private final transient IEssentials ess;
EssentialsXMPPPlayerListener(final IEssentials ess) {
super();
this.ess = ess;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(final PlayerJoinEvent event) {
final User user = ess.getUser(event.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, EssentialsXMPP::updatePresence);
sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game");
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(final AsyncPlayerChatEvent event) {
final User user = ess.getUser(event.getPlayer());
sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage()));
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(final PlayerQuitEvent event) {
final User user = ess.getUser(event.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, EssentialsXMPP::updatePresence);
sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game");
}
private void sendMessageToSpyUsers(final String message) {
try {
List<String> users = EssentialsXMPP.getInstance().getSpyUsers();
synchronized (users) {
for (final String address : users) {
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, () -> EssentialsXMPP.getInstance().sendMessage(address, message));
}
}
} catch (Exception ignored) {}
}
}

View file

@ -1,31 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.IEssentials;
import net.ess3.api.IUser;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.List;
public interface IEssentialsXMPP extends Plugin {
String getAddress(final Player user);
String getAddress(final String name);
List<String> getSpyUsers();
IUser getUserByAddress(final String address);
boolean sendMessage(final Player user, final String message);
boolean sendMessage(final String address, final String message);
void setAddress(final Player user, final String address);
boolean toggleSpy(final Player user);
void broadcastMessage(final IUser sender, final String message, final String xmppAddress);
IEssentials getEss();
}

View file

@ -1,75 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.IConf;
import java.io.File;
import java.util.*;
public class UserManager implements IConf {
private final transient EssentialsConf users;
private final transient List<String> spyusers = Collections.synchronizedList(new ArrayList<>());
private static final String ADDRESS = "address";
private static final String SPY = "spy";
UserManager(final File folder) {
users = new EssentialsConf(new File(folder, "users.yml"));
reloadConfig();
}
final boolean isSpy(final String username) {
return users.getBoolean(username.toLowerCase(Locale.ENGLISH) + "." + SPY, false);
}
void setSpy(final String username, final boolean spy) {
setUser(username.toLowerCase(Locale.ENGLISH), getAddress(username), spy);
}
final String getAddress(final String username) {
return users.getString(username.toLowerCase(Locale.ENGLISH) + "." + ADDRESS, null);
}
final String getUserByAddress(final String search) {
final Set<String> usernames = users.getKeys(false);
for (String username : usernames) {
final String address = users.getString(username + "." + ADDRESS, null);
if (search.equalsIgnoreCase(address)) {
return username;
}
}
return null;
}
void setAddress(final String username, final String address) {
setUser(username.toLowerCase(Locale.ENGLISH), address, isSpy(username));
}
List<String> getSpyUsers() {
return spyusers;
}
private void setUser(final String username, final String address, final boolean spy) {
final Map<String, Object> userdata = new HashMap<>();
userdata.put(ADDRESS, address);
userdata.put(SPY, spy);
users.setProperty(username, userdata);
users.save();
reloadConfig();
}
@Override
public final void reloadConfig() {
users.load();
spyusers.clear();
final Set<String> keys = users.getKeys(false);
for (String key : keys) {
if (isSpy(key)) {
final String address = getAddress(key);
if (address != null) {
spyusers.add(address);
}
}
}
}
}

View file

@ -1,321 +0,0 @@
package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.IUser;
import org.bukkit.entity.Player;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import java.io.File;
import java.util.*;
import java.util.logging.*;
public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf {
private static final Logger logger = Logger.getLogger("EssentialsXMPP");
private static final SimpleFormatter formatter = new SimpleFormatter();
private final transient EssentialsConf config;
private transient XMPPConnection connection;
private transient ChatManager chatManager;
private final transient Map<String, Chat> chats = Collections.synchronizedMap(new HashMap<>());
private final transient Set<LogRecord> logrecords = Collections.synchronizedSet(new HashSet<>());
private final transient IEssentialsXMPP parent;
private transient List<String> logUsers;
private transient Level logLevel;
private transient boolean ignoreLagMessages = true;
private transient Thread loggerThread;
private transient boolean threadrunning = true;
XMPPManager(final IEssentialsXMPP parent) {
super();
this.parent = parent;
config = new EssentialsConf(new File(parent.getDataFolder(), "config.yml"));
config.setTemplateName("/config.yml", EssentialsXMPP.class);
reloadConfig();
}
boolean sendMessage(final String address, final String message) {
if (address != null && !address.isEmpty()) {
try {
startChat(address);
final Chat chat;
synchronized (chats) {
chat = chats.get(address);
}
if (chat != null) {
if (!connection.isConnected()) {
disconnect();
connect();
}
chat.sendMessage(FormatUtil.stripFormat(message));
return true;
}
} catch (XMPPException ex) {
disableChat(address);
}
}
return false;
}
@Override
public void processMessage(final Chat chat, final Message msg) {
// Normally we should log the error message
// But we would create a loop if the connection to a log-user fails.
if (msg.getType() != Message.Type.error && msg.getBody().length() > 0) {
final String message = msg.getBody();
switch (message.charAt(0)) {
case '@':
sendPrivateMessage(chat, message);
break;
case '/':
sendCommand(chat, message);
break;
default:
final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant()));
parent.broadcastMessage(sender, "=" + sender.getBase().getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant()));
}
}
}
private boolean connect() {
final String server = config.getString("xmpp.server");
if (server == null || server.equals("example.com")) {
logger.log(Level.WARNING, "config broken for xmpp");
return false;
}
final int port = config.getInt("xmpp.port", 5222);
final String serviceName = config.getString("xmpp.servicename", server);
final String xmppuser = config.getString("xmpp.user");
final String password = config.getString("xmpp.password");
final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName);
String stringBuilder = "Connecting to xmpp server " + server + ":" + port + " as user " + xmppuser + ".";
logger.log(Level.INFO, stringBuilder);
connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false));
connConf.setSendPresence(true);
connConf.setReconnectionAllowed(true);
connConf.setDebuggerEnabled(config.getBoolean("debug", false));
connection = new XMPPConnection(connConf);
try {
connection.connect();
connection.login(xmppuser, password, "Essentials-XMPP");
connection.sendPacket(new Presence(Presence.Type.available, "No one online.", 2, Presence.Mode.available));
connection.getRoster().setSubscriptionMode(SubscriptionMode.accept_all);
chatManager = connection.getChatManager();
chatManager.addChatListener(this);
return true;
} catch (XMPPException ex) {
logger.log(Level.WARNING, "Failed to connect to server: " + server, ex);
return false;
}
}
final void disconnect() {
if (loggerThread != null) {
loggerThread.interrupt();
}
if (chatManager != null) {
chatManager.removeChatListener(this);
chatManager = null;
}
if (connection != null) {
connection.disconnect(new Presence(Presence.Type.unavailable));
}
}
final void updatePresence() {
final int usercount;
final StringBuilder stringBuilder = new StringBuilder();
usercount = parent.getEss().getOnlinePlayers().size();
if (usercount == 0) {
final String presenceMsg = "No one online.";
connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.dnd));
}
if (usercount == 1) {
final String presenceMsg = "1 player online.";
connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.available));
}
if (usercount > 1) {
stringBuilder.append(usercount).append(" players online.");
connection.sendPacket(new Presence(Presence.Type.available, stringBuilder.toString(), 2, Presence.Mode.available));
}
}
@Override
public void chatCreated(final Chat chat, final boolean createdLocally) {
if (!createdLocally) {
chat.addMessageListener(this);
final Chat old = chats.put(StringUtils.parseBareAddress(chat.getParticipant()), chat);
if (old != null) {
old.removeMessageListener(this);
}
}
}
@Override
public final void reloadConfig() {
logger.removeHandler(this);
config.load();
synchronized (chats) {
disconnect();
chats.clear();
if (!connect()) {
return;
}
startLoggerThread();
}
if (config.getBoolean("log-enabled", false)) {
logger.addHandler(this);
logUsers = config.getStringList("log-users");
final String level = config.getString("log-level", "info");
try {
logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
logLevel = Level.INFO;
}
ignoreLagMessages = config.getBoolean("ignore-lag-messages", true);
}
}
@Override
public void publish(final LogRecord logRecord) {
try {
if (ignoreLagMessages && logRecord.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) {
return;
}
if (logRecord.getLevel().intValue() >= logLevel.intValue()) {
synchronized (logrecords) {
logrecords.add(logRecord);
}
}
} catch (Exception ignored) {
// Ignore all exceptions
// Otherwise we create a loop.
}
}
@Override
public void flush() {
// Ignore this
}
@Override
public void close() throws SecurityException {
// Ignore this
}
private void startLoggerThread() {
loggerThread = new Thread(() -> {
final Set<LogRecord> copy = new HashSet<>();
final Set<String> failedUsers = new HashSet<>();
while (threadrunning) {
synchronized (logrecords) {
if (!logrecords.isEmpty()) {
copy.addAll(logrecords);
logrecords.clear();
}
}
if (!copy.isEmpty()) {
for (String user : logUsers) {
try {
XMPPManager.this.startChat(user);
for (LogRecord logRecord : copy) {
final String message = formatter.format(logRecord);
if (!XMPPManager.this.sendMessage(user, FormatUtil.stripLogColorFormat(message))) {
failedUsers.add(user);
break;
}
}
} catch (XMPPException ex) {
failedUsers.add(user);
logger.removeHandler(XMPPManager.this);
logger.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex);
}
}
logUsers.removeAll(failedUsers);
if (logUsers.isEmpty()) {
logger.removeHandler(XMPPManager.this);
threadrunning = false;
}
copy.clear();
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
threadrunning = false;
}
}
logger.removeHandler(XMPPManager.this);
});
loggerThread.start();
}
private void startChat(final String address) throws XMPPException {
if (chatManager == null) {
return;
}
synchronized (chats) {
if (!chats.containsKey(address)) {
final Chat chat = chatManager.createChat(address, this);
if (chat == null) {
throw new XMPPException("Could not start Chat with " + address);
}
chats.put(address, chat);
}
}
}
private void sendPrivateMessage(final Chat chat, final String message) {
final String[] parts = message.split(" ", 2);
if (parts.length == 2) {
final List<Player> matches = parent.getServer().matchPlayer(parts[0].substring(1));
if (matches.isEmpty()) {
try {
chat.sendMessage("User " + parts[0] + " not found");
} catch (XMPPException ex) {
logger.log(Level.WARNING, "Failed to send xmpp message.", ex);
}
} else {
final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">";
for (Player p : matches) {
p.sendMessage(from + p.getDisplayName() + "] " + message);
}
}
}
}
private void sendCommand(final Chat chat, final String message) {
if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant()))) {
try {
parent.getServer().dispatchCommand(Console.getInstance().getCommandSender(), message.substring(1));
} catch (Exception ex) {
logger.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
private void disableChat(final String address) {
final Chat chat = chats.get(address);
if (chat != null) {
chat.removeMessageListener(this);
chats.remove(address);
}
}
public boolean isConfigValid() {
final String server = config.getString("xmpp.server");
return server != null && !server.equals("example.com");
}
}

View file

@ -1,17 +0,0 @@
xmpp:
server: 'example.com'
user: 'name@example.com'
password: 'password'
# servicename: 'example.com'
# port: 5222
# sasl-enabled: false
op-users:
# - 'name@example.com'
debug: false
log-enabled: false
# Level is minimum level that should be send: info, warning, severe
log-level: warning
log-users:
# - 'name@example.com'

View file

@ -1,20 +0,0 @@
# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.)
name: EssentialsXMPP
main: com.earth2me.essentials.xmpp.EssentialsXMPP
# Note to developers: This next line cannot change, or the automatic versioning system will break.
version: ${full.version}
website: http://ess.khhq.net/wiki/XMPP
description: Provides XMPP communication.
authors: [snowleo]
depend: [Essentials]
api-version: 1.13
commands:
setxmpp:
description: Sets your XMPP address.
usage: /<command> <address>
xmpp:
description: Sends a message to a player.
usage: /<command> <player> <message>
xmppspy:
description: Toggles XMPP spy for all messages.
usage: /<command> <player>

View file

@ -1 +0,0 @@
craftbukkit-*.jar

View file

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>EssentialsXParent</artifactId>
<groupId>net.ess3</groupId>
<version>2.17.1</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>1_8_R1Provider</artifactId>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>NMSProvider</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
</project>

View file

@ -1,46 +0,0 @@
package net.ess3.nms.v1_8_R1;
import net.ess3.nms.SpawnerProvider;
import net.minecraft.server.v1_8_R1.NBTTagCompound;
import org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
public class v1_8_R1SpawnerProvider extends SpawnerProvider {
@Override
public ItemStack setEntityType(ItemStack is, EntityType type) {
net.minecraft.server.v1_8_R1.ItemStack itemStack;
CraftItemStack craftStack = CraftItemStack.asCraftCopy(is);
itemStack = CraftItemStack.asNMSCopy(craftStack);
NBTTagCompound tag = itemStack.getTag();
if (tag == null) {
tag = new NBTTagCompound();
itemStack.setTag(tag);
}
if (!tag.hasKey("BlockEntityTag")) {
tag.set("BlockEntityTag", new NBTTagCompound());
}
tag = itemStack.getTag().getCompound("BlockEntityTag");
tag.setString("EntityId", type.getName());
ItemStack bukkitItemStack = CraftItemStack.asCraftMirror(itemStack).clone();
return setDisplayName(bukkitItemStack, type);
}
@Override
public EntityType getEntityType(ItemStack is) {
net.minecraft.server.v1_8_R1.ItemStack itemStack;
CraftItemStack craftStack = CraftItemStack.asCraftCopy(is);
itemStack = CraftItemStack.asNMSCopy(craftStack);
NBTTagCompound tag = itemStack.getTag();
if (tag == null || !tag.hasKey("BlockEntityTag")) {
throw new IllegalArgumentException();
}
String name = tag.getCompound("BlockEntityTag").getString("EntityId");
return EntityType.fromName(name);
}
@Override
public String getHumanName() {
return "CraftBukkit 1.8 NMS-based provider";
}
}

View file

@ -1 +0,0 @@
craftbukkit-*.jar

View file

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>EssentialsXParent</artifactId>
<groupId>net.ess3</groupId>
<version>2.17.1</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>1_8_R2Provider</artifactId>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>NMSProvider</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
</project>

View file

@ -1,46 +0,0 @@
package net.ess3.nms.v1_8_R2;
import net.ess3.nms.SpawnerProvider;
import net.minecraft.server.v1_8_R2.NBTTagCompound;
import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
public class v1_8_R2SpawnerProvider extends SpawnerProvider {
@Override
public ItemStack setEntityType(ItemStack is, EntityType type) {
net.minecraft.server.v1_8_R2.ItemStack itemStack;
CraftItemStack craftStack = CraftItemStack.asCraftCopy(is);
itemStack = CraftItemStack.asNMSCopy(craftStack);
NBTTagCompound tag = itemStack.getTag();
if (tag == null) {
tag = new NBTTagCompound();
itemStack.setTag(tag);
}
if (!tag.hasKey("BlockEntityTag")) {
tag.set("BlockEntityTag", new NBTTagCompound());
}
tag = itemStack.getTag().getCompound("BlockEntityTag");
tag.setString("EntityId", type.getName());
ItemStack bukkitItemStack = CraftItemStack.asCraftMirror(itemStack).clone();
return setDisplayName(bukkitItemStack, type);
}
@Override
public EntityType getEntityType(ItemStack is) {
net.minecraft.server.v1_8_R2.ItemStack itemStack;
CraftItemStack craftStack = CraftItemStack.asCraftCopy(is);
itemStack = CraftItemStack.asNMSCopy(craftStack);
NBTTagCompound tag = itemStack.getTag();
if (tag == null || !tag.hasKey("BlockEntityTag")) {
throw new IllegalArgumentException();
}
String name = tag.getCompound("BlockEntityTag").getString("EntityId");
return EntityType.fromName(name);
}
@Override
public String getHumanName() {
return "CraftBukkit 1.8.3 NMS-based provider";
}
}

View file

@ -1,51 +0,0 @@
package net.ess3.nms.refl;
import net.ess3.nms.refl.ReflUtil.NMSVersion;
import org.junit.Assert;
import org.junit.Test;
public class NMSVersionTest {
@Test
public void testMajor() {
NMSVersion v2_9_R1 = NMSVersion.fromString("v2_9_R1");
Assert.assertEquals(2, v2_9_R1.getMajor());
Assert.assertEquals(9, v2_9_R1.getMinor());
Assert.assertEquals(1, v2_9_R1.getRelease());
Assert.assertEquals(v2_9_R1.toString(), "v2_9_R1");
Assert.assertTrue(v2_9_R1.isHigherThan(NMSVersion.fromString("v1_10_R1")));
Assert.assertTrue(v2_9_R1.isHigherThanOrEqualTo(NMSVersion.fromString("v1_9_R1")));
}
@Test
public void testMinor() {
NMSVersion v1_10_R1 = NMSVersion.fromString("v1_10_R1");
Assert.assertEquals(1, v1_10_R1.getMajor());
Assert.assertEquals(10, v1_10_R1.getMinor());
Assert.assertEquals(1, v1_10_R1.getRelease());
Assert.assertEquals(v1_10_R1.toString(), "v1_10_R1");
Assert.assertTrue(NMSVersion.fromString("v1_9_R1").isLowerThan(v1_10_R1));
Assert.assertTrue(NMSVersion.fromString("v1_9_R1").isLowerThanOrEqualTo(v1_10_R1));
}
@Test
public void testRelease() {
NMSVersion v1_9_R2 = NMSVersion.fromString("v1_9_R2");
Assert.assertEquals(1, v1_9_R2.getMajor());
Assert.assertEquals(9, v1_9_R2.getMinor());
Assert.assertEquals(2, v1_9_R2.getRelease());
Assert.assertEquals(v1_9_R2.toString(), "v1_9_R2");
Assert.assertEquals(v1_9_R2, NMSVersion.fromString("v1_9_R2"));
Assert.assertTrue(v1_9_R2.isHigherThan(NMSVersion.fromString("v1_9_R1")));
}
}

14
pom.xml
View file

@ -35,20 +35,19 @@
<id>paper-repo</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>rayzr-repo</id>
<url>https://cdn.rawgit.com/Rayzr522/maven-repo/master/</url>
</repository>
</repositories>
<modules>
<module>Essentials</module>
<module>EssentialsAntiBuild</module>
<module>EssentialsChat</module>
<module>EssentialsGeoIP</module>
<module>EssentialsProtect</module>
<module>EssentialsSpawn</module>
<module>EssentialsXMPP</module>
<module>nms/NMSProvider</module>
<module>nms/UpdatedMetaProvider</module>
<module>nms/1_8_R1Provider</module>
<module>nms/1_8_R2Provider</module>
<!--<module>nms/1_8_R1Provider</module>
<module>nms/1_8_R2Provider</module>-->
<module>nms/LegacyProvider</module>
<module>nms/ReflectionProvider</module>
<module>nms/FlattenedProvider</module>
@ -78,7 +77,6 @@
<build>
<defaultGoal>clean install</defaultGoal>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>