Compare commits

..
848 Commits
Author SHA1 Message Date
JRoy a6edf04a60 Release 2.18.2 2020-11-16 11:32:40 +00:00
Josh Roy 3ba675a899 Allow users to modify existing homes when over homes limit (#3776)
Fixes #3761
2020-11-15 17:40:34 +00:00
pop4959 1fed7a9a3a Fix tab completion for delhome (#3775)
There was a minor issue with one line of code in delhome which was causing the user's homes not to be listed since the condition was effectively reversed. This was also causing an NPE for console senders attempting to tab complete.

Fixes #3774
2020-11-14 22:50:48 +00:00
80fb91b6d7 Fix /clear <player> <item> not clearing offhand (#3715)
Co-authored-by: Kenichycmd <kenichycmd@gmail.com>
Co-authored-by: MD <1917406+mdcfe@users.noreply.github.com>
2020-11-09 16:43:55 +00:00
Josh Roy 5b0c2a4131 Use ray-tracing based target block for 1.13.2+ (#3763)
Uses new method of ray-tracing to target block instead of using BlockIterator which doesn't respect the player looking at a different y-level. Falls back to old BlockIterator method on server versions older than 1.13.2

Fixes #3756.
2020-11-09 16:38:02 +00:00
Josh Roy bb43e8f7b6 Add option to prevent replying from vanished players (#3703)
Closes #2066
2020-11-09 12:25:16 +00:00
Josh Roy 4d9a10147a Split backup command by space (#3762)
Splits command sent to ProcessBuilder by spaces. Fixes backup commands with arguments

Fixes #3759
2020-11-09 08:52:35 +00:00
Josh Roy ea4f5cf919 Update to 1.16.4 (#3753) 2020-11-02 13:36:48 -08:00
dependabot[bot] 295bc9f76d Bump junit from 4.12 to 4.13.1 (#3726)
Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-10-23 00:19:54 +01:00
MD 327806d9a1 Add new PR templates and revamp issue templates (#3711)
Adds new PR templates and revamps the existing issue templates to (hopefully) make the PR/issue submission easier to understand.
2020-10-23 00:19:04 +01:00
Josh Roy 80e7558fc0 Move some tab complete messages to debug mode only (#3739) 2020-10-22 12:15:02 -07:00
md678685 9cda59511e Consolidate permissions default setup into single class 2020-10-19 21:27:05 +01:00
md678685 c12a031918 Add more specific platform support messages 2020-10-19 21:26:38 +01:00
Alexander SöderbergandMD a4f580e319 Make HelpInput use the known command map (#3675)
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

This PR makes HelpInput use knownCommands in the command map, rather than relying on plugin descriptions. This means that commands that have been registered programmatically (or impromptu) will be recognized and displayed in the help menu.

The ugly reflection is due to Spigot not exposing the command map getter. This has been tested on Spigot 1.8, 1.16.3 and Paper 1.16.3 with plugins that register commands directly to the command map.
2020-10-19 15:27:40 +01:00
md678685 583bf88207 Implement ConsoleCommandSender methods 2020-10-19 15:06:50 +01:00
montlikadani a5f8e83e03 Remove redundant checks in the tree command (#3716) 2020-10-13 00:47:12 -07:00
Alexander Söderberg e2f17f11d3 Tab-complete plugin names in /help (#3713)
Plugin names are accepted as input to `/essentials:help`, but they are not completed. This makes it easier to lookup plugin commands.
2020-10-07 11:54:30 -07:00
md678685 4f8c040d06 Add link to Register license notice 2020-10-05 17:34:55 +01:00
Josh Roy af1d068022 Add more inventory commands (#3704)
Add more commands to access virtual crafting inventories (on platforms with the required APIs).

Closes #3195 and #108.
2020-10-05 14:45:33 +01:00
Andre_601andMD 1bd8d1c85c Update old EssentialsX URLs in issue templates (#3678)
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

This updates the old essentialsx.github.io domains to the new essentialsx.net one.
2020-10-05 14:20:17 +01:00
pop4959 d7fc859d14 Use username instead of nickname in console /sell messages (#3693)
Closes #3662

This PR changes the default placeholder `{0}` to username. Display name can still be used with `{5}`.

Before change:
messages.properties
`itemSoldConsole=\u00a7e{0} \u00a7asold\u00a7e {1}\u00a7a for \u00a7e{2} \u00a7a({3} items at {4} each).`
console
`[Essentials] ~test sold dirt for $64 (64 items at $1 each).`

After change:
messages.properties
`itemSoldConsole=\u00a7e{0} \u00a7asold\u00a7e {1}\u00a7a for \u00a7e{2} \u00a7a({3} items at {4} each).`
console
`[Essentials] pop4959 sold dirt for $64 (64 items at $1 each).`

messages.properties
`itemSoldConsole=\u00a7e{5} \u00a7asold\u00a7e {1}\u00a7a for \u00a7e{2} \u00a7a({3} items at {4} each).`
console
`[Essentials] ~test sold dirt for $64 (64 items at $1 each).`
2020-10-05 09:50:56 +01:00
Ryan ac953cd114 Remove sign color codes from trade.log (#3699)
Started looking into #3116 but noticed this issue and wanted to fix it first.

Also added a comment as to why the username is truncated as this took me a long time to figure out and seemed arbitrary. Probably could truncate the username later for trade signs only as other signs don't require any username to be present on the sign. However, for now I simply opted to document.
2020-10-05 09:47:12 +01:00
md678685 6e6dd041d5 Add Javadocs to most API classes 2020-10-04 19:59:42 +01:00
md678685 9b3c8a9df2 Reformat and fix Checkstyle violations 2020-10-04 19:59:42 +01:00
md678685 234a481b0d Add Checkstyle rules and suppressions
This commit adds Checkstyle rules for EssentialsX, based on those from the adventure library (https://github.com/KyoriPowered/adventure/tree/master/.checkstyle).

It also makes Checkstyle passes mandatory for a GH build to pass.
2020-10-04 19:59:42 +01:00
pop4959 89b3c9233e Bump Paperlib version (#3695) 2020-10-03 12:29:43 -07:00
Josh Roy 5d61a43fe1 Add balanceTopLine i18n translation string (#3626) 2020-09-25 19:16:12 -07:00
Olivia 29d5ccf751 Fix /lightning ignoring essentials.lightning.others (#3671) 2020-09-13 17:23:50 -07:00
l1ttleO fde0665593 Update Readme to list 1.16.3 as a supported version (#3666) 2020-09-12 10:58:54 -07:00
l1ttleO 29541b0995 Bump supported server version to 1.16.3 (#3664) 2020-09-12 10:37:18 -07:00
Josh Roy 05f31c5ddf Fix time command throwing exceptions when used in console (#3622)
Fixes #3621
2020-09-09 16:00:13 +01:00
JRoy f89840545d Revert clearinventory command to pre-command-refactor
This command is too big to rewrite without a behavior change
2020-09-09 15:52:59 +01:00
JRoy 18534f8576 Fix inverted messages in Commandpaytoggle 2020-09-09 15:52:38 +01:00
JRoy 1382a05dc8 Fix IEssentials#getOnlineUsers ABI breakage 2020-09-09 15:52:37 +01:00
JRoy 1671d4839c Clean up some tab completes that I missed 2020-09-09 15:52:29 +01:00
Josh Roy 4d2fbd04c5 Fix /sell and /worth messages displaying {1} instead of the item(s) value (#3656) 2020-09-08 12:36:05 -07:00
md678685 dc6b9b89cd Handle funky bStats classloading correctly
Fixes bStats for plugins that do funky classloading things, like AntiVPN.
2020-08-29 20:37:20 +01:00
Josh Roy 76f36aa895 [CI-SKIP] Some issue template updates (#3623)
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

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

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

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

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

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

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

Fixes #3579 (async `/skull` command)
Fixes #3336 (improve codestyle of commands)
Partially addresses #3339 (`/spawn` and `/setspawn` are now hidden from tabcomplete)
Closes #3087 (`/paytoggle` is now a loop command)
2020-08-11 19:09:22 +01:00
pop4959 14c6c2a055 Fix spawner delay feature (#3239)
Closes #1332

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

This can be replicated easily by spawning some skeleton traps like so:
`/summon skeleton_horse ~ ~ ~ {SkeletonTrap:1}`
and then attempting to run `/killall skeletonhorse`.

After this small change, any tamed skeleton horses will be retained, but non-player-owned skeleton horses will be removed as appropriate.

Closes #3475.
2020-07-09 19:36:08 +01:00
MD 07fa87dc6a Deny tpahere requests to players without permission to accept (#3478) 2020-07-09 10:45:14 -07:00
pop4959 b58c98bea0 Add jail contexts (#3476)
Someone probably wants these. Also, who in the world decided that `IJails::getList` should throw an exception?

https://user-images.githubusercontent.com/17698576/87005099-57ffc080-c173-11ea-956f-0b64a52c7f40.png

https://user-images.githubusercontent.com/17698576/87005107-5afab100-c173-11ea-8d25-6efde7ee9026.png

https://user-images.githubusercontent.com/17698576/87005382-c5135600-c173-11ea-9335-e80e322afd89.png

https://user-images.githubusercontent.com/17698576/87005299-a44b0080-c173-11ea-8789-f2f0d8b9cc4b.png
2020-07-09 08:41:25 +01:00
zml 08e553bd1a Hide EssX commands from non-core modules in autocomplete (#3473)
quick little thing so people stop complaining
2020-07-09 08:37:41 +01:00
Josh Roy e35fb82bc2 Add UserTeleportHomeEvent (#3403)
Adds an event which allows developers to see & cancel when users attempt to teleport home. This event is needed over `PreTeleportEvent` due to the fact that it would be extremely difficult to accurately filter it by the /home command.

Closes #3401
2020-07-08 19:53:32 +01:00
MD a92ca63ca9 Replace UserTeleportEvent with more sane events (#3192)
This PR replaces UserTeleportEvent with two new teleport events called at different stages:
- TeleportWarmupEvent; called before a user's teleport warmup begins and allows plugins to skip it or prevent a teleportation
- PreTeleportEvent; called after the warmup completes but before any safety checks are carried out

This is a **breaking change** as it removes UserTeleportEvent, but the previous event isn't useful or descriptive in its current form and was only recently introduced, so it's unlikely that many plugins already depend on this.

Closes #2506.
2020-07-08 19:51:00 +01:00
pop4959 cbfad7b320 Choose better elevation for random nether teleport (#3466) 2020-07-07 18:19:53 -07:00
MD c16987fb87 Add config option to hide join/quit messages above X players (#3464) 2020-07-07 15:16:20 -07:00
Flask Bot 477f5a7841 New Crowdin updates (#3462) 2020-07-07 20:41:06 +01:00
md678685 6f149224d1 Fix reporting of economy backend to bStats 2020-07-06 21:15:03 +01:00
Josh Roy 1a6ad2fdb0 Allow for specifying amount to increase itemstack in /more (#3302)
Fixes #2342.
2020-07-06 19:55:07 +01:00
pop4959 76e511a774 Implement random teleport command (#3418)
Adds `/tpr` and `/settpr` commands, which respectively allow you to teleport randomly or set teleportation parameters.

Server owners are expected to set the center with `/settpr` before players can use `/tpr`. They can also set the minimum and maximum range to be teleported from the center (default 0-1000).

Also includes an event where plugins can adjust or cancel the teleport.

Closes #3154.
2020-07-06 19:53:43 +01:00
Josh RoyandMD 9681933ec2 Add mute expiry time in mute messages (#3329)
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

Closes #1211.
2020-07-06 19:52:51 +01:00
711bfed557 Add itemlore command (#3331)
Co-authored-by: pop4959 <pop4959@gmail.com>
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

Adds a command to add to or clear an item's lore.

Closes #1911.
2020-07-06 19:46:57 +01:00
zml 016a1b3421 Handle explicitly denied permissions with no perms plugin (#3419)
to finally end the `/hat` saga, hopefully for good
2020-07-06 19:40:47 +01:00
MD 01b9ec4a42 Allow preventing bed and respawn anchor explosions in Protect (#3453)
Adds `bed-explosion` and `respawn-anchor-explosion` options to the Protect config.
2020-07-06 19:38:07 +01:00
pop4959 9b729dd091 unchange 1.13 naming 2020-07-06 11:34:43 -07:00
triagonal 0a73be2082 Add PrivateMessageSentEvent and fix PrivateMessagePreSendEvent (#3432)
This PR introduces a new private messaging related event `PrivateMessageSentEvent` and fixes a mistake made on my part during the implementation of `PrivateMessagePreSendEvent`.

Recently when attempting to use the pre-send event in order to play a sound to the recipient of a message, I found that the event was not completely adequate for my use case. Between the firing of the pre-send event and the end of the delivery attempt, the message delivery could fail for a number of reasons (e.g. messages toggled off, sender ignored, unreachable recipient) with no straightforward way of determining this using the existing event.

I believe that a second event fired after the message sending attempt has been fully processed will provide a simple method of determining whether or not a message was successfully delivered by including the [`MessageResponse`](https://github.com/EssentialsX/Essentials/blob/60f54ee37d9472848e28d2e64adc2735e10975c1/Essentials/src/com/earth2me/essentials/messaging/IMessageRecipient.java#L84) in the event.

Additionally, I found that when implementing the pre-send event, I mistakenly passed an incorrect reference for the `sender` meaning that currently there's no clean or reliable way to determine if `sender` is the `Console` or a `User` (`instanceof` doesn't work, which leaves checking by name or using reflection).
2020-07-06 19:34:13 +01:00
md678685 c668879070 Add slightly more sanity to Vault code
This subtly changes how backend permissions plugins are reported on
bStats. (Previously, somehow the LP service provider was detected as
originating from Vault...?)
2020-07-06 19:09:20 +01:00
md678685 c4d318b7d0 Deprecate TimedTeleport 2020-07-06 18:49:25 +01:00
pop4959 e7d9dbfbcf Allow preventing bed and respawn anchor explosions in EssentialsProtect 2020-07-05 18:46:23 -07:00
MD 1be3daf0b5 Update bStats Metrics and add wrapper class for new graphs (#3451)
This PR updates the version of the bStats Metrics class to the latest version, supporting plugin IDs in place of just plugin names. It also adds the following graphs:
- Active permissions backend
- Active economy backend
- Whether or not a command has been used as a bar chart (pending bStats backend implementation)
- Version history graph as a multiline graph (also pending bStats impl)

It also removes the weird `getMetrics` and `setMetrics` APIs which should never have been API in the first place.
2020-07-05 19:30:01 +01:00
Josh Roy 8f86849aec Fix 65f8883 breaking offline home listing (#3446) 2020-07-02 18:59:40 -07:00
Josh Roy 0b4ee9e73e Add hidden config to stop throwing errors for passengers (#3445) 2020-07-02 15:30:22 -07:00
Josh Roy 65f88834ba Fix further AME(s) in /home (#3444) 2020-07-02 22:58:40 +01:00
pop4959 024c56efdd Fix recipe command on Paper (#3404) 2020-07-01 15:19:42 -07:00
pop4959 9c487b0aac Match kit name in delkit (#3396)
This allows deleting kits ignoring case; fixes #3370.

I don't know if this is the ideal fix, but everything else for kits seems to nuke the letter casing. Not really sure why in `Kits.java`, the keys needs to get lowercased in a new mock `ConfigurationSection`. It just seems like this would purely make it harder to access the same section again in the real config. Instead, I just added a different method that matches the real config name of the kit (as set in `/createkit`, which currently allows uppercase).
2020-07-01 22:12:43 +01:00
pop4959 d743f928ad Ignore NPCs in EntityCombustByEntityEvent (#3389) 2020-07-01 22:06:49 +01:00
pop4959 07e2fe3af1 Improve suicide and kill commands (#3388)
Fixes #3189 

This PR makes improvements to the suicide and kill commands, namely:
1) Call `EntityDamageEvent` with damage equal to `Float.MAX_VALUE`, which is the amount that is inflicted by `/minecraft:kill`.
2) Removes the calls to `Damageable::damage` which ends up damaging the player with `DamageSource.GENERIC`, and later causing another `EntityDamageEvent` where as a result the last damage cause gets set to `EntityDamageEvent.DamageCause.CUSTOM`. Thus, the `EntityDamageEvent` that Essentials calls gets rendered useless when someone tries to get the damage cause of the player in `PlayerDeathEvent`. Setting health to zero forcibly kills the player without causing damage.
3) Add `getTabCompleteOptions` to the suicide command, as it currently incorrectly suggests players.
2020-07-01 22:04:46 +01:00
pop4959 9f384c71f3 Confirm home replacement when overwriting existing homes (#3338)
Co-authored-by: Josh Roy <10731363+JRoy@users.noreply.github.com>
Co-authored-by: MD <1917406+md678685@users.noreply.github.com>

Warns the player that they are trying to replace a home, if they try to set one with the same name, when `confirm-home-overwrite` is set to `true` in the config.

https://user-images.githubusercontent.com/17698576/83004206-3633eb00-9fc4-11ea-9317-fe245fed9cbb.png

Fixes #2038
Closes #2847
2020-07-01 22:03:22 +01:00
Josh Roy 7a5aea0bcf EditSign Command (#3415)
bro so epic bro
2020-07-01 21:58:11 +01:00
Josh Roy b6c9bc1439 Add command + money queues to process after items in kits (#3434)
Fixes #3431
2020-07-01 21:51:10 +01:00
Josh Roy b7f38517ef Fix some reported bugs regarding teleportation. (#3433)
Fixes #3420
Fixes #3430
2020-06-30 17:00:20 +01:00
Josh Roy 60f54ee37d Fix relocation pattern for EssentialsXSpawn (#3427) 2020-06-28 19:14:06 -07:00
Josh Roy adf1273bf9 Fix RGB support in prefixes/suffixes (#3422) 2020-06-28 16:36:17 +01:00
MD 3c79e9e59d Update items.json from generator (#3394)
This PR replaces the current `items.json` file with one generated *solely* by ItemDbGenerator.

In 1.13.x, the `items.json` shipped with EssentialsX was generated using the [genItemsFlat script and data](https://github.com/md678685/essx-scripts). For 1.14 and 1.15, this was merged with the output of [ItemDbGenerator](https://github.com/EssentialsX/ItemDbGenerator), but this is an awkward and unreliable process involving three separate tools. This has now been consolidated into a single tool, which is now on par with the old process.
2020-06-27 22:38:32 +01:00
1ab1b5713e Update to 1.16.1 (#3408)
Co-authored-by: Josh Roy <10731363+JRoy@users.noreply.github.com>
Co-authored-by: md678685 <1917406+md678685@users.noreply.github.com>
Co-authored-by: pop4959 <pop4959@gmail.com>
2020-06-27 12:17:35 -07:00
Flask-Bot edf2f295d1 Update Crowdin configuration file 2020-06-27 16:41:40 +01:00
pop4959 c043416b11 Fix spawner provider on 1.16 (#3412) 2020-06-24 23:25:14 -07:00
Josh Roy 4a471f0a93 Provider Rework (#3407)
Moved providers around, made them make sense, profit
2020-06-24 22:00:59 +01:00
md678685 04a1d8197f Update PaperLib to 1.0.4 2020-06-24 18:08:39 +01:00
Josh Roy d9bf099c3d Reduce sync loads for teleporting (#3102)
This PR reduces the number of sync loads occurring on any teleport caused by essentials.

Fixes #2861
Fixes #2287
Fixes #3274
Fixes #3201
Fixes #2120

Before this PR, essentials would get a block multiple times causing sync loads to check if it was safe to teleport to. Now, the target block's chunk if fetched async with PaperLib and passed along to `LocationUtil#isBlockUnsafeForUser` (which internally calls other LocationUtil methods what that chunk object) resulting in the chunk only loading once, off the main thread. The only operations remaining on the main thread is `LocationUtil#getSafeDestination`. This is due to the method's recursion which would be a pain to move async. **However:** since the chunk was already loaded async, `LocationUtil#getSafeDestination` most of the time won't cause sync chunk loads. The only time it would cause sync chunk loads is with an unsafe location near a chunk border.

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

* Reduce sync teleporting loads

* Avoid argument re-assigning

* Remove async teleports when unnecessary

* Make exceptions cleaner

* Async all the things

Made an async version of every method with fallbacks for deprecated methods.

* Remove old now fallback method

* Migrate everything to the new async teleport API

* Update ITeleport javadocs

* Fix invoking via async context

* Fix /jail using deprecated method

* Fix jail join handler using deprecated method

* Rename all teleport classes to indicate async

* Remove deprecated methods

* Add (and deprecate) old teleport api

* Revert TimedTeleport.java

* Reduce Diff

* Add legacy sendToJail method

* Reduce Diff Further

* Use getNewExceptionFuture in Commandtpo

* Use getNewExceptionFuture everywhere

* Fix even more usages

* Revert LocationUtil.java

* Fix issue causing unsafe locations to not work properly

* Add deprecated notice in IUser implementation

* Use CompletableFuture#completeExceptionally for exceptions

* Use Essentials' logger in EssentialsCommand#showError

* Return implementation rather than interface

* Avoid possible deadlocks with entity ejections

* Nuke some sync loads with homes

Took 7 hours and 2 PRs to paper but it's here!

* Fix ABI and make the codestyle worse

* Make the codestyle worse because muh diff

* Further ruin the codestyle

* Fix error messages not showing in TimedTeleports

* Improve messages around beds for /home

* Fix #3274

Allow unsafe locations for different worlds + spectator mode

* Fix fly safety operators
2020-06-24 09:52:25 +01:00
Jason d2f2140be9 Fix a messages.properties message (#3391)
It's a small change but I figured more consistency could be nice
2020-06-19 17:15:52 +01:00
pop4959 04f88e460b Add missing tl keys for tempbanip (#3387) 2020-06-16 18:39:22 -07:00
pop4959 d64f73e719 Add support for translating command description and usage (#3284) 2020-06-16 13:39:48 -07:00
Josh Roy 2ab4dcbc11 Add option to remove vanishing items from keepinv users (#3328) 2020-06-15 16:22:00 -07:00
846043e9a0 Add settings to protect items from explosions (#2504)
Co-authored-by: Josh Roy <10731363+JRoy@users.noreply.github.com>
Co-authored-by: pop4959 <pop4959@gmail.com>

Adds protection settings to Protect to block item damage when entities such as wither skulls, fireballs, TNT and creepers explode.

Closes #2284.
2020-06-15 13:54:16 +01:00
MD ea57e4ae01 Add serialize method to ItemResolvers for custom serialization (#3307)
Add an optional `serialize` method to `ItemResolver`s which plugins can implement in order to add custom items to `/createkit`. Also improves ItemResolver docs.

Closes #3305, closes #3216.
2020-06-15 13:46:44 +01:00
Josh Roy 6aa5e5cc4a Add config option to control selling names items with /sell (#3314)
Adds an `allow-selling-named-items` config option, which allows server admins to enable/disable the ability to sell named items with `/sell`.

Closes #1988.
Closes #908.
Closes #2196.
2020-06-15 13:44:46 +01:00
oxygencraft 3e5bd4cf09 Deny teleport requests to players lacking permission to accept (#3361)
This PR will deny any teleport requests to players lacking permission to accept the request (`essentials.tpaccept`).

Closes #1259.
2020-06-15 13:36:13 +01:00
TehBrian 3d096c1f31 Fix inconsistent coloring in messages (#3366)
Fix two inconsistencies that look like this:

https://user-images.githubusercontent.com/32250137/84316124-971d0080-ab38-11ea-8297-73f978e79a57.png

The period's color at the end is out of place. This pull-request fixes that by setting the period's color to `§4` instead of `§6`.
2020-06-15 13:35:13 +01:00
Glare b5b6bce758 Ensure RemoveEffectsOnHeal config setting is actually registered (#3377) 2020-06-13 09:40:42 -07:00
Jasonandtriagonal 46ed8e954f Add config.yml note (#3359)
Co-authored-by: triagonal <10545540+triagonal@users.noreply.github.com>

"The player's bed respawn point is still set by Minecraft even if `update-bed-at-daytime` is set to `false` in config, meaning that the entire feature is indeed ineffective on Minecraft 1.15 and above."
2020-06-10 13:40:05 +01:00
pop4959 cfca2f7550 Mention setworth command in worth.yml (#3364) 2020-06-10 13:37:55 +01:00
MDandJosh Roy a09df9bf3a Add UTF8 support for .properties files (#3358)
Co-authored-by: Josh Roy <10731363+JRoy@users.noreply.github.com>

Based on edaa4f6, this allows messages files to be read in UTF8 without the need for native2ascii conversion. This also removes the native2ascii-maven-plugin, previously used to convert Crowdin translations to a compatible format. I've tested this briefly and it appears to work correctly with both internal translations and custom messages.
2020-06-07 12:06:33 +01:00
Josh Roy dc2462c277 Add option to change disposal title via sign (#3269)
Closes #2628.
2020-06-05 16:16:47 +01:00
md678685 25c7ebcf39 Remove BuildTools script and update README 2020-06-05 15:22:40 +01:00
pop4959 baab65d776 Add support for permission contexts (#3320)
As discussed in #2960. Allows Essentials to register contexts with permission plugins that support them. A working implementation for LuckPerms is included in this PR. PermissionsEx 2 also has support for registering contexts, however it should probably be added at a later date, since as per zml2008 on Discord, the API is not yet stable.

https://user-images.githubusercontent.com/17698576/82718550-f5507500-9c57-11ea-970d-9d5f8bce8037.png
2020-06-03 21:36:27 +01:00
pop4959 9e2b906048 Display date diff correctly (#3292)
There is an age old issue in Essentials which causes date diffs (such as those displayed in teleportation delays, mutes, and temp bans) to display incorrectly to the user when the command is run. After looking into this a bit, it looks like the reason for this is that if there is even a 1 ms time difference between parsing the date diff and displaying it, the time displayed will be truncated by an entire second. This PR fixes this problem by adding 50 ms of buffer time to the date object *only* when it is calculating the date diff string. This is not significant enough to be noticed by users, and allows Essentials code to correctly generate the date diff string as long as it does so within 50 ms of parsing it.

As a theoretical example... lets say a user is muted for 1 year. If 1 ms passed (in code prior to this PR) between parsing and displaying the date diff, then the displayed time will be 11 months, 29 days, 23 hours. This is because 1 year - 1 ms is being truncated down and then Essentials lops off time accuracy beyond the 3 most significant terms. After this PR, the date diff will be parsed normally, but when the display string is being calculated, it will use 1 year + 50 ms (and if 1 ms passed, then that would be 1 year + 49 ms), which gets truncated to 1 year.

As a practical example:
https://user-images.githubusercontent.com/17698576/82106444-d55c0700-96d5-11ea-8290-377442e4f9fe.png

Quite often (I'd say about half of the time) before this PR, the date diff will display like this, when the example command `/mute <player> 1y` is run.

https://user-images.githubusercontent.com/17698576/82106467-063c3c00-96d6-11ea-9da2-3dc1556add14.png

After this PR, the date diff displays correctly every time.

Fixes #3349.
2020-05-30 15:18:16 +01:00
pop4959 9f3c2683ae Clean up providers a bit (#3279) 2020-05-28 12:06:03 -07:00
pop4959 9e01a1a427 Player should not be able to send empty shout/question messages (#3341) 2020-05-28 11:45:05 -07:00
pop4959 db729241c9 Fix issue with eco reset requiring 3 args (#3340) 2020-05-28 11:44:46 -07:00
d5d8c80d74 Protect Armor Stands + Item Frames (#3270)
Co-authored-by: JRoy <joshroy126@gmail.com>
Co-authored-by: AlexTheCoder <alexjmeech@gmail.com>
2020-05-27 12:36:53 -07:00
Josh Roy 4c48ccb422 Block removing hats with curse of binding (#3299) 2020-05-27 12:36:22 -07:00
Josh Roy 53e7c83254 Add tempbanip command (#3291) 2020-05-27 12:35:20 -07:00
Josh Roy fdef1062f0 Add config option to block /pay from ignored users (#3273) 2020-05-27 12:34:11 -07:00
kakd b9f8fc2e11 Option to send coordinate after death (#3207) 2020-05-27 01:58:54 -07:00
Xeyame db410fb3e7 Add missing methods to Commandexp (#3335) 2020-05-26 17:26:58 -07:00
Jason 500dadc760 Update config.yml custom join/quit message comments (#3334) 2020-05-26 16:22:38 -07:00
md678685 7d61953753 Fix spawner provider detection only working on 1.13+
This caused a seemingly-unrelated error where the 1.7/1.8 provider was being used on all versions up until 1.12. Upon further investigation, this line caused a NoSuchFieldError, and since this isn't an Exception it was caught by the outer `catch (Throwable t)` which was intended to catch throwables from the providers rather than the setup of tryProvider.
2020-05-20 19:49:45 +01:00
pop4959 5b9b76d5e7 Fix clearing specific items in clearinventory (#3263)
Fixes #2986
Closes #3050
Closes #3191

Refactors the clearinventory command code in such a way that fixes the problem of not being able to clear all of a specific item on newer server versions. Also re-adds data value support for older server versions that support it, which seemed to have been inadvertently removed in 79bc340.

Checked against 1.8.8, 1.12.2, 1.13.2, 1.15.2.
2020-05-17 21:10:12 +01:00
Josh Roy b9804d8980 Ignore CloudNet v3 SLPE (#3288)
Yet another CloudNet fix.

Fixes #3282
2020-05-17 15:35:31 +01:00
Josh Roy b960ee365a Fix improper target block handing in /tree & /bigtree (#3271) 2020-05-13 15:55:17 -07:00
Josh Roy 302f0acbaa Add permission for storing user's last location on teleportation (#3272) 2020-05-13 15:53:36 -07:00
Glare 8f5b97b9d2 Merge pull request #3277 from pop4959/remove-1.8-spawner-providers-2 2020-05-13 14:29:54 -05:00
pop4959 6371cf7517 Remove 1.8 nms spawner providers from pom 2020-05-13 12:17:37 -07:00
pop4959 e53520aef6 Remove 1.8 NMS spawner providers (#3276)
This PR removes the 1.8 R1 and R2 spawner providers. I was looking into refactoring these to use reflection instead of importing NMS code (in order to avoid requiring buildtools to compile), but after some research it looks like these are actually not even used anymore, in favor of the LegacySpawnerProvider (which Essentials appears to use for 1.8.0-1.12.2). Thus, keeping these is fairly pointless and causes more harm than good. There is no reason to continue including them, nor maintaining them. Essentials currently doesn't even officially support these versions anyway.
2020-05-13 10:56:50 +01:00
triagonal d59fd71ba5 implement PrivateMessagePreSendEvent (#3260)
This PR introduces an event to be called just before a private message is sent to a user. This event provides the message sender, the message recipient, and the contents of the message.

This event provides the possibility for greater customization of private messages, such as playing a sound or displaying a boss bar when a private message is received, or filtering private message content.

Closes #726, closes #2097.
2020-05-13 08:03:28 +01:00
Crash Cringle 4b967a749b Added a command to /eco that allows users to take percentages from pl… (#3080)
* Removed unnecessary formatting

* Fixed spacing around isPercent, removed unnecessary parenthesis, optimized conversion
2020-05-12 21:38:36 -07:00
pop4959 8f88a8dcb3 Allow 1 char name (#3264) 2020-05-12 21:27:33 -07:00
pop4959 a58ba406eb Add offhand slot to invsee equip (#3265) 2020-05-12 21:26:24 -07:00
pop4959 a93ca9b7bc Use world's sea level for depth command (#3268) 2020-05-12 21:05:57 -07:00
Josh Roy 02e6b5f1b3 Fix isStopping MethodHandle invocation on Spigot (#3267)
Fixes #3266.
2020-05-12 20:14:01 +01:00
Josh Roy 63dd5f3f64 Fix age old bug with active status in Backup manager (#3262)
I cannot even reproduce this error but I guess one other person can. Fuck this stupid feature
2020-05-11 18:09:29 -07:00
Alexander Meech a3a50e9cd5 Implement permission node to extinguish other players (#2826)
Implements a specific permission node to restrict access to extinguishing other players, so Extinguish command will match other commands with similar functionality (i.e. /feed)

Fixes #2796
2020-05-11 17:40:24 +01:00
pop4959 8e3c1aaa96 Implement rest command (#3205)
Implements a rest command based on @mart-r's suggestion in #2299. Resetting the time since rest statistic prevents phantoms from coming after you for an hour (real time). The statistic is also set to zero when using a bed. This command cannot be used pre-1.13 because the statistic does not exist (nor would it matter since there are no phantoms).

Closes #2299
2020-05-11 17:11:06 +01:00
Josh Roy 8b71437264 Improve backup functionality (#3258)
Waits for an ongoing backup task to complete in onDisable (and yells at users for `/reload`ing), and adds a `backup.always-run` option to enable always running backups even when no users have logged in since the last backup.

Fixes #3257 and closes #2646.
2020-05-11 16:55:31 +01:00
Josh Roy 61d0ed3f01 Fix invalid charge error when using suffix currency on signs (#3253)
i swear i test my code

Fixes #3252.
2020-05-11 15:20:00 +01:00
Josh Roy fc2b7b63a2 Save player logout times on shutdown (#3157)
Properly save userdata and mark the player's last logout time when the server is shutting down.

Fixes #2764.
2020-05-11 14:53:05 +01:00
kmecpp 96590a3389 Add KitClaimEvent (#3197)
Adds an event fired when a kit is expanded for a user. Fixes #3196.
2020-05-09 21:19:51 +01:00
zml a043de3e44 Add a more helpful error message for xmpp module (#3247)
Rather than spitting out a stacktrace, this gives users some instructions on what to do.

It's a bit spammy so the error messages get noticed, that could be toned down a bit if we just want to be silent on login. Unfortunately a lot of plugins haven't discovered the debug and trace log levels, so a lot of startup warnings (like this one) will get lost in the spam if there aren't other issues.
2020-05-09 13:21:02 +01:00
Josh Roy 81d3900ef6 Cleanup after UUID Ignore List PR (#3227)
Most of these are edge case fixes, but still fixes nonetheless!
2020-05-04 14:32:49 +01:00
Josh Roy fd136384a1 Add null check in ignore command (#3226)
This would only become a problem if a server owner decided to delete a bunch of their userdata. Nonetheless, it doesn't hurt to have the check.

I promise this is the last pull request regarding this 😄
2020-05-04 14:17:08 +01:00
Josh Roy dd5fe117b5 Fix null check in Username->UUID ignore list converter (#3225)
Didn't test with a username that didn't exist and didn't notice this. Null check(s) are now in their proper place.

Fixes #3223.
2020-05-04 13:48:50 +01:00
Josh Roy e9d29f789f Add default enchantment level for enchant sign (#3070)
Defaults the enchantment level on signs to `1` if one is not provided on the sign.

Closes #1497.
2020-05-04 11:10:16 +01:00
Josh Roy 1bc1f646fd Convert ignore list storage to UUID-based (#3209)
As the title describes, this PR converts the ignore list storage from username-based to UUID-based.

Fixes #239.
2020-05-04 11:06:09 +01:00
Josh Roy 8ad55cb634 Add UUID and User based economy methods (#3085)
Adds methods to the Economy API to use UUIDs and User objects. Additionally, deprecates all the username (String) based methods. Backwards compatibility has been maintained and I added User validation to UUID-based methods and null checks in User-based methods
2020-05-04 11:00:25 +01:00
mart-r b19dec120a Don't show hidden players in /balance unless exact name entered (#3218)
Fixes #2305

Not looking for hidden players within the command, yet looking for offline players.
Only matching a hidden player if the name match was exact (i.e not matching nicknames).
2020-05-04 10:36:01 +01:00
pop4959 283c088b21 Add protect option for disabling ender crystal explosions (#3210)
Closes #587.
2020-04-30 20:39:00 +01:00
pop4959 d5ffed09b4 Fix home tab completions (#3206)
Fixes #1337 😎 

This PR fixes tab completions for all of the home commands in Essentials. Prior to this PR, the behavior is approximately as follows:

- `/sethome` has no implementation for completions, and so it provides player names, which isn't very useful, and in my opinion can cause more harm than good by confusing users.
- `/home` and `/delhome` fail to provide valid completions when a user has the `essentials.home.others` permission. The argument syntax is `[player:]<name>` but it tries to complete it as `<player> <name>`. Not only does it not show you suggestions for your own homes, but it proceeds to show you invalid suggestions!

This PR provides completions that accurately reflect the syntax and real behavior of the command, including suggesting homes for player names that are partially matched. It will provide suggestions for all of your own homes, as well as providing suggestions based on how far along you are in the command (players if you haven't specified `:` yet, otherwise a specific player's homes).
2020-04-30 20:26:27 +01:00
Josh Roy b7eec09307 Add config option to make currency symbol as a suffix (#3066)
Adds `currency-symbol-suffix` config option to move the currency symbol as a suffix rather than a prefix.

Closes #2577.
2020-04-25 13:12:55 +01:00
Josh Royandmd678685 23f0f98af3 Cleanup code (#3067)
Co-Authored-By: md678685 <1917406+md678685@users.noreply.github.com>

Basically cleans up a bunch of warnings that are easily suppressed.
2020-04-25 13:08:57 +01:00
Josh Royandmd678685 6bbdbc89a6 Improve MuteStatusChangeEvent (#3068)
Co-Authored-By: md678685 <1917406+md678685@users.noreply.github.com>

Adds getTimestamp and getReason methods to MuteStatusChangeEvent with the apropriate JavaDocs explaining them.

Closes #2459.
2020-04-23 16:28:08 +01:00
zml 12c8623666 Add permissions defaults to plugin.yml for op-affecting commands (#3029)
This aims to reduce the unintended consequences of granting all Essentials permissions or giving a player op, by defaulting permissions some more permissions to false, including `essentials.hat.prevent-type.<type>`. There's also a new essentials.exempt metapermission to have one parent that controls exemption from kick/ban/mute/etc. This will change behaviour for ops to some extent.
2020-04-23 16:15:10 +01:00
mink 2bd6ebd2b1 Config option to toggle disabling flight / speed on world change (#2546)
Closes #2141.

This PR adds the option to toggle whether or not EssentialsX should handle disabling player flight / speed when they switch to a new world, in case server administrators are handling that via a third party plugin.
2020-04-23 16:13:19 +01:00
pop4959 40fb496052 OfflinePlayer getAttackCooldown (#3190)
Fix compile
2020-04-23 12:15:32 +01:00
triagonal b72d822f94 Re-add missing GeoIP license message key (#3186)
This PR re-adds the geoIpLicenseMissing key which was inadvertently removed during the recent mass locale update (#3165).
2020-04-21 19:44:54 +01:00
FourDown 6d92ac9af6 Fix book formatting (#3173) 2020-04-16 17:01:51 -07:00
Josh Roy 47f27a8016 Fix method signature breakage in versions lower than 1.14 (#3175) 2020-04-16 16:55:06 -07:00
Noahandmd678685 849d095e9a Add /ecreative alias to /gamemode (#3101)
* Proper command alias

* Update Essentials/src/plugin.yml

Co-authored-by: md678685 <1917406+md678685@users.noreply.github.com>
2020-04-14 17:30:25 +01:00
Trent Hensler 923f240aa1 New Crowdin translations (#3165)
* New translations messages.properties (Russian)

* New translations messages.properties (Portuguese)

* New translations messages.properties (Hebrew)

* New translations messages.properties (Japanese)

* New translations messages.properties (Latvian)

* New translations messages.properties (Lithuanian)

* New translations messages.properties (Norwegian)

* New translations messages.properties (Polish)

* New translations messages.properties (Portuguese, Brazilian)

* New translations messages.properties (German)

* New translations messages.properties (Romanian)

* New translations messages.properties (Serbian (Latin))

* New translations messages.properties (Slovak)

* New translations messages.properties (Spanish)

* New translations messages.properties (Swedish)

* New translations messages.properties (Thai)

* New translations messages.properties (Greek)

* New translations messages.properties (French)

* New translations messages.properties (Italian)

* New translations messages.properties (Chinese Simplified)

* New translations messages.properties (Turkish)

* New translations messages.properties (Hungarian)

* New translations messages.properties (Vietnamese)

* New translations messages.properties (Korean)

* New translations messages.properties (Basque)

* New translations messages.properties (Bulgarian)

* New translations messages.properties (Chinese Traditional)

* New translations messages.properties (Finnish)

* New translations messages.properties (Chinese Traditional, Hong Kong)

* New translations messages.properties (Croatian)

* New translations messages.properties (Czech)

* New translations messages.properties (Danish)

* New translations messages.properties (Dutch)

* New translations messages.properties (English, United Kingdom)

* New translations messages.properties (English, United States)

* New translations messages.properties (Estonian)

* New translations messages.properties (Ukrainian)
2020-04-14 17:15:19 +01:00
triagonal 8655ff2de3 Add displayname placeholders to self-AFK messages (#3164)
As a result of #2780 (oops) the self-AFK messages can no longer exactly match the regular AFK messages as the placeholder for the player's displayname was left out for the self messages.

This PR adds those placeholders so that those who would prefer that these messages are the same can simply copy their messages from the normal `userIs*Away*` keys to the new `userIs*AwaySelf*` keys.
2020-04-14 11:56:17 +01:00
triagonal 6f61010cf9 Allow toggling public broadcast of AFK messages (#2780)
(description from #2608)

So... I've implemented a system for toggling whether or not AFK messages are broadcasted to the entire server and also changed a few things along the way:

1. I added a config toggle broadcast-afk-message that will change whether AFK messages are broadcast globally or not.
2. In both cases the AFK target now recieves a "self-oriented" message instead of the global default. Basically just says "You are now/no longer AFK". This would be a change from the default behaviour.
3. I created a way to exclude certain IUsers from broadcastMessage messages using an IUser... varargs parameter. I wasn't too sure how to implement the exclusion, but this seemed like a fairly good option.

I'm not too sure if what I've come up with is an optimal solution, but it's been tested and confirmed to work as intended.

closes #2116, closes #959

---

* implement toggle for broadcasting afk message

* add "self-private" AFK messages, implement exclusion system for broadcastMessage

* remove rogue import, clarify config comment

* move excluded collection creation out of loop, use set instead

* use set instead of varargs

* ok but actually use the set this time

* address requested changes

* update missed message section

* move from Collection to Predicate for broadcast exclusion

* update Predicate variable name

* use identity comparison (cleanup)

* clean up unnecessary imports, remove extra spacing
2020-04-13 14:33:37 +01:00
md678685 5082badca4 Improve config.yml comments and structure (#3151)
This PR fixes some issues with the config.yml:
* Adds links to the EssentialsX docs where appropriate
* Moves a couple of settings into their correct locations
* Changes headers to remove the weird implications of modularity (EssentialsHelp isn't a module, it's *one* command)
* Updates support link at top
* Minor grammar nitpicks
2020-04-13 09:06:31 +01:00
Josh Roy 307bd2a35f Prevent tridents from being picked up (#3149) 2020-04-10 12:44:45 -07:00
md678685 a11552f497 Document and clean up API events 2020-04-10 12:00:01 +01:00
Jason 8556caaeb4 Update kits.yml example to be more consistent (#3148)
Follows the note using {USERNAME} instead of {player} to prevent confusion
2020-04-09 17:11:14 +01:00
md678685 7c09012b3d Update /fireball usage and description 2020-04-09 16:40:49 +01:00
Jason eb596caa00 Change {PLAYER} to {USERNAME} in kits.yml comment (#3057)
Avoids confusion between `{PLAYER}` (KeywordReplacer placeholder) and `{player}` (kit-specific placeholder).
2020-04-09 16:00:35 +01:00
HexedHero ab4501aa4c Add check for NPCs to /back listeners (#2833)
Add a check for NPCs to the PlayerTeleportEvent and PlayerDeathEvent to avoid unnecessarily tracking NPCs' `/back` locations.

Closes #2832.
2020-04-09 15:37:51 +01:00
md678685 4b766d373d Fix kit command example
Shhhhh, #2980 isn't real, it can't hurt you
2020-04-09 15:10:43 +01:00
ThatGamerBlue e3574edc5d scripts: fix buildtools script under windows git bash (#3145)
wget is nonfunctional in git bash for windows, so we should use curl instead
(no matter what you pass to wget it fails with the same error)

https://i.imgur.com/YDw68vM.png
2020-04-09 15:05:21 +01:00
Dieter Nuytemans dcb69ddc73 Set sleepingingored default to false (#3141) 2020-04-06 22:18:33 -07:00
pop4959 1d6ad297a4 Add new interface methods to FakeServer (#3140) 2020-04-05 23:13:13 -07:00
Josh Roy 85a5e517c9 Fix passenger check not working on versions below 1.11.2 (#3132) 2020-04-05 02:48:21 +11:00
Radoje17 b08d380643 Added real name boolean option for the /list command (#3117) 2020-04-02 00:06:32 -07:00
Glare ad98fc4121 Implemented uptime placeholder (#3120) 2020-04-01 11:37:55 -07:00
Josh Roy 810689c037 Add passenger dismounting for teleports (#3069)
Add passenger dismounting for teleports
2020-03-31 18:04:44 -07:00
Joe Hirschfeld c007700c59 Merge pull request #3106 from Markyroson/2.x
Make MockBukkit compatible #3105
2020-03-31 00:06:39 -07:00
Joe Hirschfeld 8cc3f6626b Merge pull request #3113 from darbyjack/200-IQ-Protect-Improvements
Fixed my PR pt2
2020-03-30 23:42:54 -07:00
darbyjack a3b8a4adc9 Version to 1.14 2020-03-31 01:40:37 -05:00
Joe Hirschfeld 8f817c089b Merge pull request #3111 from darbyjack/200-IQ-Protect-Improvements
200 IQ Essentials Protect Improvements
2020-03-30 23:32:58 -07:00
Joe Hirschfeld ed4e7794c3 Merge pull request #3063 from schlatt-co/feature/3034
Implement better AfkStatusChangeEvent
2020-03-30 23:15:34 -07:00
darbyjack 6f732d410e Fixed my stupid PR 2020-03-31 01:13:14 -05:00
Joe Hirschfeld 6c8da20883 Merge pull request #3052 from pop4959/fix-zh-CN-geoip-issue
Fix zh-CN GeoIP locale issue
2020-03-30 23:01:50 -07:00
Joe Hirschfeld c7d9ce7f7f Merge pull request #3051 from pop4959/xp-tab-complete-fix
Fix tab completion for Exp command
2020-03-30 22:58:21 -07:00
Joe Hirschfeld 4e7f639076 Merge pull request #3049 from pop4959/near-exempt
Near exclude permission
2020-03-30 22:47:36 -07:00
Joe Hirschfeld b2c3b3a99f Merge pull request #2914 from montlikadani/patch-5
Fix NPE when the user is null in the hidden players
2020-03-30 21:27:39 -07:00
Joe Hirschfeld 77338d66dc Make drop-items-if-full work on Essentials kits (#2820) 2020-03-30 21:11:56 -07:00
Xeyame e2130df596 Add different translation keys for the "me" message (#2805)
* Add different translation keys for the "me" message

* Add proper German "me" translation
2020-03-30 21:10:46 -07:00
montlikadani 2bbe6d6069 Implement message for #2640 (#2721)
* Update Essentials.java

* Update messages.properties

* Update messages.properties
2020-03-30 21:01:15 -07:00
montlikadani c8b8e505f3 Add teleport warmup event to API (#2590)
* Update Teleport.java

* Create UserTeleportEvent.java

* Update Teleport.java

* Add location to event
2020-03-30 20:38:13 -07:00
latiku 89743f9900 implement command teleporting to a player's last known logout location (#2505)
* implement /offlinetp command, teleports to a player's last known logout location

* send a message to /tp user when they try teleporting to an offline player

* getHidden is now false, you are no longer able to teleport to offline players using offline tp

* change /offlinetp to /tpoffline to match essentialsx conventions
2020-03-30 20:35:23 -07:00
latiku dbc0562fb0 permission-based jailed player interactions (#2503) 2020-03-30 20:32:12 -07:00
pop4959 76f4dff14c Fix bed message on some older versions of MC (#3048)
Fixes #3045. Some older versions of MC use "BED_BLOCK" to represent beds.
2020-03-30 08:32:44 +01:00
pop4959 baa2a2f24f Use isAuthorized for permission check 2020-03-29 13:44:33 -07:00
Pokechu22 2ca02911b3 Mention 1.15.2 in the README (#3107) 2020-03-29 12:11:44 -07:00
Markyroson cf48237049 Make MockBukkit compatible #3105 2020-03-29 10:34:16 -07:00
pop4959 adfe2c1975 Update FakeWorld (#3095) 2020-03-26 19:12:07 +11:00
triagonal a782043798 Revert "Add {PLAYER} placeholder with uppercase in kits (#2929)" (#3072)
This reverts commit 90c4a2f53c.
2020-03-14 22:49:48 -07:00
montlikadani 90c4a2f53c Add {PLAYER} placeholder with uppercase in kits (#2929) 2020-03-14 15:17:58 -07:00
pop4959 338b371e4c Implement max mute time feature (#2807) 2020-03-14 15:12:43 -07:00
Glare 347179373d Fixed double local logging (#2755) 2020-03-13 02:33:18 -07:00
montlikadani 3bb45b80b1 Add tab-completer for /spawnmob command (#2661) 2020-03-13 02:30:50 -07:00
Glare e3ec0f3b9b Added in option to remove effects on heal (#2754) 2020-03-13 02:24:29 -07:00
Joel Otero f20572b30c Add speed info to whois (#2952) 2020-03-13 01:10:44 -07:00
Josh Roy 2124cce603 Fix User::payUser(User, BigDecimal, Cause) not properly utilizing Cause (#3064) 2020-03-13 00:39:21 -07:00
JRoy ebf60c1e70 Implement better AfkStatusChangeEvent 2020-03-12 22:08:11 -04:00
pop4959 c31b6c3683 Update FakeWorld + FakeServer (#3061) 2020-03-11 17:20:46 +11:00
pop4959 ffc83343fe Fix zh-CN GeoIP locale issue 2020-03-05 01:08:55 -08:00
pop4959 2554acd304 Fix tab completion for Exp command 2020-03-05 00:31:40 -08:00
pop4959 98239114ad Near exclude permission 2020-03-04 23:23:23 -08:00
md678685 c10b39c1c7 Fix bee spawn egg aliases 2020-03-01 11:16:42 +00:00
montlikadaniandmd678685 20e11465e4 Properly fix error with fireball command (#3040)
Closes #3016.

* Update Commandfireball.java

* Update Commandfireball.java

Co-authored-by: md678685 <1917406+md678685@users.noreply.github.com>
2020-03-01 11:12:55 +00:00
pop4959 46e1b95b33 Add missing OfflinePlayer methods (#3033) 2020-02-23 18:11:57 -08:00
md678685 279d6f16e1 Bump version to 2.17.2
\o/
2020-02-22 10:05:14 +00:00
md678685 a747eccaa3 Fix /fireball on 1.8.8 (#3027)
Dragon fireballs were added in 1.9 and so this previously caused an
error. This PR fixes that (and adds tridents as throwables). Fixes #3016.
2020-02-22 10:03:43 +00:00
md678685 0bafbc3184 Reduce permission check calls in PlayerCommandSendEvent (#3026)
This reduces permissions checks by only checking each command once, not checking each command for each alias.

The impact of this is a near-tenfold reduction in permission checks during this listener, which should slightly improve performance when using LuckPerms (and provide significant improvements on older inefficient permissions plugins).
2020-02-22 10:02:53 +00:00
Edward Wang 8069370b8c Clarify easter egg config description (#3028) 2020-02-21 13:12:09 -08:00
Jason 46f4b92ff7 Update config.yml group-formats (#3025)
Since most (if not all) modern permission plugins only use lowercase group names, the examples should also be lowercase. A note has also been added explaining that group names are case-sensitive.
2020-02-21 12:24:49 +00:00
md678685 d92f5ce71c Add 1.14/1.15 item aliases and fallbacks
Short term replacement for #2897 until ItemDbGenerator is complete:

* Closes #2934 by adding 1.15 items
* Closes #2790 by adding minecraft:sign fallbacks and a "sign" alias
* Closes #2732 by adding aliases and fallbacks for cactus green/green dye, dandelion yellow/yellow dye and rose red/red dye.
2020-02-21 11:11:35 +00:00
Josh Roy 2314bf8bd4 Fix CustomItemResolver causing a StackOverflowError (#3022)
CustomItemResolver was fetching the custom item from the item database instead of the resolved custom item which caused a StackOverflowError.

Fixes #3018.
2020-02-18 20:20:53 +00:00
Jasonandmd678685 7808b21496 Explain how to add commands to kits (#2980)
* Explain how to add commands to kits

* Update Essentials/src/kits.yml

Co-Authored-By: md678685 <1917406+md678685@users.noreply.github.com>

Co-authored-by: md678685 <1917406+md678685@users.noreply.github.com>
2020-02-16 15:39:28 +00:00
triagonal 18ef412211 Add beezooka command (#3003)
This PR introduces the `/beezooka` command as suggested in #2975. The command acts similarly to `/kittycannon` with the exception of the Bee being tamed, instead flying around for a small amount of time before exploding.

Sample usage:
![beezooka](https://user-images.githubusercontent.com/10545540/74099459-11804880-4b78-11ea-9c3d-499b06d912fb.gif)

As Bees do not exist below version 1.15, an error will display when attempting to run the command on such a version:
![image](https://user-images.githubusercontent.com/10545540/74099477-4d1b1280-4b78-11ea-91c2-fa675994a85f.png)

Closes #2975.
2020-02-10 11:46:41 +00:00
md678685 0678328253 Update funding to include Ko-fi link 2020-02-10 11:34:59 +00:00
md678685 5503e1e14c Revert "Split plugin compatibility report into own class"
Revert 6fa5b80c0a, which broke `/ess version`, until this can be fixed.
2020-02-10 09:05:32 +00:00
triagonal 9e89cfa4ed Implement missing FakeWorld methods (#3002) 2020-02-08 21:10:49 -08:00
imDaniX 13f454a022 Properly escape pipe character on item lore (#2994)
Using negative lookbehind instead of negated characters set.

Fixes #2962, fixes #2984
2020-02-07 10:10:54 +00:00
pop4959 129650dade Update FakeServer (#2997) 2020-02-07 12:08:29 +11:00
md678685 6fa5b80c0a Split plugin compatibility report into own class 2020-02-01 21:46:53 +00:00
pop4959 04dfcd0965 Bump supported version to 1.15.2 2020-01-22 09:14:41 +00:00
pop4959 2e818ac709 Properly register entity transform event depending on version (#2942)
Fixes the problem mentioned in #2931 which was introduced in #2836. This is caused as a result of EntityTransformEvent being a relatively new event introduced in Spigot [856adc3e6af](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/856adc3e6afc3e9c0495ac27e38b96b144e54b1e), which was after the update to 1.13.2 in Spigot [f311182396b](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/f311182396bd74b106efebc926ea4d0b92cfba80).

Closes #2931.
2020-01-14 07:54:51 +00:00
pop4959 32ef61197f Fix bed spawn message on 1.15+ (#2943)
Closes #2893

**Tests**
![2020-01-13_14 08 12](https://user-images.githubusercontent.com/17698576/72297425-be66b480-3610-11ea-8421-1ac6881259b8.png)
![2020-01-13_14 10 02](https://user-images.githubusercontent.com/17698576/72297431-c32b6880-3610-11ea-89fc-bdda2d0cec89.png)
2020-01-14 07:50:48 +00:00
md678685 fa06cd8253 Fix Java 9 breakage causing issues on Java 8 2020-01-11 17:03:33 +00:00
pop4959 5020983af5 Update GeoIP (#2926)
This implements the fix suggested by @Bobcat00 in #2919

Users of GeoIP will now be required to register a MaxMind account and create a license to download the database required by the plugin. This license is entered into the new license-key field in the configuration.

---

* Update GeoIP

* Simplify branch

* Update old config detection

* Update geoIpLicenseMissing to point to the EssX wiki
2020-01-11 07:10:40 +00:00
pop4959 f4496b6977 Update FakeWorld again (#2925)
Spigot added some new methods.
2020-01-04 12:32:40 +00:00
montlikadani a1719d651e Update Commandlightning.java 2019-12-31 17:51:21 +01:00
montlikadani e7be2b68a3 Update PlayerList.java 2019-12-31 17:49:46 +01:00
pop4959 552dcb56a1 Improvements for delkit (#2908)
3 improvements for delkit within this PR:

1) Cleaned up unused imports
2) Show actual kit name when deleting instead of memory address (this is the reason originally for making this)
3) Implement tab completion

I've tested to make sure the changes are properly functioning. See below:

Before:
![2019-12-29_01 12 09](https://user-images.githubusercontent.com/17698576/71555204-4bd5c200-29de-11ea-9fe3-eb88db08ef48.png)

After:
![2019-12-29_01 48 50](https://user-images.githubusercontent.com/17698576/71555207-56905700-29de-11ea-9277-271bb0656d64.png)
![2019-12-29_01 48 25](https://user-images.githubusercontent.com/17698576/71555208-58f2b100-29de-11ea-8257-742fa7bb3150.png)
2019-12-31 16:10:38 +00:00
montlikadani e158a65603 Improve scheduler methods to use Java 1.8 lambdas (#2700)
* Update EssentialsPlayerListener.java

* Update Backup.java
2019-12-31 13:58:09 +00:00
CmdrKittens b694e8aaa2 Don't attempt to modify a Map value view (#2910)
md dun goofed
2019-12-29 19:41:17 +00:00
md678685 a2e09121ba Slightly nicer AntiBuild messages 2019-12-26 16:17:10 +00:00
md678685 4ce7dfa8f0 Minor refactor of permissions handlers
* Move `essentials.build` perm check from AntiBuild into default SuperPerms handler
* Don't emulate wildcards for LuckPerms or PEX
* Add `build: true` meta support for LuckPerms (+ other plugins as needed)
2019-12-26 15:08:07 +00:00
md678685 1c4ce7b4bd Don't assume primary group is always present
Fixes a potential issue with PEX 2.0 (and 1.x) where users may not have a primary group.
Closes #2901.
2019-12-26 13:08:38 +00:00
md678685 8a04c1e232 Fix custom_items.yml generation 2019-12-24 23:02:07 +00:00
md678685 6e5d378324 Add methods to set/remove custom aliases 2019-12-24 09:36:15 +00:00
md678685 8e1f3617fd Add custom_items.yml file 2019-12-24 09:36:15 +00:00
Mark Vadeikaandmd678685 2549ed830f Enable control of entity transformations in EssentialsProtect (#2836)
This allows users to prevent any of the following transformations:

- Creeper charging
- Villager infected by zombie villagers
- Villager being cured
- Villagers turning into witches
- Pigs turning into zombie pigmen
- Zombies turning into Drowned (and husks turning into Zombies)
- Mooshrooms switching colors

Configurations are in a new subsection, `protect.prevent.transformation`. All options are disabled by default.

---

* Allow for control of transformations

* Undid removal of villager checking

* Undid removal of villager checking

* Documentation for transformation configs

Co-Authored-By: md678685 <1917406+md678685@users.noreply.github.com>

* Removed duplicate configuration lines

* Updated info about husks drowning

* Changed config names

Co-authored-by: md678685 <1917406+md678685@users.noreply.github.com>
2019-12-23 13:55:05 +00:00
Josh Roy 0ebd64d314 Add a cause enum to UserBalanceUpdateEvent (#2824)
Basically, I just needed this for one of my plugins; otherwise, this could be useful for people using this event who want to see where the user's balance is being updated from.

---

* Add UserBalanceUpdateEvent.Cause
* Add special cause enum
* Add API Cause
2019-12-23 13:16:34 +00:00
Mark Vadeika 843ecb4a42 Escape pipe character on item lore (#2831)
I just adjusted the regex used to split the item lore into multiple lines in order to allow escaping of the pipe character using \|.

Fixes #2830.
2019-12-23 13:15:26 +00:00
md678685 a1a0d34940 Attempt to parse input as UUID in loop commands (#2606)
Related: #2424
2019-12-23 13:06:15 +00:00
md678685 15bb978dab Remove unused VersionUtil constants 2019-12-22 23:55:25 +00:00
md678685 6a7cf39548 Fix wrong filename in ManagedFile error message 2019-12-22 23:53:36 +00:00
pop4959 8ccb70d07d Add phantoms to protect.prevent.spawn (#2806)
Closes #2733.
2019-12-22 22:13:26 +00:00
dashaw92 45461a93b0 Correct unbanip's permission for broadcasts 2019-12-22 22:11:44 +00:00
Joe Hirschfeld b3a54a78bc Save materials in unlimited by name
There was a mistake where materials in unlimited would instead be saved
as a bukkit Material instead of its name. Instead, save it by the name.
2019-12-22 22:10:30 +00:00
AgentTroll a4182b5ff9 Correct check for command cooldowns list in userdata 2019-12-20 12:44:10 +00:00
pop4959 215dcde4b9 Update to 1.15.1 2019-12-19 12:38:18 +00:00
md678685 67b2a9a4f4 Build with GitHub Actions (#2800)
* Add GitHub Actions workflow

* Update workflow

* Run BuildTools in workflow

* Update build.yml

* Add distributionManagement to pom.xml

* Add GitHub registry Maven credentials

* Remove Travis CI config

* mkdir -p

* Remove GitHub package registry push

Didn't work anyway

* Remove distributionManagement

* Cache Maven repo

* Fix step order

* Use JitPack for VaultAPI
2019-12-16 14:23:00 +00:00
Johnny Cao 3b51b23ac2 Block gamemode changes for jailed players (#2875)
Blocks players from experiencing any gamemode changes while they are jailed.

Fixes #1996.
2019-12-12 07:37:13 +00:00
Johnny Cao e0f19f8121 Allow players to set single word AFK message - fixes #2712 (#2876)
Allows players with "essentials.afk.others" to toggle afk themselves with a single word message
2019-12-11 19:20:56 +00:00
Madis Otenurm e720fb528a Crowdin in readme (#2877)
* Crowdin for readme

* Update README.md
2019-12-11 19:04:12 +00:00
md678685 518a5454c6 Add missing FakeWorld methods 2019-12-11 08:48:45 +00:00
Josh Roy 2d9c846084 Update to 1.15 (#2873)
* Compile against 1.15

* Remove achievement related methods for OfflinePlayer

* Add 1.15 to VersionUtil

* Revert "Remove achievement related methods for OfflinePlayer"

This reverts commit d0ab84e0

* Add 1.15 Mobs

* Remove Achievement related methods from OfflinePlayer

This needs more work as this currently breaks > 1.15 support

* Actually this isn't a problem
2019-12-11 07:47:56 +00:00
md678685 59e30f05fc Merge pull request #2871 from AgentTroll/patch-mockito
Update Mockito to allow tests to pass in newer versions of Java
2019-12-10 07:48:07 +00:00
AgentTroll 0f1085a02d Update Mockito to allow tests to pass in newer versions of Java 2019-12-09 20:55:55 -05:00
Glare 882699919e Reimplement spawn-if-no-home config option (#2757)
This reimplements the `spawn-if-no-home` config option from the original Essentials plugin. If set to true, running `/home` without having set a home will send the player to spawn (previous behaviour). If set to false, running `/home` will instead show an error message and not teleport the player anywhere.

Closes #1452.
2019-10-20 09:12:53 +01:00
Ryan f6a70a542e Implements missing createExplosion methods in FakeWorld (#2818) 2019-10-13 14:35:38 -07:00
rye761 785b1fe937 Make drop-items-if-full work on Essentials kits 2019-10-13 17:00:11 -04:00
triagonal bae909ba10 implement missing OfflinePlayer methods 2019-09-24 15:51:43 +01:00
triagonal dbb9757a9f add {USERNAME} placeholder to chat format 2019-09-23 06:20:28 +01:00
md678685 deaeb46ce9 Implement missing FakeWorld methods 2019-08-28 21:14:06 +01:00
md678685 219012bc35 Set item meta in setSkullOwner before returning
*Should* address #2765.
2019-08-28 15:26:23 +01:00
md678685 5f9eb22d23 Fix player head meta on versions below 1.13 2019-08-24 10:05:26 +01:00
md678685 2c33fb6834 Correctly return null for invalid IDs when doing legacy conversion 2019-08-13 15:12:04 +01:00
md678685 8bcef6022b Add max-projectile-speed option
Projectils can load chunks pretty intensively if too fast.
2019-08-05 19:56:25 +01:00
md678685 93d36779f0 Implement regex-based nickname blacklist
Adds `nick-blacklist` list to config which takes phrases or regexes. Users with essentials.nick.blacklist.bypass can bypass the blacklist.
2019-08-05 19:01:48 +01:00
Glare 2502f5e6f2 Check if user has a permission to block putting X item on their head. (#2574)
Closes #2550. 

* Check if user has a permission to block putting X item on their head.
* Forced the material name to be lower case.
* Fixed a typo in the message.
* Updated permission node and added check to the EssentialsPlayerListener.
2019-08-05 16:19:03 +01:00
triagonal 95f2852cf3 Implement toggle for command block logging (#2599)
Just a simple config toggle for whether or not command block commands should be logged.

closes #1153, closes #162

---

* Add toggle for command block logs
* update setting name
2019-08-05 16:17:22 +01:00
md678685 ff9f712d65 Add per-projectile permissions and speed argument to /fireball 2019-08-05 16:12:32 +01:00
Mickey42302 60c4e75a1c Add Dragon Fireballs to "/fireball". 2019-08-05 16:12:32 +01:00
md678685 ccf7c48bf1 Add aliases to /delkit 2019-08-05 15:35:32 +01:00
md678685 65d81eb31e Clean up /essentials 2019-08-05 15:25:55 +01:00
md678685 b97eb12dfc Implement /delkit command
Closes #2709, closes #2719.
2019-08-05 14:06:37 +01:00
md678685 d2724d77df URGENT: critical bug fix 2019-08-02 16:05:41 +01:00
md678685 119b21ac67 Check plugin equals rather than name equals in autocomplete listener 2019-08-01 14:57:48 +01:00
md678685 1ff73b3837 Bump version to 2.17.1 2019-07-30 18:10:27 +01:00
Glare d98f8b3467 Fixed dupe on new builds. (#2696)
Fixes #2695.
2019-07-30 12:56:46 +01:00
md678685 ac8b8861cb Merge remote-tracking branch 'origin/2.x' into 2.x 2019-07-28 16:18:00 +01:00
md678685 22dc5dcebd Fix /r not showing in 1.13+ tab complete
Fixes #2659.
2019-07-28 15:00:49 +01:00
Josh Roy 3c09e72ce4 Bump supported 1.14.x version to 1.14.4 (#2681) 2019-07-20 00:48:13 -07:00
pop4959 fffc3fcac7 Implement missing methods in FakeWorld (#2679) 2019-07-18 11:56:00 -07:00
md678685 bcdbbe9546 Fix wall sign protection on 1.12.2 and below
Fixes #2635.
2019-06-27 15:50:04 +01:00
md678685 19f03cd70e Add missing /tpauto messages
Add messages from #2310 to the `messages.properties` file. Fixes #2634.
2019-06-27 12:00:47 +01:00
md678685 9b7858b830 Update README.md 2019-06-26 22:13:10 +01:00
md678685 8bc55387dd Bump version to 2.17.0 2019-06-26 16:50:11 +01:00
md678685 0584353bfa Bump version to 2.17-pre1 2019-06-26 15:32:08 +01:00
md678685 2938330222 Load and save kit use timestamps consistently
Fixes #2301.

The kit's name was previously sanitised/lowercased when accessed but not when saved. This fixes that. ensuring the kit delay will be reported correctly.

Tested on 1.14.3 - does not appear to break existing kit delays.
2019-06-26 12:54:19 +01:00
md678685 ef7393036e Update to 1.14.3 2019-06-26 11:49:10 +01:00
Josh Roy 0409f5bc4a Update 1.14.3 version string (#2624)
Closes #2624.
2019-06-26 11:48:50 +01:00
Josh Roy 8ff1ebd7c2 Fix version regex on 1.14.3 (#2622) @JRoy 2019-06-25 07:18:16 +01:00
md678685 9089fe8be3 Attempt to fall back to Material.getMaterial(int) below 1.13
Fixes #2615.
2019-06-24 09:41:33 +01:00
Johnny Cao 74d96ce624 Fixes #2121 - Allow players to teleport into a location with water if configured (#2520)
# Description of #2520
This is a continuation of #2457, accidentally hit rebase and recommitted a load of commits from the 2.x log into my repo...

I've reverted the code and added the configuration option, modifying the `LocationUtil#HOLLOW_MATERIALS` as necessary when the config is loaded.

New demo: streamable.com/pm50r
```
[16:01:00 INFO]: Server version: 1.13.2-R0.1-SNAPSHOT git-Spigot-3cb9dcb-77ca7ca (MC: 1.13.2)
[16:01:00 INFO]: EssentialsX version: 2.16.1.154
[16:01:00 INFO]: Vault is not installed. Chat and permissions may not work.
```

# Description of #2457
Fixes #2121.

Prior to the addition of this patch, teleporting from another world through commands such as `/spawn` and `/home` would cause players to be teleported to the surface of the water. After this patch, using the same command will correctly teleport them to the original location.

In seeing that the addition of water would cause the `HOLLOW_MATERIALS` set to be identical to the `TRANSPARENT_MATERIALS`, I have removed the latter's usage and simply added water to the former.

I'm not exactly sure if adding water to `HOLLOW_MATERIALS` is the right decision, but it fixes the issue, and I personally don't really see any point in not having water in the list. I imagine some people might use this as a way to drop players on the surface of the water, but they can fix that issue quite easily by actually going to the surface and setting the location there. I also can see that water is not necessarily a "safe" location because players can drown, but I really see no other alternative. 

The only reason it works like normal in the same world is because the safe location method exempts locations in the same world as the teleporting player, and thus this check is never even performed in the first place for those players anyway.

**Demo**
```
[16:22:49 INFO]: CONSOLE issued server command: /ess version
[16:22:49 INFO]: Server version: 1.13.2-R0.1-SNAPSHOT git-Paper-"16db0e6a" (MC: 1.13.2)
[16:22:49 INFO]: EssentialsX version: 2.16.1.9
[16:22:49 INFO]: LuckPerms version: 4.3.73
[16:22:49 INFO]: Vault is not installed. Chat and permissions may not work.
```
https://streamable.com/71072
2019-06-17 11:28:12 +01:00
md678685 8b7bcbb880 Don't update user activity on physical interactions
Fixes #2578.
2019-06-17 11:06:45 +01:00
md678685 dbd86155fb Only accept square recipes in /condense
Fixes #1194.
2019-06-16 13:28:02 +01:00
md678685 9b77c0802b Switch Travis to openjdk8 2019-06-16 11:25:25 +01:00
md678685 cd7fa79560 Don't warn about CloudNet SLPEs
Fixes #2592.
2019-06-16 11:13:32 +01:00
md678685 10e9879a64 Update to 1.14.x (#2510)
Add support for Spigot/Paper 1.14.2.
2019-06-16 10:15:12 +01:00
md678685 d1dcc47a27 Specify Java 8 for Travis build
Required due to BuildTools not supporting Java 9 or above for MC 1.8.x.
2019-06-16 10:12:35 +01:00
Pokechu22 7a73301a37 Add permissions for individual colors (#1441)
* Add tests for existing format behavior

* Replace formatting implementation

* Add permissions for individual color codes

Resolves #415

* Use format code names

* Fix escaping

* Mockito: test scope only

* Explicitly check the .magic permission

Once I switch to checking if a perm's set in the loop, the explicit check is needed for an * perm.

* Add support for removing individual colors

* Use `obfuscated` as the name for §k

`magic` is still accepted as the group name, so this is not a breaking change.
2019-06-09 15:56:58 +01:00
md678685 e1dec7d9e7 Fix items.json merging 2019-06-09 15:34:24 +01:00
md678685 99fefdb47d Re-add header to items.json 2019-06-09 15:18:16 +01:00
md678685 5ebce8965e Merge 1.13 and 1.14 items.json together
In 2.17.0, [essx-scripts genItemsFlat](https://github.com/md678685/essx-scripts/blob/master/src/genItemsFlat.js) is being replaced with [ItemDbGenerator](https://github.com/md678685/ItemDbGenerator). To ease migration, this is a file generated by merging the 1.14 entries from the new generator into the existing 1.13 file. This will be replaced by an items.json generated entirely by ItemDbGenerator eventually.
2019-06-09 15:10:12 +01:00
md678685 5a0b7285d4 Add FUNDING.yml Patreon link 2019-06-09 13:04:51 +01:00
md678685 829110e89a Implement missing OfflinePlayer methods 2019-06-09 12:59:32 +01:00
md678685 dc1a0b65fa Merge branch 'mc/1.14' of https://github.com/EssentialsX/Essentials into mc/1.14 2019-06-09 12:58:06 +01:00
md678685 b140826e60 Remove unused import in MaterialUtil 2019-06-09 12:21:40 +01:00
md678685 0d9387458d Remove unused import in AFK event 2019-06-09 12:21:25 +01:00
md678685 f2447a9134 Add fallbacks property to ItemData
Allows items.json to specify fallback names for materials on older versions.

Additionally make non-API methods inaccessible, as they shouldn't be needed by other plugins.
2019-05-31 15:57:51 +01:00
md678685 2ea3d8943e Update outdated meme 2019-05-30 19:34:18 +01:00
Drew Mitchell e4cc78a750 Implement PR #1682 - TPA Event (#1727) @DrewAMitchell
* Attempts to implement #1682 - TPARequestEvent
Awaiting further feedback. I've implemented the event, and elected to send a message to the requester of the TPA when the event gets cancelled.
* Fix formatting
* Fix up l18s errors, remove todos
* Clean up for merge
2019-05-30 19:17:57 +01:00
md678685 a08832cfc8 Implement /itemname command (#2573)
Implement /itemname command, across three PRs. Originally implemented by SupaHam, and updated by zsturgess and myself.
2019-05-30 19:16:43 +01:00
md678685 c97918df24 Add safe-usermap-names option to control usermap key sanitisation
This is necessary to stop players with Chinese characters in their username losing their balances.
2019-05-30 18:50:51 +01:00
Glare e9833d1cd2 Implement essentials.balancetop.exclude permission (#2499)
Closes #595.
2019-05-30 15:20:30 +01:00
md678685 111a18585d Allow clearing item names + add locale messages for /itemname 2019-05-30 15:12:52 +01:00
Zac Sturgess 155d3ec938 Update /itemname in plugin.yml
This contains changes from #2555 squashed into one commit.

Closes #2555.
2019-05-30 14:53:15 +01:00
Ali Moghnieh 8bafacbd51 Create /itemname command that names held items.
This contains changes from #672 minus messages, squashed into one commit.

Closes #672.
2019-05-30 14:53:06 +01:00
montlikadani 0e3f48ee54 Improve disposal, /bigtree and /fireball (#2461) @montlikadani
* Allow the Disposal inventory title to be configurable
* Add darkoak to `/bigtree`'s usage message
* Allow potions to be fired with `/fireball`

## Commits
* Update plugin.yml
* Update Commanddisposal.java
* Update messages.properties
* Update Commandfireball.java
* Update SignDisposal.java
* Fix import
* Remove colour code from disposal message
2019-05-30 14:03:12 +01:00
Trent Hensler b566b4a0c6 Update translations from Crowdin (#2571)
* New translations messages.properties (German)
* New translations messages.properties (Romanian)
* New translations messages.properties (Korean)
* New translations messages.properties (Latvian)
* New translations messages.properties (Lithuanian)
* New translations messages.properties (Norwegian)
* New translations messages.properties (Polish)
* New translations messages.properties (Portuguese)
* New translations messages.properties (Portuguese, Brazilian)
* New translations messages.properties (Russian)
* New translations messages.properties (Italian)
* New translations messages.properties (Serbian (Cyrillic))
* New translations messages.properties (Serbian (Latin))
* New translations messages.properties (Slovak)
* New translations messages.properties (Spanish)
* New translations messages.properties (Swedish)
* New translations messages.properties (Thai)
* New translations messages.properties (Turkish)
* New translations messages.properties (Japanese)
* New translations messages.properties (Icelandic)
* New translations messages.properties (Dutch)
* New translations messages.properties (Bulgarian)
* New translations messages.properties (Vietnamese)
* New translations messages.properties (French)
* New translations messages.properties (Hungarian)
* New translations messages.properties (English, United Kingdom)
* New translations messages.properties (English, United States)
* New translations messages.properties (Basque)
* New translations messages.properties (Bosnian)
* New translations messages.properties (Chinese Simplified)
* New translations messages.properties (Hebrew)
* New translations messages.properties (Chinese Traditional)
* New translations messages.properties (Chinese Traditional, Hong Kong)
* New translations messages.properties (Croatian)
* New translations messages.properties (Czech)
* New translations messages.properties (Danish)
* New translations messages.properties (Estonian)
* New translations messages.properties (Finnish)
* New translations messages.properties (Greek)
* New translations messages.properties (Ukrainian)
2019-05-28 17:56:17 +01:00
md678685 a9ed66d5e0 Add essentials.keepinv to plugin.yml 2019-05-28 12:24:07 +01:00
Josh Roy 94131edb32 Bump Bukkit to 1.14.2 (#2569)
* Bump to API 1.14.2

* Update v1_14_2_R01 as latest supported 1.14 build
2019-05-27 23:12:23 +01:00
md678685 e21863956c Fix checking for attached wall signs 2019-05-27 11:51:56 +01:00
md678685 4201e6ef85 Make all events async when not on primary thread
Fixes #2566, fixes #2556, fixes #2545.
2019-05-26 12:08:58 +01:00
Trent Hensler 5deb1de555 Allow AFK status test to pass. 2019-05-22 12:06:27 -07:00
md678685 c65534ebb1 Only make AfkStatusChangeEvent async when off primary thread 2019-05-22 11:39:26 +01:00
md678685 f22efce3ca Use MobCompat entries for other 1.11+ mobs 2019-05-18 23:51:40 +01:00
md678685 5f0909047d Use MobCompat.CAT throughout MobData 2019-05-18 22:45:43 +01:00
md678685 7cc4dc2f07 Make AfkStatusChangeEvent async 2019-05-18 20:56:57 +01:00
md678685 60ebe9e738 Add llama colour support; improve support for old game versions
Fixes issues with /spawnmob on older versions of the game.

(Also add llama colours, which were missing from the 1.11 update.)
2019-05-18 20:56:34 +01:00
minksuki a1297feb9d adds a permission node that keeps a player's inventory on death (#2531) @minksuki
Closes #2524.

Adds a permission node, `essentials.keepinv` so on player death their inventory will not be wiped.
2019-05-15 07:59:48 +01:00
Josh Roy 09598d0173 Update Bukkit to 1.14.1 (#2544)
* Update v1_14_1_R01 as latest supported 1.14 build

* Bump to API 1.14.1
2019-05-14 09:00:22 +01:00
md678685 35fc845040 Fix Metrics plugin name reporting 2019-05-13 19:15:33 +01:00
md678685 e59950966f Fix Metrics package name 2019-05-13 19:14:01 +01:00
md678685 98cc5b33a3 Update bStats Metrics to latest version
Now featuring server brand support!
2019-05-12 16:17:00 +01:00
Julian van Doorn d107d00ac3 Fix spawning shields with enchantments (#2515) @Argetan
* Moved comment to newline for style consistency.
* Fixed issue 2507 by checking if an enchantment is being applied.
* Added a couple newlines for readability.
* Removed faulty ifs).
2019-05-12 13:50:35 +01:00
md678685 ccc000a416 Add Villager variants, pt 2 2019-05-09 22:20:45 +01:00
md678685 7790f8818b Add Villager variants, pt 1 2019-05-09 15:12:51 +01:00
JRoy 72ca629cf1 Add 1.14 Enchantments 2019-05-09 13:36:09 +01:00
md678685 65017d7f5c Fix /kittycannon
The most important command of all!

(This hasn't been tested with 1.13 or below yet.)
2019-05-08 23:29:55 +01:00
md678685 6d4f7afc79 Improve VersionUtil prerelease handling
Actually includes updated regex this time! (I have no idea how I forgot to update it in cfba203981 - I had already written out the regex)

Incorporates part of https://github.com/EssentialsX/Essentials/pull/2523 - thanks @JRoy.
2019-05-08 23:26:40 +01:00
md678685 4fcb032791 Update FakeServer 2019-05-08 23:23:15 +01:00
md678685 0e668fa0f2 Fix plural suffixes for fish and foxes 2019-05-08 23:06:50 +01:00
md678685 68b933a501 Add Ocelot.Type fallbacks for all MobCompat.CatTypes 2019-05-08 23:06:28 +01:00
md678685 5236ad9f64 Remove redundant BABY_FOX 2019-05-08 22:56:25 +01:00
md678685 937c18fe1d Update FakeWorld 2019-05-08 22:43:57 +01:00
md678685 fb48aaba9d Initial cross-version mob compatibility
Incorporates part of https://github.com/EssentialsX/Essentials/pull/2523 - thanks @JRoy.
2019-05-08 22:40:51 +01:00
md678685 365efe4f2d Implement missing FakeWorld and OfflinePlayer methods 2019-05-08 13:49:54 +01:00
md678685 78b2dba42a Bump to API 1.14 2019-05-08 13:49:35 +01:00
Julian van Doorn f793b7607f OS X compatible buildtools.sh (#2513) @Argetan
* OS X compatible buildtools.sh

* Update buildtools.sh
2019-04-30 07:55:54 +01:00
md678685 c567bc22e9 Compile against 1.14-pre5 2019-04-24 14:30:53 +01:00
md678685 d282462547 Use MaterialUtil to check signs 2019-04-24 14:28:15 +01:00
md678685 af4cfd3fe9 Update bStats Metrics to use Gson 2019-04-24 13:54:33 +01:00
md678685 cfba203981 Add prerelease support to VersionUtil 2019-04-24 13:37:43 +01:00
Glare Masters d680ed7363 Check /tpacancel permissions before sending message (#2498)
Fixes #1354.
2019-04-23 09:22:50 +01:00
md678685 69232c0717 Fix missing formatting code in geoipCantFind 2019-04-22 15:24:31 +01:00
latiku b4baa28f01 fix geoip country returning "." if the user is joining from localhost (#2494) @latiku
Implements a check to see if the user's address is `localhost` or `127.0.0.1`, and if so return that the country is unknown.

**Edit by @md678685: fixes #2471.**
2019-04-22 09:38:06 +01:00
md678685 0aa11b58b9 Update items.json
Updated to md678685/essx-scripts@e6394a2884

* Fix overlapping armor/wooden pressure plate aliases
2019-04-19 15:10:10 +01:00
md678685 7b60b562b9 Update items.json
Update items.json to md678685/essx-scripts@581db130ef

Changes:
* Add pressure plate aliases
* Add "mushroomcow" aliases for mooshroom spawners
* Add zombie pigman spawner aliases
2019-04-19 14:49:36 +01:00
montlikadani 6377cbfb2b Remove stale messages and add/change formatting in others (#2486) 2019-04-18 13:25:25 -04:00
montlikadani 3f5f9cc717 Fixed when the mail has already cleared (#2063) 2019-04-18 13:18:42 -04:00
Johnny Cao eac1e9b574 Fixes #1928 - Auto-AFK issue: AFK timer not reset on disconnect (#2458)
Update activity regardless of cancel-afk-on-interact setting
2019-04-17 20:45:07 -04:00
Glare Masters 26d63da7aa [Feature] Implemented a message to say teleporting to home. (#2489)
[Feature] Implemented a message to say teleporting to home.
2019-04-17 19:14:44 -04:00
Joseph Hirschfeld 722181439e Merge pull request #1953 from Xeyame/#1899
Expand /exp command
2019-04-17 12:18:58 -04:00
Joseph Hirschfeld ddcb7041f1 Merge pull request #2455 from AgentTroll/patch-94
Fixes #94 - Player with same first letters conflict
2019-04-17 02:46:20 -04:00
Joseph Hirschfeld 8af33e0ae2 Merge pull request #2166 from mathiascode/commandevents
Use chat instead of dispatchCommand
2019-04-17 02:33:29 -04:00
Joseph Hirschfeld d01e12ac14 Merge pull request #2158 from pop4959/near-fix
Sort /near by nearest player.
2019-04-17 02:31:38 -04:00
Joseph Hirschfeld 8c0aa840ab Merge pull request #1949 from Ichbinjoe/2.x_feature_jail_no_teleport
[Feature] Add config optn. to disable jail free tp
2019-04-17 02:04:16 -04:00
md678685 05118e9498 Merge pull request #2484 from Xeyame/2.x
Allow using environment variable to set xmx flag in buildtools.sh
2019-04-16 15:47:23 +01:00
Xeyame 7838adf833 Allow using environment variable to set xmx flag 2019-04-16 16:34:57 +02:00
md678685 e230cee91e Add new item database API (#2472)
* Allow resolver functions to be added to item databases

* Allow resolvers to add item names to list

* Make getResolverNames package-private
2019-04-15 10:09:16 +01:00
md678685 8e4fc77244 Merge pull request #2469 from N3FS/feature/command-send
Add PlayerCommandSendEvent listener to hide commands in autocomplete
2019-04-15 10:07:49 +01:00
md678685 0d572036f8 New Crowdin translations (#2476)
* New translations messages.properties (English, United States)

* New translations messages.properties (Russian)

* New translations messages.properties (Korean)

* New translations messages.properties (Lithuanian)

* New translations messages.properties (Polish)

* New translations messages.properties (Portuguese)

* New translations messages.properties (Portuguese, Brazilian)

* New translations messages.properties (Romanian)

* New translations messages.properties (Serbian (Cyrillic))

* New translations messages.properties (Italian)

* New translations messages.properties (Serbian (Latin))

* New translations messages.properties (Slovak)

* New translations messages.properties (Spanish)

* New translations messages.properties (Swedish)

* New translations messages.properties (Thai)

* New translations messages.properties (Turkish)

* New translations messages.properties (Ukrainian)

* New translations messages.properties (Japanese)

* New translations messages.properties (Hungarian)

* New translations messages.properties (English, United Kingdom)

* New translations messages.properties (Chinese Traditional, Hong Kong)

* New translations messages.properties (German)

* New translations messages.properties (Norwegian)

* New translations messages.properties (Bulgarian)

* New translations messages.properties (Basque)

* New translations messages.properties (Bosnian)

* New translations messages.properties (Chinese Simplified)

* New translations messages.properties (Chinese Traditional)

* New translations messages.properties (Croatian)

* New translations messages.properties (Hebrew)

* New translations messages.properties (Czech)

* New translations messages.properties (Danish)

* New translations messages.properties (Dutch)

* New translations messages.properties (Estonian)

* New translations messages.properties (Finnish)

* New translations messages.properties (French)

* New translations messages.properties (Greek)

* New translations messages.properties (Vietnamese)
2019-04-07 21:21:29 +01:00
md678685 26fdd0ff6b Fix playerMutedFor[Reason] formatting codes 2019-04-07 21:19:45 +01:00
Trent Hensler 70a4aee930 New translations messages.properties (Vietnamese) 2019-04-07 13:11:55 -07:00
Trent Hensler 3631323aa7 New translations messages.properties (Greek) 2019-04-07 13:11:53 -07:00
Trent Hensler 1fd7d18056 New translations messages.properties (French) 2019-04-07 13:11:51 -07:00
Trent Hensler a60f67cd0a New translations messages.properties (Finnish) 2019-04-07 13:11:49 -07:00
Trent Hensler 5ba781d00e New translations messages.properties (Estonian) 2019-04-07 13:11:46 -07:00
Trent Hensler 17c5d25996 New translations messages.properties (Dutch) 2019-04-07 13:11:44 -07:00
Trent Hensler bd9f271eff New translations messages.properties (Danish) 2019-04-07 13:11:42 -07:00
Trent Hensler 89b4bd2405 New translations messages.properties (Czech) 2019-04-07 13:11:40 -07:00
Trent Hensler 4da9095c59 New translations messages.properties (Hebrew) 2019-04-07 13:11:37 -07:00
Trent Hensler 75e84a5797 New translations messages.properties (Croatian) 2019-04-07 13:11:35 -07:00
Trent Hensler 54d64dbb5f New translations messages.properties (Chinese Traditional) 2019-04-07 13:11:32 -07:00
Trent Hensler 03e746953c New translations messages.properties (Chinese Simplified) 2019-04-07 13:11:30 -07:00
Trent Hensler ec8a51b06c New translations messages.properties (Bosnian) 2019-04-07 13:11:28 -07:00
Trent Hensler 369c08a624 New translations messages.properties (Basque) 2019-04-07 13:11:26 -07:00
Trent Hensler 7a8e5e92d9 New translations messages.properties (Bulgarian) 2019-04-07 13:11:23 -07:00
Trent Hensler 185ec7ff2b New translations messages.properties (Norwegian) 2019-04-07 13:11:21 -07:00
Trent Hensler af986cc7b2 New translations messages.properties (German) 2019-04-07 13:11:18 -07:00
Trent Hensler 25d96ccfa7 New translations messages.properties (Chinese Traditional, Hong Kong) 2019-04-07 13:11:16 -07:00
Trent Hensler b45c42ef22 New translations messages.properties (English, United Kingdom) 2019-04-07 13:11:14 -07:00
Trent Hensler ea2ac3d483 New translations messages.properties (Hungarian) 2019-04-07 13:11:12 -07:00
Trent Hensler 873df96d0d New translations messages.properties (Japanese) 2019-04-07 13:11:10 -07:00
Trent Hensler d69495baa7 New translations messages.properties (Ukrainian) 2019-04-07 13:11:08 -07:00
Trent Hensler 06ff8f24fe New translations messages.properties (Turkish) 2019-04-07 13:11:06 -07:00
Trent Hensler b996608455 New translations messages.properties (Thai) 2019-04-07 13:11:04 -07:00
Trent Hensler 6c1c22132e New translations messages.properties (Swedish) 2019-04-07 13:11:02 -07:00
Trent Hensler 8b326d5852 New translations messages.properties (Spanish) 2019-04-07 13:11:00 -07:00
Trent Hensler dd34f65c98 New translations messages.properties (Slovak) 2019-04-07 13:10:58 -07:00
Trent Hensler 0bd0f853f3 New translations messages.properties (Serbian (Latin)) 2019-04-07 13:10:55 -07:00
Trent Hensler e7a75efaff New translations messages.properties (Italian) 2019-04-07 13:10:53 -07:00
Trent Hensler 2904b50061 New translations messages.properties (Serbian (Cyrillic)) 2019-04-07 13:10:51 -07:00
Trent Hensler 3b6ac632d9 New translations messages.properties (Romanian) 2019-04-07 13:10:48 -07:00
Trent Hensler 9ad3f0e0d7 New translations messages.properties (Portuguese, Brazilian) 2019-04-07 13:10:45 -07:00
Trent Hensler 9529a4ba02 New translations messages.properties (Portuguese) 2019-04-07 13:10:42 -07:00
Trent Hensler 69b9ab097b New translations messages.properties (Polish) 2019-04-07 13:10:40 -07:00
Trent Hensler 4b14c4bcc6 New translations messages.properties (Lithuanian) 2019-04-07 13:10:38 -07:00
Trent Hensler 5154c670c0 New translations messages.properties (Korean) 2019-04-07 13:10:36 -07:00
Trent Hensler 09b699cc9c New translations messages.properties (Russian) 2019-04-07 13:10:34 -07:00
Trent Hensler f2a212e3a4 New translations messages.properties (English, United States) 2019-04-07 13:10:31 -07:00
md678685 19ca946e3b Add Estonian alias to Crowdin config 2019-04-07 21:08:30 +01:00
md678685 e21be39c13 Add Basque alias to Crowdin config 2019-04-07 21:02:42 +01:00
md678685 8fcfff7abd Update Crowdin config 2019-04-07 21:01:22 +01:00
md678685 bcc150a014 Update l10n configs 2019-04-07 20:22:48 +01:00
md678685 3d97e93831 Implement missing OfflinePlayer location methods 2019-04-07 17:06:17 +01:00
md678685 9d93d4db54 Only log removed commands is debug enabled 2019-04-07 17:03:56 +01:00
md678685 0d8aec7eea Add PlayerCommandSendEvent listener to hide commands in autocomplete 2019-03-31 20:35:47 +01:00
md678685 7b165c6c2c Merge pull request #2450 from AgentTroll/patch-2414
Fixes #2414 - Warp signs no permission message
2019-03-15 12:11:17 +00:00
md678685 d3cee314c6 Merge pull request #2451 from AgentTroll/patch-2403
Fixes #2403 - Ability to execute /back for another player
2019-03-15 12:10:33 +00:00
md678685 4395245aab Merge pull request #2454 from AgentTroll/patch-2415
Fixes #2415 - Command for last reply message option
2019-03-15 12:10:10 +00:00
md678685 9d4b0a13c5 Merge remote-tracking branch 'origin/pr/1557' into 2.x 2019-03-15 11:59:35 +00:00
md678685 c908290c27 Simplify willMute condition 2019-03-15 11:58:30 +00:00
md678685 f5c21d1089 Merge branch '2.x' into final_mute_reason_issue#385 2019-03-15 11:52:50 +00:00
Johnny Cao 883fc75f47 Clarifies the last recipient config key 2019-03-10 01:42:10 -08:00
AgentTroll eaac3049af Fix getPlayer(...) for offline players having similar names 2019-03-09 18:50:55 -08:00
AgentTroll f68fb52af1 Add command to toggle reply player functionality 2019-03-09 15:39:45 -08:00
AgentTroll 863bd5a89e Add /back target capability 2019-03-08 22:41:59 -08:00
AgentTroll 50225624a5 Add message for failing sign warp permission check 2019-03-08 15:53:04 -08:00
md678685 25ddaef423 Merge pull request #2329 from triagonal/issue-2311
Implement config option for sleep ignoring AFK players
2019-03-08 22:15:53 +00:00
md678685 585f2bef07 Merge pull request #2310 from pop4959/command-tpauto
Implement tpauto command
2019-03-08 17:19:31 +00:00
md678685 017ea1a4fe Remove unnecessary types 2019-03-08 11:24:42 +00:00
md678685 3b4b5bcd8e Remove Lombok
Remove the (already minimal) usage of Lombok. This will ease development for people who don't already have their IDE set up for Lombok support.

It's also totally unnecessary - it took less than 60 seconds to generate the code needed to replace Lombok annotations in Jails and Spawns.
2019-03-08 11:24:42 +00:00
md678685 f57557b43a Bump version to 2.16.1 2019-03-01 22:45:25 +00:00
md678685 0711fd6f9e Add #version line to allow automatic items.json updates 2019-03-01 12:04:08 +00:00
md678685 b5ecbd1739 Remove Vault repo
Fixes Travis builds and slow builds - Maven pauses while trying to reach the repo and so Travis assumes that the build has failed.
2019-03-01 11:41:29 +00:00
md678685 dda5e4e333 Merge pull request #2402 from Techno3600/patch-1
Pull Request for #2282
2019-03-01 11:32:46 +00:00
pop4959 74b0e71015 More efficient distance calculation 2019-02-26 19:54:19 -08:00
md678685 dde4a36df0 Economy API: Attempt to find users by UUID if username not present (#2432)
Attempt to find user by UUID if username not present. Fixes (maybe) #2400.

https://github.com/EssentialsX/Essentials/issues/2400#issuecomment-466043896
2019-02-22 18:10:36 +00:00
triagonal 31b98fb9f3 allow console to use color codes when sending mail (#2435) @triagonal 2019-02-22 14:34:56 +00:00
kashike 289d34d96c Relocate PaperLib in EssentialsXSpawn too
fixes #2433
2019-02-22 09:58:02 +00:00
md678685 eafd110ed0 Update items.json
Add spawner aliases that end in "spawner".
2019-02-20 14:50:43 +00:00
md678685 e72644abf4 Update items.json
* Add mooshroom spawners
* Add new aliases for red sandstone, sandstone, stone and prismarine variants
2019-02-20 14:42:22 +00:00
md678685 b267103274 Remove getMap(short) method from FakeServer 2019-02-20 12:45:37 +00:00
DoNotSpamPls 3856a690eb Use PaperLib to load chunks and teleport players async (#2409)
* Remove outdated permission plugin handlers, minor test fixes

* Re-add PermissionEX handler

* Use PaperLib to load chunks async whenever possible

* Revert "Use PaperLib to load chunks async whenever possible"

This reverts commit db4df6f3cf.

* Use PaperLib to load chunks and teleport players async

* Resolve some PR issues

* Update PaperLib, return teleport causes

* Remove useless PaperLib usage in LocationUtil

* Fix FakeServer spacing
2019-02-20 12:25:05 +00:00
md678685 f214696664 Check Protect/AntiBuild config materials against Material enum (#2431) 2019-02-20 12:24:30 +00:00
md678685 9e73c29b40 Fix creating and using kits on legacy versions (#2428)
* Attempt to look up legacy items in Material enum
* Use name method when serializing ItemStacks
* Make name uppercase before looking up in Material enum
2019-02-20 12:24:07 +00:00
md678685 aca83bd462 Switch Vault dependency to VaultAPI (#2430)
* Switch Vault dependency to VaultAPI
* Remove direct Vault class usage from VaultEco
2019-02-20 11:28:20 +00:00
md678685 189d6a23c6 Add README section about depending on EssX 2019-02-19 21:58:43 +00:00
md678685 441f88deea Implement missing FakeServer methods 2019-02-17 19:01:47 +00:00
Wiz_Techno 6d6666dace Pull Request for #2282
"Obsolete entries in items.csv should be removed"
2019-01-31 23:14:21 -05:00
Rafał Pokrywka fb779533e6 Replace nbsp with a space when formatting messages (#2394) @ravkr 2019-01-27 12:15:03 +00:00
DoNotSpamPls 7325113a8c Remove outdated permission plugin handlers, minor test fixes (#2367) @DoNotSpamPls
* Remove outdated permission plugin handlers, minor test fixes

* Re-add PermissionEX handler

* Use PaperLib to load chunks async whenever possible

* Revert "Use PaperLib to load chunks async whenever possible"

This reverts commit db4df6f3cf.
2019-01-27 12:14:16 +00:00
Glare Masters 827217823e Add the ability to make spectator gamemode signs (#2386) @darbyjack
Fixes #2383.
2019-01-20 10:14:20 +00:00
md678685 060dfc69f4 Update items.json
Fixed regression of unspawnable items not being marked as such, impacting the alias generation process. This fix also retains the ability to specify non-item blocks in the EssentialsX Protect material lists.
2019-01-12 22:07:03 +00:00
md678685 b831713737 Check whether item is spawnable in FlatItemDb 2019-01-12 21:43:36 +00:00
md678685 7da90b3a6b Load item spawn blacklist after item DB
Partially resolves #2360.
2019-01-12 21:43:36 +00:00
md678685 32540c23ab Add IItemDb#isReady to check if item database is available 2019-01-12 21:43:36 +00:00
md678685 d24b0616f8 Hide ServerListPingEvent exceptions thrown by CB's LegacyPingHandler (#2378)
Fixes #2327.
2019-01-12 17:19:11 +00:00
md678685 9aef2ef883 Update items.json
Add several new aliases. Closes #2348.
2019-01-09 15:10:38 +00:00
md678685 727d473319 Fix Enchantments on 1.12.2 and lower 2019-01-09 14:23:55 +00:00
md678685 8225e51867 Fix XMPP metrics reporting
The XMPP config was being reported as valid when it wasn't valid.
2019-01-09 13:57:18 +00:00
md678685 1ba6c2a596 Properly fix language mappings 2019-01-08 22:19:16 +00:00
md678685 60a166aeb0 Fix language mapping in Crowdin config 2019-01-08 21:45:46 +00:00
md678685 65c2155bca Update Crowdin config
Map most locales to the existing locale files.
2019-01-08 21:36:16 +00:00
md678685 6031c01584 Update Crowdin config
Fix file placement and map locale codes to existing translations
2019-01-08 21:21:35 +00:00
md678685 da8e8c8a25 Update Crowdin config
Crowdin should only use `messages.properties` as the "source" and this file will get copied to all the other language files like `messages_de.properties` for the German translation, `messages_ro.properties` for the Romanian translation etc.
2019-01-08 21:14:56 +00:00
Trent Hensler 70a750a32d Update Crowdin configuration file 2019-01-08 12:48:25 -08:00
md678685 7c63324504 Fix allow-old-id-signs allowing creation of signs with IDs 2019-01-07 22:38:13 +00:00
md678685 dd41b10522 attempt to fix Essentials overriding Skulls (#2356) @kennyrkun 2019-01-05 18:48:33 +00:00
triagonal 7948e764d4 disallow setting bed homes in non-overworld dimensions (#2335) @triagonal 2019-01-05 18:43:27 +00:00
DoNotSpamPls 82ede4530a Lots of little fixes in the Essentials modules (#2337) @DoNotSpamPls
Look at changed files for the changes
2019-01-05 18:42:09 +00:00
md678685 e8ab2db8e8 Improve ServerListPingEvent warning handling 2019-01-05 18:12:04 +00:00
md678685 8882e0214c Add bStats metrics for each EssentialsX module (#2333)
Does what it says on the tin.
2019-01-05 17:48:44 +00:00
md678685 4adb669cdd Add support for spawners with entities on 1.13+ 2019-01-05 17:35:29 +00:00
md678685 7e1d258dd3 Cache BukkitVersion in getServerBukkitVersion 2019-01-05 16:29:11 +00:00
md678685 417fe29e21 Remove duplicated item IDs in messages 2019-01-05 16:28:53 +00:00
md678685 bd8ef2a25d Only show available warps in tab complete
Fixes #2353 by only displaying warps where the player has the permission `essentials.warps.<warp>`.
2019-01-05 15:45:34 +00:00
md678685 fd01b75c33 Wrap UnsafeValues.fromLegacy() in try/catch for older versions
Should address #2352.
2019-01-05 15:27:07 +00:00
md678685 1388755d2a Wrap Enchantment.getByKey in try/catch for older versions
Should address #2351.
2019-01-05 15:17:58 +00:00
md678685 97cc3d0066 Update items.json
* Fix wrong harming potion mapping (fixes #2349)
* Add mob spawner aliases (not complete, related to #2347)
* Closes #2348:
  - Fix log aliases mistakenly pointing to stripped logs
  - Fix sandstone alias
  - Add shorter concrete powder aliases
2019-01-05 15:04:59 +00:00
md678685 694cf7a79e Revert 1.13 API hacks in LegacyItemDb
Earlier changes broke the items.csv database on older versions - this should now be fixed.
2019-01-04 15:01:18 +00:00
md678685 da89efb79f Make VersionUtil not explode when patch is not present 2019-01-03 22:16:14 +00:00
md678685 04ec013407 Update README to reflect 1.13 support 2019-01-03 21:25:48 +00:00
md678685 023cf6a1aa Merge pull request #2278 from EssentialsX/1.13
Full 1.13 support + 2.16.0 release
2019-01-03 20:56:14 +00:00
md678685 f7cbb141f8 Release 2.16.0
🎉
2019-01-03 20:47:24 +00:00
md678685 5690952516 Implement missing OfflinePlayer methods 2019-01-03 20:42:03 +00:00
md678685 e94202c55a Use 1.8-friendly User#getItemInHand method in commands 2019-01-03 20:33:08 +00:00
md678685 aa6ad271a0 Remove redundant metricsEnabled field from Settings 2019-01-03 20:33:08 +00:00
md678685 3b41bb47b6 Improve Travis build script (#2338)
I've added a new script at `scripts/buildtools.sh` that is responsible for:
* Checking whether CraftBukkit 1.8 and 1.8.3 are already available in the local Maven repo
* Downloading BuildTools if not already present
* Running BuildTools if necessary

This improves Travis build times as it now doesn't run BuildTools twice for *every single build*, instead running it only if the Travis cache fails and CraftBukkit is missing for some other reason.
2019-01-01 16:13:50 +00:00
md678685 e7bdb7fabc Improve the wording of the README's "Building" section 2019-01-01 15:42:45 +00:00
md678685 110698223d Travis: make build prep script executable 2019-01-01 15:23:35 +00:00
md678685 437be593b9 Add new build preparation script 2019-01-01 15:10:59 +00:00
md678685 502d37b574 Update Lombok to compile on Java 9+ 2018-12-31 17:44:08 +00:00
md678685 df59f9f859 Merge remote-tracking branch 'origin/2.x' into 1.13 2018-12-31 14:59:12 +00:00
md678685 f436fbab6b Remove redundant BuildTools runs 2018-12-31 14:54:59 +00:00
seema84 8404720501 change typos (#2328) @seema84
* change typos

* format text

* remove double color
2018-12-31 13:08:57 +00:00
md678685 4431d452f1 Bump to 2.16-pre4
Pretty much there now.
2018-12-31 13:02:08 +00:00
md678685 6a529d6671 Update EssentialsX Protect with cross-version enum lookups 2018-12-31 12:54:43 +00:00
md678685 78fca9a67a Updates signs with cross-version enum lookups 2018-12-31 12:53:41 +00:00
md678685 0114b5e4f6 Update several commands with cross-version enum lookups 2018-12-31 12:53:23 +00:00
md678685 5a14a64b6c Add cross-version support to SpawnMob 2018-12-31 12:24:41 +00:00
md678685 b555ea6350 Add cross-version support to MobData 2018-12-31 12:20:05 +00:00
md678685 361ae1dd16 Use constant field for "harp"/"piano" sound 2018-12-31 12:19:22 +00:00
md678685 58117eba88 Remove redundant BuildTools instructions 2018-12-31 12:18:45 +00:00
md678685 6260b49b4f Restore item ID messages in /itemdb 2018-12-31 11:57:15 +00:00
md678685 988239267b Restore durability permissions checks in AntiBuild 2018-12-31 11:56:50 +00:00
md678685 19cffe3872 Restore ID-based charges in /repair 2018-12-31 11:39:08 +00:00
md678685 3b1cef918e Simplify item spawn permission checks; restore ID-based item spawn perms 2018-12-31 11:29:27 +00:00
triagonal 3d004d2a81 change config setting name 2018-12-31 16:42:42 +11:00
triagonal d1bbebad3a updated config comments 2018-12-30 20:49:58 +11:00
triagonal 42714ff8af implement config toggle for afk users bypassing sleep 2018-12-30 20:38:34 +11:00
md678685 3553328f7a Bump to 2.16-pre3 2018-12-29 21:22:08 +00:00
md678685 0202271f00 Add missing FakeWorld methods 2018-12-29 21:16:17 +00:00
md678685 d91d6a419c Update items.json
* Fix incorrect "cobblestone" and "stone" aliases
* Fix stripped log aliases not appearing
* Fix meat/fish aliases pointing to spawn eggs
2018-12-28 16:40:39 +00:00
md678685 5173090474 Update items.json
Adds more minecart, meat, fish and hay aliases.
2018-12-26 21:05:48 +00:00
md678685 c26df8318f Update items.json
* Add more shorter spawn egg aliases
* Add new trapdoor aliases
* Add new infested block aliases and stone brick variants
2018-12-26 19:24:50 +00:00
md678685 7b44f0088a Update items.json
* Add spawn eggs aliases
* Add new aliases for several items and blocks like beetroot, pumpkins and crafting tables
* Remove `WALL_` materials (these are unspawnable)
2018-12-26 18:05:55 +00:00
md678685 aa4d3cc9fd Bump to 2.16-pre2 2018-12-25 00:27:54 +00:00
md678685 246fd03265 Fix typo in README 2018-12-23 23:33:46 +00:00
md678685 55074872fe Add setting to enable item ID recognition on signs
Item IDs can now be enabled for existing signs by manually changing a config option, but there is no facility to create new signs with item IDs.
2018-12-23 23:02:36 +00:00
md678685 28559dda3a Lowercase the provided ID in FlatItemDb#get 2018-12-23 19:45:23 +00:00
md678685 cbcfad5b2e Merge branch '2.x' into 1.13 2018-12-23 19:33:20 +00:00
md678685 a9ad440860 Overhaul AbstractItemDb.serialize to use MaterialUtil methods 2018-12-23 19:32:10 +00:00
md678685 5104463593 Add MaterialUtil.getColorOf 2018-12-23 19:31:33 +00:00
md678685 4b1c51c21d Reword IItemDb#serialize docs 2018-12-23 18:02:38 +00:00
md678685 236ef52980 Improved README (#2293)
I've made several improvements to the README, including:
* Overall rewording to make phrasing feel less awkward
* Added links to Patreon
* More consistent images for links at top
* Consolidated "Why you should use it" and "Other info" into "Why use EssentialsX?"
* More specific about version support
* Moved "Support" section above "Building" and added explanation
* Removed redundant "Commit Guidelines" section
  - It has been totally ignored for years, and it doesn't make much sense to keep it
* Added a new "Contributing" section near the bottom
2018-12-23 17:21:31 +00:00
md678685 f220c5b406 Update Estonian sudoExempt message
Thanks to @Madis0 for [pointing this out and translating it](https://github.com/EssentialsX/Essentials/pull/2228#issuecomment-449586891).
2018-12-22 17:47:39 +00:00
Thomas 9415582fe1 Update messages_nl.properties (#2129) @DutchUser
* Update messages_nl.properties

* Update messages_nl.properties

* Update messages_nl.properties

* Update messages_nl.properties

* Update messages_nl.properties
2018-12-22 17:42:42 +00:00
Sprungente a5a3630727 [Finish] Improving German localization (#2198) @Sprungente
* Improving 

I found some stuff to improve the translation. I'm not done yet but i think it's ready to get an eye on it. 

Hope it will be used :)

Greets Sprungente/enterih

* mistake^^

^

* Part 2

Adding more Improvements
Hope it helps other serverowners^^

* Part 2 fixes

* Part 3 



Notice for me 
a-d finished
\u00f6 ö    \u00e4 ä  \u00fc ü

* Part 4

Notice for me 
a-i finished
\u00f6 ö    \u00e4 ä  \u00fc ü

* Last part 

is line 456
requiredBukkit=\u00a76* \! * Du brauchst mindestens CraftBukkit Build \#{0}, lade es von http\://dl.bukkit.org/downloads/craftbukkit/
still exist? If yes, could a reference to spigot be added?

It's ready to merge. Can i take care on it in the future?

* small polishing

* Update messages_de.properties

* Update messages_de.properties

* Adding new strings 

added strings from #2278
2018-12-22 17:39:44 +00:00
Madis f4c36d9c43 Estonian translation update (#2228)
* Initial improvements

* Half done

* Almost done

* Translation done

* Encode umlauts

* Additional refinements

* Minor fix

* Some more tweaks

* Minor wording change

* 1.13 strings
2018-12-22 17:36:47 +00:00
pop4959 64930e3771 Fix messages & add warning 2018-12-21 01:58:44 -08:00
pop4959 16381234e0 Implement tpauto command 2018-12-19 02:50:30 -08:00
md678685 492005d00a Fix LegacyItemID method override 2018-12-15 19:11:41 +00:00
md678685 149d9b61cc Add methods to facilitate conversion from IDs to new Materials 2018-12-15 18:54:01 +00:00
md678685 77ffb6a3d5 Slightly simplify FlatItemDb 2018-12-15 18:53:06 +00:00
md678685 d95b632884 Merge branch '2.x' into 1.13 2018-12-11 14:31:42 +00:00
md678685 579f554edb Update nickname again after toggling AFK status 2018-12-11 13:26:15 +00:00
md678685 050287f306 Add 1.13 enchantments
Fixes #2254.
2018-12-11 10:04:38 +00:00
md678685 dafe156212 Merge branch '2.x' into 1.13 2018-12-09 15:25:31 +00:00
md678685 48bf264178 Fix discrepancies between default and EN locale 2018-12-09 15:21:07 +00:00
md678685 769dbe8852 Fix BukkitVersion's toString and equals 2018-12-09 15:16:44 +00:00
md678685 67bccb865a Remove colour codes from serverUnsupported in EN locale 2018-12-09 15:16:18 +00:00
md678685 d1e60de04a Ignore kits.yml created during tests 2018-12-09 15:15:55 +00:00
md678685 89d592ce43 Improve item-spawn-blacklist load logging 2018-12-09 14:58:56 +00:00
md678685 c06dda886d Actually use the force-enable-recipe option from the config 2018-12-09 14:58:36 +00:00
md678685 23d92fac63 Bump version to 2.16.0 and release 2.16-pre1 2018-12-09 14:33:53 +00:00
md678685 5922b85290 Move SHIELD to from MetaItemStack to MaterialUtil 2018-12-09 13:47:52 +00:00
md678685 814e5a643e Add SIGNS and SPAWNER to MaterialUtil 2018-12-09 13:47:22 +00:00
md678685 3db3a272d5 Update default kits.yml file
Item IDs are no longer supported in 1.13+, so remove them from the default kits section.
2018-12-09 13:07:11 +00:00
md678685 2d703fbc80 Add damage value support to FlatItemDb
...in case you wanted to give players broken swords, or something?
2018-12-09 13:04:21 +00:00
md678685 b49d3cc21c Remove unnecessary kits file
This is a leftover from dev environments and is *not* the one copied into the jar during build.
2018-12-09 13:02:44 +00:00
md678685 02b5d2357a Add missing FakeServer methods 2018-12-09 12:29:28 +00:00
md678685 1206178eca Use utility methods in MetaItemStack 2018-12-09 12:17:13 +00:00
md678685 3df3f8a812 Add several cross-version item type checks to MaterialUtil 2018-12-09 12:17:13 +00:00
md678685 7049952b07 Load forceEnableRecipe during Settings.reloadConfig 2018-12-09 12:17:13 +00:00
Mark Vadeika a18ce40921 Hiding display names (#2248) @AllTheMegahertz
Prevents a user's nickname from appearing if they are hidden, if `hide-displayname-in-vanish: true` in the config. Closes #2221.

* Does not return display name if user is hidden

* Added hide-displayname-in-vanish field

* Added hideDisplayNameInVanish()

* Changed to only hide display name if specified in config

* Changed hideDisplayNameInVanish to default to false if not specified in config.yml
2018-12-09 11:02:45 +00:00
md678685 6a6383462d Allow admins to force enable /recipe if they want
Add `force-enable-recipe`, which allows server admins to manually enable `/recipe` despite potential duplication exploits. Use this at your own risk!

Related: #1397
2018-12-08 16:41:24 +00:00
md678685 44301fae4f Fix Worth.setPrice on 1.13+; add Javadocs to Worth 2018-12-08 16:32:09 +00:00
md678685 6ee84510ea Update bStats-Metrics 2018-12-06 17:49:08 +00:00
md678685 6ecdc8d7fc Enu-moo-til 2018-12-06 17:44:22 +00:00
md678685 35a2a4d803 Add several version warning messages 2018-12-06 17:41:32 +00:00
md678685 7b67b3b858 Don't send empty line join/quit messages
GitHub meta: fixes #991 fixes #2289
2018-12-06 14:06:25 +00:00
md678685 4011810536 Correctly use LegacyItemDb after detecting version < 1.13 2018-11-19 22:51:07 +00:00
md678685 85ea07c97e Fix VersionUtil regex matching and BukkitVersion.toString 2018-11-19 22:48:33 +00:00
md678685 41b2449cdd Change /enchant's default level from -1 to 1 2018-11-19 21:11:25 +00:00
md678685 ec83a5fff2 Add EntityPickupItemEvent listener to AntiBuild 2018-11-19 20:20:10 +00:00
md678685 ded6f06ed2 Merge remote-tracking branch 'origin/2.x' into 1.13 2018-11-19 19:48:38 +00:00
md678685 2605e050a0 Deduplicate ItemDb code 2018-11-19 19:41:01 +00:00
md678685 19b1e19e42 Remove extraneous imports 2018-11-19 19:30:35 +00:00
md678685 f7a1149cac Port old ItemDb back 2018-11-19 14:13:05 +00:00
md678685 7dd52dab32 Add non-NMS VersionUtil
*Should* work on Glowstone. TODO: use this instead of ReflUtil where appropriate.
2018-11-19 14:12:10 +00:00
md678685 937aec600a Implement more FakeServer methods 2018-11-19 12:52:19 +00:00
md678685 4802053da6 Rename en-GB to en_GB for consistency 2018-11-19 12:51:26 +00:00
md678685 0105dff7ac Update AntiBuild default entries to enum names 2018-11-19 12:49:34 +00:00
md678685 8cc448efcf Remove meta/durability checks from AntiBuild 2018-11-19 11:38:50 +00:00
md678685 982b358bf8 Bump AntiBuild and Protect to api-version: 1.13 2018-11-19 11:28:31 +00:00
md678685 ffc80d61af Implement missing FakeWorld and OfflinePlayer methods 2018-11-19 11:26:05 +00:00
md678685 f55956612c Add messages_en-GB.properties (#2206)
Tins what it does on the say.
2018-11-19 08:38:37 +00:00
md678685 cd3b342d74 Target Bukkit 1.13.2 2018-10-31 15:00:54 +00:00
md678685 ba959586e2 Merge remote-tracking branch 'games647/java9' into 1.13 2018-10-31 14:53:49 +00:00
md678685 4c07e584b7 Default to max stack size 2018-10-31 14:47:45 +00:00
Banbeucmas 280d1215de Adding EssentialsWarpEvent (#1921) @Banbeucmas
* Adding EssentialsWarpEvent for checking if player is wrapping

* Spacing

* Adding Trade parameter

* Refactoring

* Adding #setWarp() to the Event

* Spacing

* Documenting the purpose of the Event

* Javadoc?
2018-10-28 18:53:52 +00:00
md678685 22538ba7c9 Merge branch '1.13' into 2.x_feature_jail_no_teleport 2018-10-28 18:46:53 +00:00
montlikadani a2a95ed840 Added acacia and dark oak tree types (#2001) @montlikadani
* Update Commandbigtree.java

* Update Commandbigtree.java

* Update Commandtree.java
2018-10-28 18:41:46 +00:00
md678685 4bd9461282 Rename help-.md to help.md 2018-10-28 10:54:01 +00:00
md678685 96adef5269 Update issue templates (#2045)
* Update issue templates

Add new issue templates - I didn't even know GitHub had these now

* Remove duplicate bug template

* Remove duplicate feature template

* Update help-.md

* Update report-a-bug.md

* Update request-a-feature.md

* Delete ISSUE_TEMPLATE.md
2018-10-27 15:42:56 +01:00
md678685 9576ea25a6 Use reflection-based detection for pickup listener in player listener (#2151)
Allows the plugin to start up on Glowstone correctly.

Tested on Spigot 1.12.2, Spigot 1.9.4 and Glowstone 2018.7.0, works correctly on all.
2018-10-27 15:37:29 +01:00
md678685 a7fcafb245 Filter out comment lines when loading items.json 2018-10-27 15:00:04 +01:00
md678685 73bb41d579 Merge branch '1.13-items' into 1.13 2018-10-26 15:59:51 +01:00
md678685 0a90d76493 Remove item IDs from Worth 2018-10-15 13:56:36 +01:00
md678685 010981d3c8 Remove ID-based charges in /repair 2018-10-15 13:51:04 +01:00
md678685 3353061e76 Remove ID-based permission checks in /more 2018-10-15 13:49:16 +01:00
md678685 79bc34047b Allow multiple item names in /clearinventory
Allow a comma-separated list of item names in /clearinventory.
2018-10-15 13:46:12 +01:00
md678685 60c90408e7 Remove ID-based permission checks in /give and /item 2018-10-15 13:16:10 +01:00
md678685 1218c3e226 Merge branch '1.13' into 1.13-items 2018-10-13 18:23:58 +01:00
md678685 a05fc9d08e Remove duplicated OfflinePlayer method 2018-10-13 17:14:10 +01:00
md678685 6906ef2154 Merge branch '1.13' into 1.13-items 2018-10-13 16:59:57 +01:00
md678685 7d25e84ebc Merge branch '2.x' into 1.13 2018-10-13 16:59:44 +01:00
md678685 121d935315 Implement missing FakeServer methods 2018-10-13 16:55:49 +01:00
md678685 2f66a866d8 Implement missing FakeWorld and OfflinePlayer methods 2018-10-13 16:55:42 +01:00
md678685 0e088c17a8 Remove IdProvider dependency 2018-10-13 16:45:20 +01:00
md678685 4cd8a6636b Log invalid JSON entries 2018-10-13 16:44:50 +01:00
md678685 5c7fc763fc Formatting 2018-10-13 16:44:24 +01:00
md678685 1e381a59be Throw meaningful exception when item not found 2018-10-13 16:32:21 +01:00
md678685 85111f25cb Use ItemData#equals when finding item name
Avoids accidentally causing an NPE while comparing potion data.
2018-10-13 16:09:45 +01:00
md678685 f78887a02e Remove item IDs from /itemdb 2018-10-13 15:59:25 +01:00
md678685 feba535637 Actually assign the ManagedFile to file 2018-10-13 15:38:45 +01:00
md678685 3262143c73 Implement missing FakeServer methods 2018-10-13 15:30:27 +01:00
md678685 18feb7967a Implement missing FakeWorld and OfflinePlayer methods 2018-10-13 15:26:58 +01:00
md678685 e9b1511117 Remove item ID support in Worth 2018-10-12 17:26:41 +01:00
md678685 177e5f62f7 Remove providers; move JSON support into ItemDb 2018-10-12 17:26:22 +01:00
md678685 f3f4395da7 Reset BuildTools work directory on Travis 2018-10-09 20:32:40 +01:00
md678685 442e46b012 Return to root after BuildTools on Travis 2018-10-09 20:25:36 +01:00
md678685 37d699d05b mkdir -p in Travis 2018-10-09 19:54:31 +01:00
md678685 77ed1e1d4a Ensure Travis runs BuildTools before mvn install 2018-10-09 19:52:42 +01:00
md678685 50e4cd67b5 Fix typo in Travis config 2018-10-09 19:47:57 +01:00
md678685 83a90eb553 Update .travis.yml 2018-10-09 19:45:28 +01:00
md678685 c29599d39a Create .travis.yml 2018-10-09 19:34:07 +01:00
mathias a9fe842242 Use chat instead of dispatchCommand 2018-09-18 16:39:58 +03:00
md678685 692e0adde4 Use MONSTER_EGG in SpawnEggRefl 2018-09-09 16:37:02 +01:00
md678685 cdba518bae Revert "Implement 1.13 item support (#2153)" 2018-09-09 16:35:20 +01:00
md678685 b70b67fa1f Remove unnecessary CraftBukkit dependency 2018-09-09 16:34:15 +01:00
md678685 ff0ca9bc7b Remove unnecessary CraftBukkit dependency 2018-09-05 19:20:18 +01:00
md678685 320bc25d94 Implement 1.13 item support (#2153)
Uses two distinct providers to support items on 1.13 while falling back to `items.csv` for previous versions of Minecraft.
2018-09-05 14:23:16 +01:00
md678685 425e955b5d Update items.json
Add some more aliases to the file
2018-09-05 14:19:09 +01:00
pop4959 33ae9a2597 Fix TropicalFish spawning (#2159)
The name can't have a space in it or it won't be matched by any commands.
2018-09-05 13:26:33 +01:00
pop4959 19913d3612 Implement abstract method Entity::getFacing in OfflinePlayer (#2157) @pop4959
Allows EssentialsX to compile against the latest Spigot version.

Reference: [https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/8ab814cd5c415258aa0ab7617051ee4ea9f4e7bd](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/8ab814cd5c415258aa0ab7617051ee4ea9f4e7bd)
2018-09-05 11:00:27 +01:00
pop4959 0432546746 use less dependencies 2018-09-04 16:53:01 -07:00
pop4959 3395bab928 Sort /near by nearest player. 2018-09-02 23:09:22 -07:00
pop4959 a3eb58724f Add a way to use unsafe nicknames (#2152) @pop4959
Pretty much what the title says. Closes #1630.

This is a fun little feature that I'm sure many people have always wanted. I can understand that the original authors of Essentials were probably concerned about users entering names that cannot display correctly in the chat, and that is understandable.

I have added a new permission "essentials.nick.allowunsafe", which must be given to anyone who is allowed to use characters outside of the alphanumeric set. The name of the permission is inspired from "essentials.enchantments.allowunsafe", which allows unsafe enchantment levels to be applied to items without guaranteed behaviour. Similarly, the permission "essentials.nick.allowunsafe" allows unsafe characters to be entered for the user's nickname without making any guarantee that those characters will show up in chat correctly.
2018-09-02 12:14:26 +01:00
md678685 0afa00779c Add some comments to LegacyItemDbProvider 2018-09-01 19:31:32 +01:00
md678685 17d5545804 Update items.json
Fix incorrect type for Uncraftable Potions
2018-09-01 16:46:55 +01:00
md678685 cd70662f01 Update items.json
Fixes some potions spawning incorrectly where the vanilla name didn't match the Bukkit enum name
2018-09-01 16:27:28 +01:00
md678685 a89c97409b Use potion data when looking up items 2018-09-01 15:48:14 +01:00
md678685 102cb6d949 Merge branch '1.13' into 1.13-items 2018-09-01 10:46:27 +01:00
md678685 6c9c9ad42a Use enum methods throughout plugin for cross-version enum lookups 2018-09-01 10:35:08 +01:00
md678685 acbc96fd55 Add enum utility helpers for Statistic and Material 2018-09-01 10:34:11 +01:00
md678685 ca721c1acb Add V1_13_R2 to ReflUtil 2018-08-27 21:29:30 +01:00
md678685 3bf669c42a ItemDbProvider#resolve returns ItemData
More useful than just returning the Material.
2018-08-27 21:21:06 +01:00
md678685 cdc5f75fcb Remove unnecessary equals method on abstract ItemData 2018-08-27 21:19:36 +01:00
md678685 d74f19970b Strip out legacy ItemDb code, pt 1928371236123897 2018-08-27 21:19:15 +01:00
md678685 2ddde37771 Improve FlatItemData#equals 2018-08-27 21:02:27 +01:00
md678685 c1c422e03d Update items.json 2018-08-27 21:00:57 +01:00
md678685 7608b7d658 Merge branch '1.13' into 1.13-items 2018-08-27 20:01:48 +01:00
md678685 d1d5ae814f Merge branch '2.x' into 1.13 2018-08-27 20:01:01 +01:00
md678685 452fa61717 Change tryProvider test values 2018-08-27 19:58:19 +01:00
md678685 825f697fd2 Update items.json 2018-08-27 19:30:05 +01:00
md678685 4ea71ae88e Implement missing methods in FakeWorld 2018-08-27 14:10:06 +01:00
md678685 bdb32f5878 Bump Bukkit version to 1.13.1 2018-08-27 13:10:15 +01:00
md678685 e3c726b8f6 Log total loaded items on reload 2018-08-27 13:06:27 +01:00
md678685 96c6c7b1ca Add per-provider implementations of ItemData 2018-08-27 11:23:47 +01:00
md678685 634d62f9ef Fix typo in /kickall 2018-08-27 10:30:29 +01:00
md678685 2806156cf4 Add "allow-world-in-broadcastworld" option
Allows players to send broadcasts to a specified world by running `/broadcastworld [world] <message>` if enabled.

This is disabled by default in old configs to avoid confusion between updates.
2018-08-27 10:26:54 +01:00
md678685 e642192461 Kick players in /banip
The four-year-old to-do has finally been done!

Closes #2143.
2018-08-26 22:54:00 +01:00
md678685 959c788f22 Don't kick exempt players when running /kickall 2018-08-26 21:03:17 +01:00
montlikadani cda520589a Revert "Doesn't kick all players if the player has permission (#2145) @montlikadani"
This reverts commit 5c1db129d3.
2018-08-26 20:59:46 +01:00
montlikadani 5c1db129d3 Doesn't kick all players if the player has permission (#2145) @montlikadani
So, if a player has permission (eg, an operator or more), they will not kick them out because of permission.
2018-08-26 20:13:05 +01:00
Leomixer17 c718962426 Update messages_it.properties (#2144) @Leomixer17 2018-08-26 17:07:05 +01:00
Thomas 575a11b645 Updated "createKitSuccess=" (#2133) @DutchUser
* Updated "createKitSuccess="

They have the old one, its now in the "kits.yml" not in "config.yml"

* Update messages_da.properties

* Update messages_de.properties

* Update messages_es.properties

* Update messages_en.properties

* Update messages_et.properties

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess=

* Updated "createKitSuccess=

* Updated "createKitSuccess=

* Updated "createKitSuccess=

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Updated "createKitSuccess="

* Update messages_vi.properties

Going add the other later today, 

* invalidItemFlagMeta
* noJailsDefined
* openingDisposal
* socialSpyMsgFormat
* socialSpyMutedPrefix
* tempbanJoin
* whoisUuid

* Update messages_vi.properties

* Update messages_vi.properties @md678685

I have no idea why this whole file is in `\u` codes

* Update messages.properties @md678685
2018-08-26 16:12:13 +01:00
Xeyame f97c5fc1ff Make /realname configurable (#1952) @Xeyame
Closes #1810.

@md678685: I've added colour codes to the `realName` messages by default, which was not originally part of this PR.
2018-08-26 15:39:37 +01:00
montlikadani 81397d98b8 Added editable messages (#2072) @montlikadani
**If it is accepted then I will add it to the other message files.**
2018-08-26 15:17:07 +01:00
Leomixer17 82b2ff0b3f Update messages_it.properties (#2142) @Leomixer17 2018-08-26 15:13:33 +01:00
md678685 05fcb7b1aa Refactor to allow items to be added after first load 2018-08-25 18:38:50 +01:00
md678685 c79db98978 Add more debug logging to Settings (#2140)
Adds debug logging for `getChatFormat` and `getCommandCooldownEntry`, which makes it much easier to track down issues with group formats in EssentialsX Chat and command cooldowns respectively.
2018-08-25 18:09:08 +01:00
md678685 303aa77901 Add missing import 2018-08-25 16:55:12 +01:00
md678685 65a4ef7ee5 Use items that actually exist in tryProvider 2018-08-25 16:54:50 +01:00
md678685 1be7fbd8a6 Remove hash comment when rebuilding JSON database 2018-08-25 16:54:09 +01:00
Max Roncace 935b5cfe0f Fix unbreakable attribute for kits (#2071) @caseif
This PR fixes the `unbreakable` attribute on kit items. Previously, Essentials was exclusively using an internal Spigot method to set this on `ItemMeta` objects; however, this solution seems to be non-functional on more recent Spigot builds (1.12.2).

I have altered the `MetaItemStack#setUnbreakable` method to use the native Bukkit method, available for [some time now](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/d986a3f), by default. Essentials will still use the old solution as a fallback in case of an older Bukkit version which does not have native support for the attribute.
2018-08-25 11:33:17 +01:00
md678685 bad02729db Allow /eco take to subtract a user's exact balance 2018-08-24 15:42:17 +01:00
md678685 80f7ded687 SPECTATOR mode is safe for teleporting everywhere. (#2049)
Teleporting in spectator mode is as safe as creative mode for every target.
2018-08-24 15:24:26 +01:00
Max Lee f569b89d8f Round down balance when converting to double (#2135) 2018-08-21 23:45:58 +01:00
md678685 fec655a29c Implement ItemDbProviders, pt 7
Implement getStack and resolve for FlatItemDbProvider
2018-08-19 23:12:27 +01:00
md678685 610774b0b9 Remove default getStack implementation 2018-08-19 23:11:30 +01:00
md678685 9487665fae Use Bukkit PotionData instead of our own 2018-08-19 23:10:23 +01:00
md678685 d5b43b7162 Include JSON files in jar at build time 2018-08-19 23:09:02 +01:00
md678685 718d9d9d3a Initialise provider and file during first reload 2018-08-19 21:55:29 +01:00
md678685 3705dbdd2b Add items.json
TODO: should we auto-download from the CI on build?
2018-08-19 21:43:53 +01:00
md678685 c37d516980 Use MONSTER_EGG in SpawnEggRefl 2018-08-19 21:16:16 +01:00
md678685 b27a6b5b8e Add additional timer marks 2018-08-19 21:11:51 +01:00
md678685 98809fafd7 Strip out legacy ItemDb code, pt 4 2018-08-19 21:10:54 +01:00
md678685 dd9a0de98d Implement ItemDbProviders, pt 6 2018-08-19 20:58:45 +01:00
md678685 de2298cf0a Strip out legacy ItemDb code, pt 3 2018-08-19 20:58:23 +01:00
md678685 56fb8b06cd Add listNames to abstract ItemDbProvider 2018-08-19 20:55:56 +01:00
md678685 3b1eb683e1 Merge branch 'patch-20' into 2.x @montlikadani 2018-08-19 20:17:32 +01:00
md678685 1029305382 Implement ItemDbProviders, pt 5 2018-08-19 19:23:20 +01:00
md678685 9b39509e88 Misc changes 2018-08-19 18:30:44 +01:00
md678685 9da58dde5c Strip out legacy ItemDb code, pt 2 2018-08-19 18:04:13 +01:00
md678685 e2507d2ff1 Implement ItemDbProviders, pt 4 2018-08-19 18:03:53 +01:00
md678685 b867f121c9 Implement ItemDbProviders, pt 3 2018-08-19 17:49:34 +01:00
montlikadani 3c6a869336 Fix iron armor bug (#2054) 2018-08-19 16:57:14 +01:00
RikoDEV f357e76980 Small corrections in the Polish translation (#2103) 2018-08-19 16:56:16 +01:00
gb2233 946a1fbb7c Fixed unicode characters in HU locale (#2130) 2018-08-19 16:55:14 +01:00
Oliver Ni 37acdc18f2 Fix Easter egg config typo (#2124) @oliver-ni
Left clicking mobs with a milk bucket turns them into a baby, not right clicking.
2018-08-16 20:24:53 +01:00
Ali Moghnieh 4dc1d2c50e Merge branch '2.x' into 1.13 2018-08-16 17:47:37 +01:00
Aerodog ed72d117a5 Add {ONLINE} variable to custom join message (#2043) 2018-08-16 17:42:14 +01:00
md678685 a302913130 Clean up unused files 2018-08-15 20:08:22 +01:00
md678685 659f1a271a Merge branch '1.13' into 1.13-items 2018-08-15 19:51:35 +01:00
md678685 3fb4b7958d Strip out legacy ItemDb code, pt 1 2018-08-15 19:50:15 +01:00
md678685 3ef0f20b0d Add tipped arrows support on 1.9/1.10
On a side note, need to investigate why the potion provider is only needed on 1.10 and below - I don't remember what changed in 1.11?
2018-08-15 19:42:12 +01:00
md678685 340baa9703 Add IEssentials#getItemDbProvider method 2018-08-15 19:40:35 +01:00
md678685 0e9232ba81 Remove breaking import 2018-08-15 19:40:08 +01:00
md678685 299afdc6a1 Add V1_13_R1 to ReflUtil 2018-08-15 18:05:44 +01:00
md678685 04feed8524 Add 1.13+ spawn egg provider
Not sure how necessary this is, but I've done it anyway
2018-08-15 17:46:55 +01:00
md678685 773979cb37 Provide ItemDb provider with other providers
Provide providers to the provider that needs the providers. Provider provider provider provide provider.
2018-08-15 16:56:46 +01:00
md678685 c27d05fd4b Fix dependency on IdProvider 2018-08-15 16:40:01 +01:00
md678685 52d814f2cc Properly fix inaccurate playtime measurement
https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/b848d8ce633871b52115247b089029749c02f579
2018-08-15 15:26:11 +01:00
md678685 5009b3b545 Revert "Fix playtime calculation"
This reverts commit 4e165d375c.
2018-08-15 15:15:30 +01:00
md678685 4e165d375c Fix playtime calculation 2018-08-14 19:29:28 +01:00
md678685 306f7a7872 Merge pull request #2119 from lagnat/1.13
Add missing methods for OfflinePlayer, FakeWorld, and FakeServer.
2018-08-14 19:20:21 +01:00
md678685 6c11569ac9 Merge branch '2.x' into 1.13 2018-08-14 18:58:06 +01:00
md678685 4be28ba193 Implement ItemDbProviders, pt 2 2018-08-14 18:57:47 +01:00
Steve Green a1e98f898b Add missing methods for OfflinePlayer, FakeWorld, and FakeServer. 2018-08-14 08:35:33 -04:00
md678685 c5376d3088 Implement ItemDbProviders, pt 1 2018-08-10 22:07:02 +01:00
md678685 3e1857b966 Add module for FlattenedProvider 2018-08-08 15:42:29 +01:00
md678685 b8a8232bc3 Wrap all constructScalar calls with reflection
Allows configs to function with both SnakeYAML 1.19 and 1.21.
2018-08-06 18:19:30 +01:00
md678685 504a7aef0f Add 1.13 mobs 2018-08-06 17:09:50 +01:00
md678685 1ddb1822ef Merge branch '2.x' into 1.13 2018-08-05 23:02:11 +01:00
md678685 d3cd4e356d Add missing OfflinePlayer 1.13 methods 2018-08-05 20:51:39 +01:00
md678685 bef440760a Remove deprecated economy libs and support
None of these economy plugins are supported any more, and removing these allows EssentialsX to be used as a dependency without locally `mvn install`ing the plugin.
2018-08-05 20:51:19 +01:00
Ali Moghnieh 768b92749f update bukkit to 1.13-R0.1-SNAPSHOT.
This commit just fixes compilation errors.
2018-07-29 17:39:32 +01:00
DoNotSpamPls 03b25a0f06 Set target to Java 8 (for 1.13) & update Maven plugins (#1922) @DoNotSpamPls
This is the same PR as the last one (PR #1823), but I messed that one up accidently, sorry for that!
2018-07-17 09:38:01 +01:00
md678685 a44775cafb Prevent users being duplicated in the ignore list
Fixes #2064, as well as alleviating the issue encountered in kangarko/ChatControl-Pro#627 for EssentialsX users.
2018-07-17 07:33:14 +01:00
montlikadani 187c4eb371 Update messages_hu.properties 2018-06-28 18:27:02 +02:00
montlikadani 49201b9945 Update messages_hu.properties 2018-06-28 17:48:27 +02:00
montlikadani 6225dc8ed1 Update messages_hu.properties 2018-06-21 14:39:25 +02:00
Brokkonaut aa622f8d27 SPECTATOR mode is safe for teleporting everywhere. 2018-06-18 23:38:54 +02:00
md678685 849efa9756 Merge branch '2.x' of https://github.com/EssentialsX/Essentials into 2.x-upstream 2018-06-15 19:44:45 +01:00
md678685 8aa764f69f Check whether nick equals "off" before formatting
Fixes #1910.
2018-06-15 19:41:56 +01:00
md678685 de57a8c602 Disable EssProtect emergency mode when Ess loads late (#1954)
Related: EssentialsX/Essentials#1951.
2018-06-15 19:21:18 +01:00
md678685 4873beb100 Allow updating the compass target to be optional (#1937)
If `compass-towards-home-perm` is enabled in the EssentialsX config, then the permission `essentials.home.compass` is checked before changing the player's compass target.

Closes #1918.
2018-06-15 19:20:06 +01:00
md678685 27d9f3725a Wrap constructScalar for SnakeYAML 1.21 (#2040)
In theory, fixes #1974, fixes #1975 and fixes #1976, and also means that
Spigot are free to upgrade SnakeYAML to 1.21 again when ready.
2018-06-15 19:18:55 +01:00
md678685 16b2c3dee3 Reset pending confirmations on login (#2033)
On login, resets any pending confirmations for the user. Fixes #2021,
closes #2023.
2018-06-15 19:09:27 +01:00
BaoKunVN 2ced9469d7 Vietnamese Translation (#1824) @BauKunVN 2018-06-13 21:23:00 +01:00
montlikadani 45c806128a Updated the messages_hu.properties file 2018-05-31 20:23:48 +02:00
md678685 3d60aa1747 Fix build errors (#2018)
Fixes build errors caused by the warp owner PRs (#1961 and #2017)
2018-05-28 12:21:23 -07:00
FlashLight34 967bb44d94 Update IWarps.java (#2017) @FlashLight34
Maybe the compilation fails because that :P
2018-05-27 07:33:37 +01:00
Xeyame 7298393ec9 Add permission to bypass other's msgtoggle (#1955) @Xeyame
* Add permission to bypass other's msgtoggle

Also thanks to MD for helping me with the code :)

* Correct comment

* Remove checking for console in favour of the already existing IUser check

* Fix comments, again

* Re add isIgnoreMsg() check

Accidently removed it, sorry

* Combine 2 checks
2018-05-26 20:43:31 +01:00
FlashLight34 817caf299f setwarp owner uuid in yml file (#1961) @FlashLight34
* Update Warps.java

its not a real change i dont know if user.getuuid() exist or onother possible cmd maybe

* Update Warps.java

* Update Commandsetwarp.java

* Update Warps.java

* Update Warps.java

* Update Commandsetwarp.java

* Update Warps.java

* Update Warps.java

* Update Commandsetwarp.java

* Update Warps.java
2018-05-26 20:42:51 +01:00
montlikadani 2ff29dab80 Update Commanddeljail.java (#2002) @montlikadani
When the user entered a word to delete the jail, deleted it, but removed anything because no jail existed.
2018-05-26 20:40:45 +01:00
Brokkonaut 030eb3375b Block ignite only for PvP, not for PvE (#1967) @Brokkonaut
Players with god mode enabled could not ignite mobs with bows while only igniting players should be blocked.
2018-05-26 20:34:31 +01:00
md678685 3237632eb4 Fix versioning of NMS modules (#1971)
Resolves numerous build errors that emerged in 613e852ffd and for some reason didn't cause a build error on ender.zone, but did everywhere else.

Fixes #1970
2018-05-18 01:23:20 -07:00
Joseph Hirschfeld b29f98c525 [Feature] Add world specific /back dest. perms (#1948) @Ichbinjoe
Adds world specific perms for whether a player may use /back to teleport
back to a given world. Adds logic to default
essentials.back.into.<world> permissions for loaded worlds to true to
maintain backwards compatibility.
2018-04-29 15:49:49 +01:00
Joseph Hirschfeld 70387f73f6 [Feature] Add config optn. to disable jail free tp
Adds the teleport-back-when-freed-from-jail configuration option. When
set to true (default), as with previous versions will teleport the
player which was jailed back to their previous position when freed. When
false, Essentials will not teleport the player anywhere, leaving them
where they are.

Closes #1947
2018-04-03 01:27:09 -04:00
Xeyame 7adb931ea8 Expand /exp command 2018-04-02 14:29:43 +02:00
md678685 b2a5280971 Avoid build version being overridden by Jenkins (#1936) 2018-03-29 14:19:19 -07:00
games647 c7000846cd Replace Reflection with setter implementation 2018-03-21 11:16:27 +01:00
games647 d24fbc9f55 Remove final modifier to fix illegal reflective access warning
Java 9 runtimes report warnings for reflective access on JRE
classes (in this case Field.modifiers). Future versions of Java
may deny the access completely.

Since we access our own code here, we could just remove the final modifier.
With it's current visibility (of private) it's unlikely that it will be
modified from somewhere else except our Settings class.
2018-03-13 16:46:25 +01:00
games647 7e40d13947 Update lombok and remove antrun to fix compiling with JDK9
* Lombok: Older version resulted in NoSuchFieldEx: pid (fixed since 1.16.8)

* JDK9 no longer has a tools.jar because of it's modular system, but ant is
no longer required. It was introduced in 3e9a2377a8
for GroupManager. Now GM is no longer maintained and removed in
    * 5ca02e6596 (calling the build.xml)
    * fa0bbde236 (removing the remaining module)
2018-03-13 16:06:39 +01:00
Taylor 5f7d226158 Merge pull request #17 from delbertina/mutes385test
Sorted messages files with the -f option and other tweaks ...
2018-01-21 17:02:26 -06:00
delbertina 0897ca57ff Removed redundant line in mute time try-catch. 2018-01-20 22:46:55 -06:00
delbertina cfcdb47529 One last tweak. New line at the end of the fr file. 2018-01-18 22:04:35 -06:00
delbertina 76f845f5f4 More tweaks. Newlines and ordering switches. 2018-01-18 22:02:39 -06:00
delbertina c65b7b6462 Fixed error in sorting with number in message name and newlines at end of files. 2018-01-18 21:52:30 -06:00
Trent Hensler ace361af60 Compile against 1.13 preview.
Still a lot of work to do. One thing to note is that I used LEGACY materials in a few spots where I didn't know what the new ones are as I'm not very familiar with the 1.13 update and what it changes.
2018-01-18 17:52:44 -08:00
delbertina 67528b25a8 Sorted messages files with the -f option 2018-01-18 15:18:22 -06:00
CreedTheFreak b096ee9703 Merge remote-tracking branch 'delbertina/mutes385test' into final_mute_reason_issue#385
Merged changes into local branch for pushing up to the pull request of
mute reason.
2018-01-16 17:49:49 -08:00
delbertina 9e2bb0b277 Rebase with sorted messages 2018-01-16 19:27:45 -06:00
CreedTheFreak b8df59ae46 Updated the former pull request to include the specified formatting changes, and small edits to the hasMuteReason and Commandmute dealing with the muteReason. I also included the ability to see the mute reason from the seenOffline method which is identical to the seenOnline code. 2018-01-16 18:21:31 -06:00
delbertina 98f42c6974 Added reason stuff to msg command and deleted reference line in seen command. Oops! 2018-01-16 18:16:34 -06:00
delbertina db19788e21 Added 8 new messages for "...Reason" versions of mute messages and implemented em. 2018-01-16 18:16:33 -06:00
delbertina 67d17472e0 Fixed logic error in hasMuteReason and errors being thrown from seen and whois. 2018-01-16 18:04:22 -06:00
delbertina f68a6eb00d Added space before reason when a muted player tries to talk. 2018-01-16 18:04:22 -06:00
delbertina b5a6df4fe2 Added space when adding reason to string. 2018-01-16 18:04:21 -06:00
delbertina 290379651d Added space when adding reason to string. Dirty :/ 2018-01-16 17:59:14 -06:00
delbertina 6ffbb86169 Changed if else blocks to ternary operators. Not sure if way to avoid weird empty string usage. 2018-01-16 17:54:50 -06:00
delbertina d8b6f87087 Added method hasMuteReason in UserData. 2018-01-16 17:54:50 -06:00
delbertina 7aad95ec08 Changed muteFormat to muteReason.
Removed space at beginning of muteReason.
2018-01-16 17:54:49 -06:00
delbertina 574e1bc1e7 Fixed easy style issues. 2018-01-16 17:48:12 -06:00
CreedTheFreak 081c6f0263 Update plugin.yml mute command usage 2018-01-16 17:48:11 -06:00
delbertina fc590f82a2 Added check to display mute reason when notifying 2018-01-16 17:48:10 -06:00
delbertina 729af4bb4d Added mute format to all msg files 2018-01-16 17:48:09 -06:00
CreedTheFreak c8cb9b3735 fixed some wonky commit thing that happened, thus the following modifications are brought to you by Delbertina. 2018-01-16 17:21:54 -06:00
CreedTheFreak 4f8ea06db1 We have added the ability for the Mute to contain a reason, which is stored for the duration of the mute in the user's data file. Currently we need to add in the mute reason code into some other commands such as /afk and /me and /seen ect. We will also need to fix a problem with the reason when we dont add in a time frame for the mute, which should mute the player indefinatly rather then cancelling the mute and throwing a DataFormat exception. 2018-01-16 17:21:53 -06:00
CreedTheFreak 9378df0ff2 Started work on implementing the mute reason, and decided to write it to the UserData just like the Ban and TempBan reasons 2018-01-16 17:21:52 -06:00
CreedTheFreak 3444c8b0d6 Merge branch 'mute_reason_changes' into final_mute_reason_issue#385
Updating local changes made on mute_reason_changes into the final branch
2017-12-26 17:20:40 -08:00
CreedTheFreak 822315a279 Updated the former pull request to include the specified formatting changes, and small edits to the hasMuteReason and Commandmute dealing with the muteReason. I also included the ability to see the mute reason from the seenOffline method which is identical to the seenOnline code. 2017-12-26 16:09:46 -08:00
CreedTheFreak 732da86710 Merge remote-tracking branch 'magnarisa/final_mute_reason_issue#385' into mute_reason_changes
Updated a clean branch with the changes we have made so far.
2017-12-26 08:23:53 -08:00
CreedTheFreak 5fbc412542 Merge remote-tracking branch 'upstream/2.x' into final_mute_reason_issue#385 2017-12-26 08:16:46 -08:00
CreedTheFreak f0b262cbd5 Merge pull request #15 from delbertina/mutes385
Added 8 new messages for "...Reason" versions of mute messages
2017-12-23 22:13:57 -08:00
delbertina ff37ef3bc5 Added reason stuff to msg command and deleted reference line in seen command. Oops! 2017-12-24 00:03:36 -06:00
CreedTheFreak 68fab2c328 Merge branch 'mutes385' of https://github.com/delbertina/Essentials into final_mute_reason_issue#385
Testing PR Changes
2017-12-23 22:03:01 -08:00
CreedTheFreak f9d81c4302 Merge branch 'mutes385' of https://github.com/delbertina/Essentials into final_mute_reason_issue#385
Testing PR
2017-12-23 21:51:21 -08:00
delbertina 3d33bbc33d Added 8 new messages for "...Reason" versions of mute messages and implemented em. 2017-12-20 00:35:51 -06:00
CreedTheFreak 53c604c1b5 Merge pull request #14 from delbertina/mutes385
Fixed spacing
2017-12-18 18:53:57 -08:00
CreedTheFreak 2975118e5b Merge branch 'mutes385' of https://github.com/delbertina/Essentials into final_mute_reason_issue#385 2017-12-18 18:40:27 -08:00
delbertina e3ee9cb4c7 Fixed logic error in hasMuteReason and errors being thrown from seen and whois. 2017-12-18 20:37:34 -06:00
CreedTheFreak 297a616460 Merge branch 'mutes385' of https://github.com/delbertina/Essentials into final_mute_reason_issue#385 2017-12-16 23:48:27 -08:00
delbertina afe0ff0ca7 Added space before reason when a muted player tries to talk. 2017-12-17 01:46:43 -06:00
CreedTheFreak adf1bc291c Merge branch 'mutes385' of https://github.com/delbertina/Essentials into final_mute_reason_issue#385 2017-12-16 22:27:52 -08:00
delbertina 034ffbd0bc Added space when adding reason to string. 2017-12-17 00:16:06 -06:00
delbertina 127a7bb2ce Merge branch 'mutes385' of https://github.com/delbertina/Essentials into mutes385
Updated local copy
Conflicts:
	Essentials/src/com/earth2me/essentials/commands/Commandafk.java
	Essentials/src/com/earth2me/essentials/commands/Commandmail.java
	Essentials/src/com/earth2me/essentials/commands/Commandme.java
	Essentials/src/com/earth2me/essentials/commands/Commandr.java
	Essentials/src/com/earth2me/essentials/commands/Commandseen.java
	Essentials/src/com/earth2me/essentials/commands/Commandwhois.java
2017-12-17 00:02:52 -06:00
delbertina e8bfac0790 Added space when adding reason to string. Dirty :/ 2017-12-16 23:26:09 -06:00
CreedTheFreak 62d5dd3516 Merge remote-tracking branch 'magnarisa/final_mute_reason_issue#385' into final_mute_reason_issue#385
Updated my local repos for testing purposes
2017-12-16 19:43:56 -08:00
CreedTheFreak bcd66fec39 Merge pull request #12 from delbertina/mutes385
Address requested changes to formatting and logic
2017-12-16 19:40:27 -08:00
Trent Hensler 1a820ad9b7 Initial removal of item IDs.
We do not rely on Bukkit's item ids anymore, though we still support them in commands via a mapping built off of the items.csv.
2017-12-12 22:06:25 -08:00
delbertina 849b329213 Changed if else blocks to ternary operators. Not sure if way to avoid weird empty string usage. 2017-12-02 20:35:44 -06:00
delbertina d555c1b081 Added method hasMuteReason in UserData. 2017-12-02 19:46:46 -06:00
delbertina 43cbab37f0 Changed muteFormat to muteReason.
Removed space at beginning of muteReason.
2017-11-26 01:32:22 -06:00
delbertina 6f7af90488 Fixed easy style issues. 2017-11-26 00:55:05 -06:00
CreedTheFreak fcda6c3b3b Merge pull request #11 from CreedTheFreak/final_mute_reason_issue#385
Update plugin.yml mute command usage
2017-09-17 15:39:01 -07:00
CreedTheFreak 910ef26c79 Update plugin.yml mute command usage 2017-09-17 15:36:06 -07:00
Taylor 1664da55a4 Merge pull request #10 from CreedTheFreak/commit_squashing
Final Implementation and the squasing of many commits
2017-09-17 16:55:14 -05:00
CreedTheFreak f8ea7f5e1f Implemented the ability to add a reason while muting a
player. The form of the mute is /mute [Player] [Time] [Reason] or /mute
[Player] [Reason] or /mute [Player] [Time] or /mute [Player]. These are
the various forms of the mute command and acts exactly like the old
command just with a reason.

The final adjustments to the MuteReason
2017-09-16 22:27:34 -07:00
delbertina b0205b9499 Added check to display mute reason when notifying 2017-09-03 23:02:56 -05:00
Taylor e05796f80e Merge pull request #4 from delbertina/msgs385
Added mute format to all msg files
2017-09-03 22:10:19 -05:00
delbertina a70fa78267 Added mute format to all msg files 2017-09-03 22:03:17 -05:00
CreedTheFreak e20693de60 Merge pull request #3 from CreedTheFreak/update_branch
Modifications Brought To you by Delbertina
2017-09-03 19:54:20 -07:00
CreedTheFreak f10a766442 fixed some wonky commit thing that happened, thus the following modifications are brought to you by Delbertina. 2017-09-03 19:49:57 -07:00
CreedTheFreak 86315fed8d Merge pull request #1 from CreedTheFreak/mute/jail_reason_issue#385
Mute reason issue#385
2017-09-03 14:46:40 -07:00
CreedTheFreak 4ff9fe8666 We have added the ability for the Mute to contain a reason, which is stored for the duration of the mute in the user's data file. Currently we need to add in the mute reason code into some other commands such as /afk and /me and /seen ect. We will also need to fix a problem with the reason when we dont add in a time frame for the mute, which should mute the player indefinatly rather then cancelling the mute and throwing a DataFormat exception. 2017-09-03 14:41:32 -07:00
CreedTheFreak 3512c4c8e6 Started work on implementing the mute reason, and decided to write it to the UserData just like the Ban and TempBan reasons 2017-09-02 20:04:25 -07:00
544 changed files with 73590 additions and 26997 deletions

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!-- based on https://github.com/KyoriPowered/adventure/blob/master/.checkstyle/checkstyle.xml -->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, properties, xml"/>
<property name="severity" value="error"/>
<!-- https://checkstyle.org/config_filefilters.html#BeforeExecutionExclusionFileFilter -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#FileTabCharacter -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<!-- https://checkstyle.org/config_misc.html#NewlineAtEndOfFile -->
<module name="NewlineAtEndOfFile"/>
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
<property name="file" value="${checkstyle.suppressions.file}"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressWithPlainTextCommentFilter -->
<module name="SuppressWithPlainTextCommentFilter"/>
<module name="TreeWalker">
<!-- https://checkstyle.org/config_misc.html#ArrayTypeStyle -->
<module name="ArrayTypeStyle"/>
<!-- https://checkstyle.org/config_imports.html#AvoidStarImport -->
<module name="AvoidStarImport"/>
<!-- https://checkstyle.org/config_misc.html#AvoidEscapedUnicodeCharacters -->
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowByTailComment" value="true"/>
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
<property name="severity" value="info"/>
</module>
<!-- https://checkstyle.org/config_misc.html#CommentsIndentation -->
<module name="CommentsIndentation"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForInitializerPad -->
<module name="EmptyForInitializerPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForIteratorPad -->
<module name="EmptyForIteratorPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyLineSeparator -->
<module name="EmptyLineSeparator">
<property name="allowMultipleEmptyLines" value="false"/>
<property name="allowMultipleEmptyLinesInsideClassMembers" value="false"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
<property name="tokens"
value="CLASS_DEF, CTOR_DEF, ENUM_DEF, IMPORT, INSTANCE_INIT, INTERFACE_DEF, METHOD_DEF, STATIC_IMPORT, STATIC_INIT, VARIABLE_DEF"/> <!-- remove PACKAGE_DEF, temporarily remove COMPACT_CTOR_DEF, RECORD_DEF -->
</module>
<!-- https://checkstyle.org/config_coding.html#FallThrough -->
<module name="FallThrough">
<property name="checkLastCaseGroup" value="true"/>
</module>
<!-- https://checkstyle.org/config_design.html#FinalClass -->
<module name="FinalClass"/>
<!-- https://checkstyle.org/config_coding.html#FinalLocalVariable -->
<module name="FinalLocalVariable"/>
<!-- https://checkstyle.org/config_whitespace.html#GenericWhitespace -->
<module name="GenericWhitespace"/>
<!-- https://checkstyle.org/config_design.html#HideUtilityClassConstructor -->
<module name="HideUtilityClassConstructor"/>
<!-- https://checkstyle.org/config_imports.html#IllegalImport -->
<module name="IllegalImport">
<property name="illegalPkgs" value="sun, jdk, com.sun"/>
</module>
<!-- https://checkstyle.org/config_coding.html#IllegalTokenText -->
<module name="IllegalTokenText">
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
<property name="tokens" value="CHAR_LITERAL, STRING_LITERAL"/>
</module>
<!-- https://checkstyle.org/config_misc.html#Indentation -->
<module name="Indentation"/>
<!-- https://checkstyle.org/config_blocks.html#LeftCurly -->
<module name="LeftCurly"/>
<!-- https://checkstyle.org/config_naming.html#MethodName -->
<module name="MethodName">
<property name="format" value="^[_]?[a-z][a-zA-Z0-9]*$"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#MethodParamPad -->
<module name="MethodParamPad"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocMethod -->
<module name="MissingJavadocMethod">
<property name="allowMissingPropertyJavadoc" value="true"/>
<property name="tokens" value="METHOD_DEF, ANNOTATION_FIELD_DEF"/> <!-- remove CTOR_DEF, COMPACT_CTOR_DEF -->
</module>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocType -->
<module name="MissingJavadocType"/>
<!-- https://checkstyle.org/config_coding.html#NoFinalizer -->
<module name="NoFinalizer"/>
<!-- https://checkstyle.org/config_whitespace.html#NoLineWrap -->
<module name="NoLineWrap"/>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceAfter -->
<module name="NoWhitespaceAfter">
<property name="allowLineBreaks" value="false"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceBefore -->
<module name="NoWhitespaceBefore">
<property name="allowLineBreaks" value="true"/>
</module>
<!-- https://checkstyle.org/config_coding.html#OneStatementPerLine -->
<module name="OneStatementPerLine"/>
<!-- https://checkstyle.org/config_misc.html#OuterTypeFilename -->
<module name="OuterTypeFilename"/>
<!-- https://checkstyle.org/config_imports.html#RedundantImport -->
<module name="RedundantImport"/>
<!-- https://checkstyle.org/config_modifier.html#RedundantModifier -->
<module name="RedundantModifier">
<property name="tokens"
value="ANNOTATION_FIELD_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INTERFACE_DEF, VARIABLE_DEF"/> <!-- remove METHOD_DEF and RESOURCE -->
</module>
<!-- https://checkstyle.org/config_coding.html#RequireThis -->
<module name="RequireThis"/>
<!-- https://checkstyle.org/config_blocks.html#RightCurly -->
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INSTANCE_INIT, LITERAL_FOR, LITERAL_WHILE, METHOD_DEF, STATIC_INIT"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="option" value="same"/>
<property name="tokens"
value="LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF, LITERAL_TRY"/> <!-- add LITERAL_DO -->
</module>
<!-- https://checkstyle.org/config_whitespace.html#SingleSpaceSeparator -->
<module name="SingleSpaceSeparator">
<property name="validateComments" value="true"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#TypecastParenPad -->
<module name="TypecastParenPad"/>
<!-- https://checkstyle.org/config_coding.html#UnnecessaryParentheses -->
<module name="UnnecessaryParentheses"/>
<!-- https://checkstyle.org/config_imports.html#UnusedImports -->
<module name="UnusedImports"/>
</module>
</module>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "http://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files=".*[\\/]test[\\/]java[\\/].*" checks="RequireExplicitVisibilityModifier"/>
<!-- TODO: don't suppress I-prefixed API interfaces under com.earth2me.essentials -->
<suppress files="(com[\\/]earth2me[\\/]essentials[\\/]|net[\\/]ess3[\\/])(?:[^\\/]+$|(?!api)[^\\/]+[\\/])" checks="MissingJavadoc(Method|Type)"/>
</suppressions>
+13
View File
@@ -0,0 +1,13 @@
# Currently used
patreon: EssentialsX
ko_fi: essentialsx
# Currently not used
#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
#open_collective: # Replace with a single Open Collective username
#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
#liberapay: # Replace with a single Liberapay username
#issuehunt: # Replace with a single IssueHunt username
#otechie: # Replace with a single Otechie username
#custom: # Replace with a single custom sponsorship URL
-41
View File
@@ -1,41 +0,0 @@
<!--
Don't put anything inside this block, as it won't be included in the issue.
If you have a question about using EssentialsX, it may be more helpful to ask
in our Discord server: https://discord.gg/F7gexAQ
If you have a feature suggestion for EssentialsX, please delete the template.
Otherwise, if you are reporting a bug, read on:
1. Fill out the template, running the commands either in the console or
as a player. Don't simply put "latest" or we will ignore it.
2. When linking files, do not attach them to the post! Paste them on
https://gist.github.com/, then paste a link to them in the relevant parts
of the template. Avoid using Hastebin or Pastebin, as files are deleted
after a period of time.
3. If you are reporting an issue with lag, please include a timings report.
4. If you are reporting an issue with messages or in-game behaviour, please
include screenshots detailing the problem.
5. Include a description and any other details that may be helpful under the
Details section.
6. Delete this line and all above lines before posting your issue! -->
### Information
Full output of `/ess version`:
Server log (upload `logs/latest.log` to [Gist](https://gist.github.com/)):
EssentialsX config (upload `plugins/Essentials/config.yml` to [Gist](https://gist.github.com/)):
### Details
Describe your issue here.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: MOSS Discord Server
url: https://discord.gg/casfFyh
about: Need help with using EssentialsX? Join the MOSS Discord server for help.
+86
View File
@@ -0,0 +1,86 @@
---
name: Help!
about: Encountered a problem with EssentialsX? Not sure how to fix it?
labels: 'type: question'
---
<!-- EssentialsX help request guide
NOTE: Failure to fill out this template properly may result in your issue being
delayed or ignored.
Don't type between any arrows in the template, as this text will be hidden.
This includes this header block and any other explanatory text blocks.
Want faster support? Come join our Discord server to get help from both
developers and community members: https://discord.gg/F7gexAQ
If you're happy to wait (or you were sent here from Discord), read on:
1. Check the Common Issues page.
Read through the wiki page to see if you've encountered a regular issue:
https://essentialsx.net/wiki/Common-Issues.html
2. Fill out the template.
Run the commands in the console. Don't just put "latest" as a version, or
we will ignore it. This will help us understand what problem you've
encountered and help us find a solution.
3. When linking logs or config 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. Do not use Hastebin
or Pastebin, as this can cause issues when trying to solve issues in the
future.
**DO NOT drag logs into this text box!**
4. If you are encountering a performance issue, please include a link to a
Timings and/or profiler report.
-->
### Information
**Full output of `/ess version`:**
<!--
Run /ess version in the console, then paste the full output of the command
between the ```s.
-->
```
```
**Server startup log:**
<!--
Restart your server and upload `logs/latest.log` to
https://gist.github.com/. You may redact sensitive data (such as IP
addresses), but you should make it clear what data was removed. Once
uploaded, paste the link below this block.
-->
**EssentialsX config:**
<!--
Upload `plugins/Essentials/config.yml` (and other config files if relevant)
to https://gist.github.com/ then paste the link below this block.
-->
### Help request
**Problem:**
<!-- What problem did you encounter? Type below this line. -->
**What I have tried:**
<!-- What have you tried so far? Type below this line. -->
**Console stack trace:**
<!--
If you are reporting an error in the console, paste it between the ```s.
-->
```
```
**Screenshots:**
<!-- If relevant, include any screenshots or a video below this line. -->
+83
View File
@@ -0,0 +1,83 @@
---
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!".
labels: 'bug: unconfirmed'
---
<!-- EssentialsX bug reporting guide
NOTE: Failure to fill out this template properly may result in your issue being
delayed or ignored.
Don't type between any arrows in the template, as this text will be hidden.
This includes this header block and any other explanatory text blocks.
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 text 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.
-->
### Information
**Full output of `/ess version`:**
<!--
Run /ess version in the console, then paste the full output of the command
between the ```s.
-->
```
```
**Server startup log:**
<!--
Restart your server and upload `logs/latest.log` to
https://gist.github.com/. You may redact sensitive data (such as IP
addresses), but you should make it clear what data was removed. Once
uploaded, paste the link below this block.
-->
**EssentialsX config:**
<!--
Upload `plugins/Essentials/config.yml` (and other config files if relevant)
to https://gist.github.com/ then paste the link below this block.
-->
### Details
**Description:**
<!-- What is the bug? Type a brief summary below this line. -->
**Steps to reproduce:**
<!-- How did you cause it? Describe what you did to cause the bug below. -->
**Expected behavior:**
<!-- What did you expect to happen? Type below this line. -->
**Console stack trace:**
<!--
If you are encountering an error in the console, paste it between the ```s.
-->
```
```
**Screenshots:**
<!-- If necessary, include screenshots or a video below this line. -->
@@ -0,0 +1,52 @@
---
name: Request a feature
about: Suggest a feature you want to see in EssentialsX!
labels: 'type: enhancement'
---
<!-- EssentialsX feature request guide
NOTE: Failure to fill out this template properly may result in your issue being
delayed or ignored.
Don't type between any arrows in the template, as this text will be hidden.
This includes this header block and any other explanatory text blocks.
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 changelogs to see if the feature was recently added:
https://github.com/EssentialsX/Essentials/releases
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.
-->
### Feature request
**Feature description:**
<!-- What feature are you suggesting? Type below this line. -->
**How the feature is useful:**
<!--
How is the feature useful to players, server owners and/or developers?
Type below this block.
-->
+82
View File
@@ -0,0 +1,82 @@
---
name: Bug fix
about: Use this if your PR fixes a bug in EssentialsX.
labels: 'type: bugfix'
---
<!-- EssentialsX bug fix submission guide
NOTE: Failure to fill out this template properly may result in your PR being
delayed or ignored without warning.
Don't type between any arrows in the template, as this text will be hidden.
This includes this header block and any other explanatory text blocks.
Want to discuss your PR before submitting it? Join the EssentialsX Development
server: https://discord.gg/CUN7qVb
By contributing to EssentialsX, you agree to license your code under the
GNU General Public License version 3, which can be found at the link below:
https://github.com/EssentialsX/Essentials/blob/2.x/LICENSE
If you are submitting a bug fix, please follow the following steps:
1. Fill out the template in full.
This includes providing screenshots and a link to the original bug
report. If there isn't an existing bug report, we recommend opening a new
detailed bug report BEFORE opening your PR to fix it, else your PR may be
delayed or rejected without warning.
You can open a new bug report by following this link:
https://github.com/EssentialsX/Essentials/issues/new/choose
2. When linking logs or config 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. Do not use Hastebin
or Pastebin, as this can cause issues with future reviews.
**DO NOT drag logs into this text box!**
3. If you are fixing a performance issue, please include a link to a
Timings and/or profiler report, both before and after your PR.
4. If you are fixing a visual bug, such as in commands, please include
screenshots so that we can more easily review the proposed fix.
(You may drag screenshots directly into this box.)
-->
### Information
<!--
Replace #nnnn with the number of the original issue. If this PR fixes
multiple issues, you should repeat the phrase "fixes #nnnn" for each issue.
-->
This PR fixes #nnnn.
### Details
**Proposed fix:**
<!-- Type a description of your proposed fix below this line. -->
**Environments tested:**
<!--
Below this line, put an "x" inside the box for the environments you have
tested this bug fix on, and if relevant alter the OS and Java version
accordingly. If this feature does not apply to an environment, strike
through the environment using ~~strikethrough~~. If you have tested on
other environments, add a new line with relevant details.
-->
- [ ] [Latest](https://papermc.io/downloads) Paper Version (any OS, any Java 8+ version)
- [ ] CraftBukkit/Spigot/Paper 1.12.2 (any OS, any Java 8+ version)
- [ ] CraftBukkit 1.8.8 (any OS, any Java 8+ version)
**Demonstration:**
<!--
Below this block, include screenshots/log snippets from before and after as
necessary. If you have created or used a test case plugin, please link to a
download of the plugin, source code and exact version used where possible.
-->
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: MOSS Discord Server
url: https://discord.gg/casfFyh
about: Need help with using EssentialsX? Join the MOSS Discord server for help.
- name: EssentialsX Development Discord Server
url: https://discord.gg/CUN7qVb
about: Got questions or want to discuss changes before opening your PR? Join the EssentialsX Development Discord server. (Need help? Join MOSS instead.)
@@ -0,0 +1,82 @@
---
name: Feature addition
about: Use this if your PR adds a new feature to EssentialsX.
labels: 'type: enhancement'
---
<!-- EssentialsX feature submission guide
NOTE: Failure to fill out this template properly may result in your PR being
delayed or ignored without warning.
Don't type between any arrows in the template, as this text will be hidden.
This includes this header block and any other explanatory text blocks.
Want to discuss your PR before submitting it? Join the EssentialsX Development
server: https://discord.gg/CUN7qVb
By contributing to EssentialsX, you agree to license your code under the
GNU General Public License version 3, which can be found at the link below:
https://github.com/EssentialsX/Essentials/blob/2.x/LICENSE
If you are submitting a new feature, please follow the following steps:
1. Fill out the template in full.
This includes providing screenshots and a link to the original feature
request. If there isn't an existing feature request, we strongly
recommend opening a new feature request BEFORE opening your PR to
implement it, as this allows us to review whether we're likely to accept
your feature in advance, and also allows us to discuss possible
implementations for the feature. If there is no associated feature
request, your PR may be delayed or rejected without warning.
You can open a new feature request by following this link:
https://github.com/EssentialsX/Essentials/issues/new/choose
2. If you are fixing a performance issue, please use the "Bug fix" PR template
instead. The "bug fix" template is better suited to performance issues.
3. Include a demonstration.
If you are adding commands, please provide screenshots and/or a video
demonstration of the feature. Similarly, if you are adding a new API,
please include a link to example code that takes advantage of your
proposed API. This will aid us in reviewing PRs and speed up the process
significantly.
-->
### Information
<!--
Replace #nnnn with the number of the original issue. If this PR implements
features from multiple issues, you should repeat the phrase "closes #nnnn"
for each issue.
-->
This PR closes #nnnn.
### Details
**Proposed feature**
<!-- Type a description of your proposed feature below this line. -->
**Environments tested:**
<!--
Below this block, put an "x" inside the box for the environments you have
tested this bug fix on, and if relevant alter the OS and Java version
accordingly. If this feature does not apply to an environment, strike
through the environment using ~~strikethrough~~. If you have tested on
other environments, add a new line with relevant details.
-->
- [ ] [Latest](https://papermc.io/downloads) Paper Version (any OS, any Java 8+ version)
- [ ] CraftBukkit/Spigot/Paper 1.12.2 (any OS, any Java 8+ version)
- [ ] CraftBukkit 1.8.8 (any OS, any Java 8+ version)
**Demonstration:**
<!--
Below this block, include screenshots/code snippets from before and after
as necessary. If you have created or used a test case plugin, please link
to a download of the plugin, source code and exact version used where
possible.
-->
+38
View File
@@ -0,0 +1,38 @@
name: Build EssentialsX
on:
push:
branches:
- 2.x
- mc/*
pull_request:
branches:
- 2.x
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Git repo
uses: actions/checkout@v1
- name: Restore Maven cache
uses: actions/cache@v1
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build with Maven
run: mvn package verify --file pom.xml
- name: Copy artifacts
run: mkdir -p ./out/ && cp -t ./out/ **/target/Essentials*.jar
- uses: actions/upload-artifact@master
with:
name: Plugin jars
path: out/
+22 -52
View File
@@ -1,52 +1,22 @@
.DS_Store
/BuildAll/nbproject/private/
/EssentialsProtect/nbproject/private/
/EssentialsChat/nbproject/private/
/EssentialsGroupBridge/nbproject/private/
/EssentialsGeoIP/nbproject/private/
/EssentialsSpawn/nbproject/private/
/EssentialsXMPP/nbproject/private/
/BuildAll/build/
/EssentialsGroupBridge/dist/
/EssentialsGroupBridge/build/
/EssentialsGeoIP/dist/
/EssentialsGeoIP/build/
/BuildAll/dist/
/EssentialsChat/build/
/EssentialsChat/dist/
/EssentialsSpawn/build/
/EssentialsSpawn/dist/
/EssentialsXMPP/dist/
/EssentialsXMPP/build/
/EssentialsProtect/dist/
/EssentialsProtect/build/
/EssentialsPermissionsCommands/nbproject/private/
/EssentialsPermissionsCommands/build/
/EssentialsPermissionsCommands/dist/
/Essentials/nbproject/private/
/Essentials/dist/
/Essentials/build/
/YamlAnnotations/
/EssentialsUpdate/nbproject/private/
/EssentialsRelease/
/EssentialsUpdate/dist/
/EssentialsUpdate/build/
/WebPush/apikey.php
/WebPush/nbproject/private
/EssentialsAntiBuild/nbproject/private/
/EssentialsAntiBuild/dist/
/EssentialsAntiBuild/build/
/jars
/out
.idea/
*.iml
*.classpath
*.project
*.settings/
target/
dependency-reduced-pom.xml
/Essentials/config.yml
/Essentials/userdata/testplayer1.yml
/Essentials/usermap.csv
/Essentials/userdata
/EssentialsGroupManager/target/
# Other IDE files
*.classpath
*.project
*.settings/
.idea/*
*.iml
.DS_Store
# Checkstyle-IDEA config
!.idea/checkstyle-idea.xml
# Essentials files
/Essentials/userdata
/Essentials/config.yml
/Essentials/kits.yml
/Essentials/userdata/testplayer1.yml
/Essentials/usermap.csv
# Build files
target/
jars/
out/
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CheckStyle-IDEA">
<option name="configuration">
<map>
<entry key="active-configuration" value="PROJECT_RELATIVE:$PROJECT_DIR$/.checkstyle/checkstyle.xml:EssentialsX" />
<entry key="checkstyle-version" value="8.36.2" />
<entry key="copy-libs" value="true" />
<entry key="location-0" value="BUNDLED:(bundled):Sun Checks" />
<entry key="location-1" value="BUNDLED:(bundled):Google Checks" />
<entry key="location-2" value="PROJECT_RELATIVE:$PROJECT_DIR$/.checkstyle/checkstyle.xml:EssentialsX" />
<entry key="property-2.checkstyle.suppressions.file" value=".checkstyle/suppressions.xml" />
<entry key="scan-before-checkin" value="false" />
<entry key="scanscope" value="JavaOnly" />
<entry key="suppress-errors" value="false" />
</map>
</option>
</component>
</project>
+31
View File
@@ -0,0 +1,31 @@
Contributing to EssentialsX
===========================
Want to help improve EssentialsX? There are several ways you can support and contribute to the project.
If you'd like to make a financial contribution to the project, you can join our [Patreon](https://www.patreon.com/essentialsx/),
or to make a one-off donation you can visit our [Ko-fi page](https://ko-fi.com/essentialsx). If you can't make a
donation, don't worry! There are lots of other ways to contribute:
* Do you run a server? Take a look at our ["help wanted"](https://github.com/EssentialsX/Essentials/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22help+wanted%22)
and ["bug: unconfirmed"](https://github.com/EssentialsX/Essentials/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22bug%3A+unconfirmed%22)
issues, where you can find issues that need extra testing and investigation.
* Do you speak multiple languages? If so, we always welcome contributions to our [Crowdin project](https://crowdin.com/project/essentialsx-official).
* Do you enjoy helping others? If so, why not contribute to the [EssentialsX documentation](https://github.com/EssentialsX/wiki)?
You can also join the [MOSS Discord community](https://discord.gg/casfFyh) and provide direct community support to
other EssentialsX users.
* If you're a developer, you could look through our ["open to PR"](https://github.com/EssentialsX/Essentials/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22status%3A+open+to+PR%22)
issues. We're always happy to receive bug fixes and feature additions as pull requests.
Submitting a PR
---------------
EssentialsX has extensive templates for PRs that detail how to submit your PR. To find out more, see the PR templates for:
* [Bug fixes](https://github.com/EssentialsX/Essentials/blob/2.x/.github/PULL_REQUEST_TEMPLATE/bug-fix.md)
* [New features](https://github.com/EssentialsX/Essentials/blob/2.x/.github/PULL_REQUEST_TEMPLATE/new-feature.md)
Want to discuss a feature before opening a PR? Join the [EssentialsX Development Discord server](https://discord.gg/CUN7qVb). Note that this server is **not for end-users** - if you need support with EssentialsX, you should join [MOSS](https://discord.gg/casfFyh) instead.
By contributing to EssentialsX, you agree to license your code under the [GNU General Public License version 3](https://github.com/EssentialsX/Essentials/blob/2.x/LICENSE).
-39
View File
@@ -1,39 +0,0 @@
# EssentialsX new Kit configuration.
# If you don't have any kits defined in this file, the plugin will try to copy them from the config.yml
# Note: All items MUST be followed by a quantity!
# All kit names should be lower case, and will be treated as lower in permissions/costs.
# Syntax: - itemID[:DataValue/Durability] Amount [Enchantment:Level].. [itemmeta:value]...
# For Item Meta information visit http://wiki.ess3.net/wiki/Item_Meta
# 'delay' refers to the cooldown between how often you can use each kit, measured in seconds.
# Set delay to -1 for a one time kit.
# For more information, visit http://wiki.ess3.net/wiki/Kits
kits:
tools:
delay: 10
items:
- 272 1
- 273 1
- 274 1
- 275 1
dtools:
delay: 600
items:
- 278 1 efficiency:1 durability:1 fortune:1 name:&4Gigadrill lore:The_drill_that_&npierces|the_heavens
- 277 1 digspeed:3 name:Dwarf lore:Diggy|Diggy|Hole
- 298 1 color:255,255,255 name:Top_Hat lore:Good_day,_Good_day
- 279:780 1
notch:
delay: 6000
items:
- 397:3 1 player:Notch
color:
delay: 6000
items:
- 387 1 title:&4Book_&9o_&6Colors author:KHobbits lore:Ingame_color_codes book:Colors
firework:
delay: 6000
items:
- 401 1 name:Angry_Creeper color:red fade:green type:creeper power:1
- 401 1 name:Starry_Night color:yellow,orange fade:blue type:star effect:trail,twinkle power:1
- 401 2 name:Solar_Wind color:yellow,orange fade:red shape:large effect:twinkle color:yellow,orange fade:red shape:ball effect:trail color:red,purple fade:pink shape:star effect:trail power:1
+50 -76
View File
@@ -6,25 +6,18 @@
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.15.0</version>
<version>2.18.2</version>
</parent>
<artifactId>EssentialsX</artifactId>
<licenses>
<license>
<name>GPLv3</name>
<url>http://www.gnu.org/copyleft/gpl.html</url>
</license>
</licenses>
<build>
<finalName>EssentialsX-${full.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.8.0</version>
<configuration>
<showDeprecation>false</showDeprecation>
</configuration>
@@ -32,7 +25,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
@@ -41,104 +34,85 @@
</goals>
</execution>
</executions>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>com.earth2me.essentials.paperlib</shadedPattern>
</relocation>
</relocations>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>BOSEconomy</groupId>
<artifactId>BOSEconomy</artifactId>
<version>v0.7.8.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/BOSEconomy.jar</systemPath>
</dependency>
<dependency>
<groupId>iConomy</groupId>
<artifactId>iConomy5</artifactId>
<version>5</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/iCo5.jar</systemPath>
</dependency>
<dependency>
<groupId>iConomy</groupId>
<artifactId>iConomy6</artifactId>
<version>6</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/iCo6.jar</systemPath>
</dependency>
<dependency>
<groupId>MultiCurrency</groupId>
<artifactId>MultiCurrency</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/MultiCurrency.jar</systemPath>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>1.5.6</version>
<groupId>com.github.milkbowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>NMSProvider</artifactId>
<version>2.0.1</version>
<groupId>net.luckperms</groupId>
<artifactId>api</artifactId>
<version>5.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.6-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>UpdatedMetaProvider</artifactId>
<version>2.0.1</version>
<artifactId>BaseProviders</artifactId>
<version>2.18.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8_R1Provider</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
<artifactId>NMSReflectionProvider</artifactId>
<version>2.18.2</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8_R2Provider</artifactId>
<version>2.0.1</version>
<artifactId>PaperProvider</artifactId>
<version>2.18.2</version>
<exclusions>
<exclusion>
<groupId>com.destroystokyo.paper</groupId>
<artifactId>paper-api</artifactId>
</exclusion>
</exclusions>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8Provider</artifactId>
<version>2.18.2</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>LegacyProvider</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>ReflectionProvider</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
</repositories>
</project>
+3 -3
View File
@@ -13,6 +13,6 @@ Minecraft colors:
&8 &&8 &9 &&9 &a &&a &b &&b
&c &&c &d &&d &e &&e &f &&f
&0
&&k &kMagic&r &&l &lBold
&&m &mStrike&r &&n &nUline
&&o &oItalic&r &&r &rReset
&&k &kMagic&r &&l &lBold&r
&&m &mStrike&r &&n &nUline&r
&&o &oItalic&r &&r &rReset
@@ -6,11 +6,15 @@ import org.bukkit.command.PluginCommand;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.plugin.Plugin;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AlternativeCommandsHandler {
private static final Logger LOGGER = Logger.getLogger("Essentials");
private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<>();
@@ -19,7 +23,7 @@ public class AlternativeCommandsHandler {
public AlternativeCommandsHandler(final IEssentials ess) {
this.ess = ess;
for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) {
for (final Plugin plugin : ess.getServer().getPluginManager().getPlugins()) {
if (plugin.isEnabled()) {
addPlugin(plugin);
}
@@ -33,7 +37,7 @@ public class AlternativeCommandsHandler {
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
for (Command command : commands) {
for (final Command command : commands) {
final PluginCommand pc = (PluginCommand) command;
final List<String> labels = new ArrayList<>(pc.getAliases());
labels.add(pc.getName());
@@ -45,16 +49,13 @@ public class AlternativeCommandsHandler {
if (reg == null || !reg.getPlugin().equals(plugin)) {
continue;
}
for (String label : labels) {
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null) {
plugincommands = new ArrayList<>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
for (final String label : labels) {
final List<PluginCommand> plugincommands = altcommands.computeIfAbsent(label.toLowerCase(Locale.ENGLISH), k -> new ArrayList<>());
boolean found = false;
for (PluginCommand pc2 : plugincommands) {
for (final PluginCommand pc2 : plugincommands) {
if (pc2.getPlugin().equals(plugin)) {
found = true;
break;
}
}
if (!found) {
@@ -68,13 +69,7 @@ public class AlternativeCommandsHandler {
final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String, List<PluginCommand>> entry = iterator.next();
final Iterator<PluginCommand> pcIterator = entry.getValue().iterator();
while (pcIterator.hasNext()) {
final PluginCommand pc = pcIterator.next();
if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) {
pcIterator.remove();
}
}
entry.getValue().removeIf(pc -> pc.getPlugin() == null || pc.getPlugin().equals(plugin));
if (entry.getValue().isEmpty()) {
iterator.remove();
}
@@ -90,7 +85,7 @@ public class AlternativeCommandsHandler {
return commands.get(0);
}
// return the first command that is not an alias
for (PluginCommand command : commands) {
for (final PluginCommand command : commands) {
if (command.getName().equalsIgnoreCase(label)) {
return command;
}
@@ -0,0 +1,455 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IAsyncTeleport;
import com.earth2me.essentials.commands.WarpNotFoundException;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.api.IUser;
import net.ess3.api.InvalidWorldException;
import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static com.earth2me.essentials.I18n.tl;
public class AsyncTeleport implements IAsyncTeleport {
private final IUser teleportOwner;
private final IEssentials ess;
private AsyncTimedTeleport timedTeleport;
private TeleportType tpType;
public AsyncTeleport(final IUser user, final IEssentials ess) {
this.teleportOwner = user;
this.ess = ess;
tpType = TeleportType.NORMAL;
}
public void cooldown(final boolean check) throws Throwable {
final CompletableFuture<Boolean> exceptionFuture = new CompletableFuture<>();
if (cooldown(check, exceptionFuture)) {
try {
exceptionFuture.get();
} catch (final ExecutionException e) {
throw e.getCause();
}
}
}
public boolean cooldown(final boolean check, final CompletableFuture<Boolean> future) {
final Calendar time = new GregorianCalendar();
if (teleportOwner.getLastTeleportTimestamp() > 0) {
// Take the current time, and remove the delay from it.
final double cooldown = ess.getSettings().getTeleportCooldown();
final Calendar earliestTime = new GregorianCalendar();
earliestTime.add(Calendar.SECOND, -(int) cooldown);
earliestTime.add(Calendar.MILLISECOND, -(int) ((cooldown * 1000.0) % 1000.0));
// This value contains the most recent time a teleportPlayer could have been used that would allow another use.
final long earliestLong = earliestTime.getTimeInMillis();
// When was the last teleportPlayer used?
final long lastTime = teleportOwner.getLastTeleportTimestamp();
if (lastTime > time.getTimeInMillis()) {
// This is to make sure time didn't get messed up on last teleportPlayer use.
// If this happens, let's give the user the benifit of the doubt.
teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis());
return false;
} else if (lastTime > earliestLong
&& cooldownApplies()) {
time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int) cooldown);
time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
future.completeExceptionally(new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis()))));
return true;
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
if (!check) {
teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis());
}
return false;
}
private boolean cooldownApplies() {
boolean applies = true;
final String globalBypassPerm = "essentials.teleport.cooldown.bypass";
switch (tpType) {
case NORMAL:
applies = !teleportOwner.isAuthorized(globalBypassPerm);
break;
case BACK:
applies = !(teleportOwner.isAuthorized(globalBypassPerm) &&
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.back"));
break;
case TPA:
applies = !(teleportOwner.isAuthorized(globalBypassPerm) &&
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.tpa"));
break;
}
return applies;
}
private void warnUser(final IUser user, final double delay) {
final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay);
c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));
user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis())));
}
@Override
public void now(final Location loc, final boolean cooldown, final TeleportCause cause, final CompletableFuture<Boolean> future) {
if (cooldown && cooldown(false, future)) {
return;
}
final ITarget target = new LocationTarget(loc);
nowAsync(teleportOwner, target, cause, future);
}
@Override
public void now(final Player entity, final boolean cooldown, final TeleportCause cause, final CompletableFuture<Boolean> future) {
if (cooldown && cooldown(false, future)) {
future.complete(false);
return;
}
final ITarget target = new PlayerTarget(entity);
nowAsync(teleportOwner, target, cause, future);
future.thenAccept(success -> {
if (success) {
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
}
});
}
private void runOnMain(final Runnable runnable) throws ExecutionException, InterruptedException {
if (Bukkit.isPrimaryThread()) {
runnable.run();
return;
}
final CompletableFuture<Object> taskLock = new CompletableFuture<>();
Bukkit.getScheduler().runTask(ess, () -> {
runnable.run();
taskLock.complete(new Object());
});
taskLock.get();
}
protected void nowAsync(final IUser teleportee, final ITarget target, final TeleportCause cause, final CompletableFuture<Boolean> future) {
cancel(false);
final PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
teleportee.setLastLocation();
if (!ess.getSettings().isForcePassengerTeleport() && !teleportee.getBase().isEmpty()) {
if (!ess.getSettings().isTeleportPassengerDismount()) {
future.completeExceptionally(new Exception(tl("passengerTeleportFail")));
return;
}
try {
runOnMain(() -> teleportee.getBase().eject()); //EntityDismountEvent requires a sync context.
} catch (final ExecutionException | InterruptedException e) {
future.completeExceptionally(e);
return;
}
}
teleportee.setLastLocation();
final Location targetLoc = target.getLocation();
if (ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockOutsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockX(), targetLoc.getBlockZ())) {
targetLoc.setX(LocationUtil.getXInsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockX()));
targetLoc.setZ(LocationUtil.getZInsideWorldBorder(targetLoc.getWorld(), targetLoc.getBlockZ()));
}
PaperLib.getChunkAtAsync(targetLoc).thenAccept(chunk -> {
Location loc = targetLoc;
if (LocationUtil.isBlockUnsafeForUser(teleportee, chunk.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) {
if (ess.getSettings().isTeleportSafetyEnabled()) {
if (ess.getSettings().isForceDisableTeleportSafety()) {
//The chunk we're teleporting to is 100% going to be loaded here, no need to teleport async.
teleportee.getBase().teleport(loc, cause);
} else {
try {
//There's a chance the safer location is outside the loaded chunk so still teleport async here.
PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
} catch (final Exception e) {
future.completeExceptionally(e);
return;
}
}
} else {
future.completeExceptionally(new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())));
return;
}
} else {
if (ess.getSettings().isForceDisableTeleportSafety()) {
//The chunk we're teleporting to is 100% going to be loaded here, no need to teleport async.
teleportee.getBase().teleport(loc, cause);
} else {
if (ess.getSettings().isTeleportToCenterLocation()) {
loc = LocationUtil.getRoundedDestination(loc);
}
//There's a *small* chance the rounded destination produces a location outside the loaded chunk so still teleport async here.
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
}
}
future.complete(true);
});
}
@Override
public void teleport(final Location loc, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause, future);
}
@Override
public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName()));
teleport(teleportOwner, new PlayerTarget(entity), chargeFor, cause, future);
}
@Override
public void teleportPlayer(final IUser otherUser, final Location loc, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
teleport(otherUser, new LocationTarget(loc), chargeFor, cause, future);
}
@Override
public void teleportPlayer(final IUser otherUser, final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
final ITarget target = new PlayerTarget(entity);
teleport(otherUser, target, chargeFor, cause, future);
future.thenAccept(success -> {
if (success) {
otherUser.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
}
});
}
private void teleport(final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
Trade cashCharge = chargeFor;
if (chargeFor != null) {
chargeFor.isAffordableFor(teleportOwner, future);
if (future.isCompletedExceptionally()) {
return;
}
//This code is to make sure that commandcosts are checked in the initial world, and not in the resulting world.
if (!chargeFor.getCommandCost(teleportOwner).equals(BigDecimal.ZERO)) {
//By converting a command cost to a regular cost, the command cost permission isn't checked when executing the charge after teleport.
cashCharge = new Trade(chargeFor.getCommandCost(teleportOwner), ess);
}
}
if (cooldown(true, future)) {
return;
}
if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") || teleportee.isAuthorized("essentials.teleport.timer.bypass")) {
if (cooldown(false, future)) {
return;
}
nowAsync(teleportee, target, cause, future);
if (cashCharge != null) {
cashCharge.charge(teleportOwner, future);
if (future.isCompletedExceptionally()) {
return;
}
}
return;
}
cancel(false);
warnUser(teleportee, delay);
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
}
private void teleportOther(final IUser teleporter, final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
Trade cashCharge = chargeFor;
if (teleporter != null && chargeFor != null) {
chargeFor.isAffordableFor(teleporter, future);
if (future.isCompletedExceptionally()) {
return;
}
//This code is to make sure that commandcosts are checked in the initial world, and not in the resulting world.
if (!chargeFor.getCommandCost(teleporter).equals(BigDecimal.ZERO)) {
//By converting a command cost to a regular cost, the command cost permission isn't checked when executing the charge after teleport.
cashCharge = new Trade(chargeFor.getCommandCost(teleporter), ess);
}
}
if (cooldown(true, future)) {
return;
}
if (delay <= 0 || teleporter == null
|| teleporter.isAuthorized("essentials.teleport.timer.bypass")
|| teleportOwner.isAuthorized("essentials.teleport.timer.bypass")
|| teleportee.isAuthorized("essentials.teleport.timer.bypass")) {
if (cooldown(false, future)) {
return;
}
nowAsync(teleportee, target, cause, future);
if (teleporter != null && cashCharge != null) {
cashCharge.charge(teleporter, future);
if (future.isCompletedExceptionally()) {
return;
}
}
return;
}
cancel(false);
warnUser(teleportee, delay);
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
}
@Override
public void respawn(final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
if (chargeFor != null) {
chargeFor.isAffordableFor(teleportOwner, future);
if (future.isCompletedExceptionally()) {
return;
}
}
if (cooldown(true, future)) {
return;
}
if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass")) {
if (cooldown(false, future)) {
return;
}
respawnNow(teleportOwner, cause, future);
if (chargeFor != null) {
chargeFor.charge(teleportOwner, future);
}
return;
}
cancel(false);
warnUser(teleportOwner, delay);
initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true);
}
void respawnNow(final IUser teleportee, final TeleportCause cause, final CompletableFuture<Boolean> future) {
final Player player = teleportee.getBase();
PaperLib.getBedSpawnLocationAsync(player, true).thenAccept(location -> {
if (location != null) {
nowAsync(teleportee, new LocationTarget(location), cause, future);
} else {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Could not find bed spawn, forcing respawn event.");
}
final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, player.getWorld().getSpawnLocation(), false);
ess.getServer().getPluginManager().callEvent(pre);
nowAsync(teleportee, new LocationTarget(pre.getRespawnLocation()), cause, future);
}
});
}
@Override
public void warp(final IUser otherUser, String warp, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
final UserWarpEvent event = new UserWarpEvent(otherUser, warp, chargeFor);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
warp = event.getWarp();
final Location loc;
try {
loc = ess.getWarps().getWarp(warp);
} catch (final WarpNotFoundException | InvalidWorldException e) {
future.completeExceptionally(e);
return;
}
otherUser.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
if (!otherUser.equals(teleportOwner)) {
teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
teleport(otherUser, new LocationTarget(loc), chargeFor, cause, future);
}
@Override
public void back(final Trade chargeFor, final CompletableFuture<Boolean> future) {
back(teleportOwner, chargeFor, future);
}
@Override
public void back(final IUser teleporter, final Trade chargeFor, final CompletableFuture<Boolean> future) {
tpType = TeleportType.BACK;
final Location loc = teleportOwner.getLastLocation();
teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND, future);
}
@Override
public void back(final CompletableFuture<Boolean> future) {
nowAsync(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND, future);
}
public void setTpType(final TeleportType tpType) {
this.tpType = tpType;
}
//If we need to cancelTimer a pending teleportPlayer call this method
private void cancel(final boolean notifyUser) {
if (timedTeleport != null) {
timedTeleport.cancelTimer(notifyUser);
timedTeleport = null;
}
}
private void initTimer(final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) {
timedTeleport = new AsyncTimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn);
}
public enum TeleportType {
TPA,
BACK,
NORMAL
}
}
@@ -0,0 +1,151 @@
package com.earth2me.essentials;
import net.ess3.api.IEssentials;
import net.ess3.api.IUser;
import org.bukkit.Location;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl;
public class AsyncTimedTeleport implements Runnable {
private static final double MOVE_CONSTANT = 0.3;
private final IUser teleportOwner;
private final IEssentials ess;
private final AsyncTeleport teleport;
private final UUID timer_teleportee;
private final long timer_started; // time this task was initiated
private final long timer_delay; // how long to delay the teleportPlayer
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
private final long timer_initX;
private final long timer_initY;
private final long timer_initZ;
private final ITarget timer_teleportTarget;
private final boolean timer_respawn;
private final boolean timer_canMove;
private final Trade timer_chargeFor;
private final TeleportCause timer_cause;
private int timer_task;
private double timer_health;
AsyncTimedTeleport(final IUser user, final IEssentials ess, final AsyncTeleport teleport, final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) {
this.teleportOwner = user;
this.ess = ess;
this.teleport = teleport;
this.timer_started = System.currentTimeMillis();
this.timer_delay = delay;
this.timer_health = teleportUser.getBase().getHealth();
this.timer_initX = Math.round(teleportUser.getBase().getLocation().getX() * MOVE_CONSTANT);
this.timer_initY = Math.round(teleportUser.getBase().getLocation().getY() * MOVE_CONSTANT);
this.timer_initZ = Math.round(teleportUser.getBase().getLocation().getZ() * MOVE_CONSTANT);
this.timer_teleportee = teleportUser.getBase().getUniqueId();
this.timer_teleportTarget = target;
this.timer_chargeFor = chargeFor;
this.timer_cause = cause;
this.timer_respawn = respawn;
this.timer_canMove = user.isAuthorized("essentials.teleport.timer.move");
timer_task = ess.runTaskTimerAsynchronously(this, 20, 20).getTaskId();
}
@Override
public void run() {
if (teleportOwner == null || !teleportOwner.getBase().isOnline() || teleportOwner.getBase().getLocation() == null) {
cancelTimer(false);
return;
}
final IUser teleportUser = ess.getUser(this.timer_teleportee);
if (teleportUser == null || !teleportUser.getBase().isOnline()) {
cancelTimer(false);
return;
}
final Location currLocation = teleportUser.getBase().getLocation();
if (currLocation == null) {
cancelTimer(false);
return;
}
if (!timer_canMove && (Math.round(currLocation.getX() * MOVE_CONSTANT) != timer_initX || Math.round(currLocation.getY() * MOVE_CONSTANT) != timer_initY || Math.round(currLocation.getZ() * MOVE_CONSTANT) != timer_initZ || teleportUser.getBase().getHealth() < timer_health)) {
// user moved, cancelTimer teleportPlayer
cancelTimer(true);
return;
}
class DelayedTeleportTask implements Runnable {
@Override
public void run() {
timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured
final long now = System.currentTimeMillis();
if (now > timer_started + timer_delay) {
try {
teleport.cooldown(false);
} catch (final Throwable ex) {
teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
if (teleportOwner != teleportUser) {
teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
}
}
try {
cancelTimer(false);
teleportUser.sendMessage(tl("teleportationCommencing"));
final CompletableFuture<Boolean> future = new CompletableFuture<>();
future.exceptionally(e -> {
ess.showError(teleportOwner.getSource(), e, "\\ teleport");
return false;
});
if (timer_chargeFor != null) {
timer_chargeFor.isAffordableFor(teleportOwner);
}
if (timer_respawn) {
teleport.respawnNow(teleportUser, timer_cause, future);
} else {
teleport.nowAsync(teleportUser, timer_teleportTarget, timer_cause, future);
}
future.thenAccept(success -> {
if (timer_chargeFor != null) {
try {
timer_chargeFor.charge(teleportOwner);
} catch (final ChargeException ex) {
ess.showError(teleportOwner.getSource(), ex, "\\ teleport");
}
}
});
} catch (final Exception ex) {
ess.showError(teleportOwner.getSource(), ex, "\\ teleport");
}
}
}
}
ess.scheduleSyncDelayedTask(new DelayedTeleportTask());
}
//If we need to cancelTimer a pending teleportPlayer call this method
void cancelTimer(final boolean notifyUser) {
if (timer_task == -1) {
return;
}
try {
ess.getServer().getScheduler().cancelTask(timer_task);
if (notifyUser) {
teleportOwner.sendMessage(tl("pendingTeleportCancelled"));
if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) {
ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled"));
}
}
} finally {
timer_task = -1;
}
}
}
@@ -7,30 +7,28 @@ import org.bukkit.command.CommandSender;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class Backup implements Runnable {
private static final Logger LOGGER = Logger.getLogger("Essentials");
private transient final Server server;
private transient final IEssentials ess;
private final AtomicBoolean pendingShutdown = new AtomicBoolean(false);
private transient boolean running = false;
private transient int taskId = -1;
private transient boolean active = false;
private transient CompletableFuture<Object> taskLock = null;
public Backup(final IEssentials ess) {
this.ess = ess;
server = ess.getServer();
if (!ess.getOnlinePlayers().isEmpty()) {
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
startTask();
}
});
if (!ess.getOnlinePlayers().isEmpty() || ess.getSettings().isAlwaysRunBackup()) {
ess.runTaskAsynchronously(this::startTask);
}
}
@@ -57,20 +55,30 @@ public class Backup implements Runnable {
}
}
public CompletableFuture<Object> getTaskLock() {
return taskLock;
}
public void setPendingShutdown(final boolean shutdown) {
pendingShutdown.set(shutdown);
}
@Override
public void run() {
if (active) {
return;
}
active = true;
final String command = ess.getSettings().getBackupCommand();
if (command == null || "".equals(command)) {
return;
}
active = true;
taskLock = new CompletableFuture<>();
if ("save-all".equalsIgnoreCase(command)) {
final CommandSender cs = server.getConsoleSender();
server.dispatchCommand(cs, "save-all");
active = false;
taskLock.complete(new Object());
return;
}
LOGGER.log(Level.INFO, tl("backupStarted"));
@@ -78,52 +86,45 @@ public class Backup implements Runnable {
server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off");
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
try {
final ProcessBuilder childBuilder = new ProcessBuilder(command);
childBuilder.redirectErrorStream(true);
childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile());
final Process child = childBuilder.start();
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()));
try {
String line;
do {
line = reader.readLine();
if (line != null) {
LOGGER.log(Level.INFO, line);
}
} while (line != null);
} finally {
reader.close();
ess.runTaskAsynchronously(() -> {
try {
final ProcessBuilder childBuilder = new ProcessBuilder(command.split(" "));
childBuilder.redirectErrorStream(true);
childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile());
final Process child = childBuilder.start();
ess.runTaskAsynchronously(() -> {
try {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()))) {
String line;
do {
line = reader.readLine();
if (line != null) {
LOGGER.log(Level.INFO, line);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
});
child.waitFor();
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
class BackupEnableSaveTask implements Runnable {
@Override
public void run() {
server.dispatchCommand(cs, "save-on");
if (ess.getOnlinePlayers().isEmpty()) {
stopTask();
}
active = false;
LOGGER.log(Level.INFO, tl("backupFinished"));
} while (line != null);
}
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
});
child.waitFor();
} catch (final InterruptedException | IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
class BackupEnableSaveTask implements Runnable {
@Override
public void run() {
server.dispatchCommand(cs, "save-on");
if (!ess.getSettings().isAlwaysRunBackup() && ess.getOnlinePlayers().isEmpty()) {
stopTask();
}
active = false;
taskLock.complete(new Object());
LOGGER.log(Level.INFO, tl("backupFinished"));
}
}
if (!pendingShutdown.get()) {
ess.scheduleSyncDelayedTask(new BackupEnableSaveTask());
}
}
@@ -1,6 +1,5 @@
package com.earth2me.essentials;
public class ChargeException extends Exception {
public ChargeException(final String message) {
super(message);
@@ -3,7 +3,6 @@ package com.earth2me.essentials;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandSource {
protected CommandSender sender;
@@ -22,18 +21,36 @@ public class CommandSource {
return null;
}
public final net.ess3.api.IUser getUser(final IEssentials ess) {
if (sender instanceof Player) {
return ess.getUser((Player) sender);
}
return null;
}
public final boolean isPlayer() {
return (sender instanceof Player);
return sender instanceof Player;
}
public final CommandSender setSender(final CommandSender base) {
return this.sender = base;
}
public void sendMessage(String message) {
public void sendMessage(final String message) {
if (!message.isEmpty()) {
sender.sendMessage(message);
}
}
public boolean isAuthorized(final String permission, final IEssentials ess) {
return !(sender instanceof Player) || getUser(ess).isAuthorized(permission);
}
public String getSelfSelector() {
return sender instanceof Player ? getPlayer().getName() : "*";
}
public String getDisplayName() {
return sender instanceof Player ? getPlayer().getDisplayName() : getSender().getName();
}
}
@@ -2,76 +2,88 @@ package com.earth2me.essentials;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public final class Console implements IMessageRecipient {
public static final String NAME = "Console";
private static Console instance; // Set in essentials
private final IEssentials ess;
private final IMessageRecipient messageRecipient;
private Console(final IEssentials ess) {
this.ess = ess;
this.messageRecipient = new SimpleMessageRecipient(ess, this);
}
public static Console getInstance() {
return instance;
}
static void setInstance(IEssentials ess) { // Called in Essentials#onEnable()
static void setInstance(final IEssentials ess) { // Called in Essentials#onEnable()
instance = new Console(ess);
}
/**
* @deprecated Use {@link Console#getCommandSender()}
*/
@Deprecated
public static CommandSender getCommandSender(Server server) throws Exception {
public static CommandSender getCommandSender(final Server server) throws Exception {
return server.getConsoleSender();
}
private Console(IEssentials ess) {
this.ess = ess;
this.messageRecipient = new SimpleMessageRecipient(ess, this);
}
public CommandSender getCommandSender() {
return ess.getServer().getConsoleSender();
}
@Override public String getName() {
@Override
public String getName() {
return Console.NAME;
}
@Override public String getDisplayName() {
@Override
public String getDisplayName() {
return Console.NAME;
}
@Override public void sendMessage(String message) {
@Override
public void sendMessage(final String message) {
getCommandSender().sendMessage(message);
}
@Override public boolean isReachable() {
@Override
public boolean isReachable() {
return true;
}
/* ================================
* >> DELEGATE METHODS
* ================================ */
@Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) {
@Override
public MessageResponse sendMessage(final IMessageRecipient recipient, final String message) {
return this.messageRecipient.sendMessage(recipient, message);
}
@Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) {
@Override
public MessageResponse onReceiveMessage(final IMessageRecipient sender, final String message) {
return this.messageRecipient.onReceiveMessage(sender, message);
}
@Override public IMessageRecipient getReplyRecipient() {
@Override
public IMessageRecipient getReplyRecipient() {
return this.messageRecipient.getReplyRecipient();
}
@Override public void setReplyRecipient(IMessageRecipient recipient) {
@Override
public void setReplyRecipient(final IMessageRecipient recipient) {
this.messageRecipient.setReplyRecipient(recipient);
}
@Override
public boolean isHiddenFrom(Player player) {
return false;
}
}
@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import java.util.HashMap;
@@ -9,10 +9,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Enchantments {
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
private static final Map<String, Enchantment> ALIASENCHANTMENTS = new HashMap<String, Enchantment>();
public final class Enchantments {
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<>();
private static final Map<String, Enchantment> ALIASENCHANTMENTS = new HashMap<>();
private static boolean isFlat;
static {
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
@@ -151,60 +151,139 @@ public class Enchantments {
// 1.8
try {
Enchantment depthStrider = Enchantment.getByName("DEPTH_STRIDER");
final Enchantment depthStrider = Enchantment.getByName("DEPTH_STRIDER");
if (depthStrider != null) {
ENCHANTMENTS.put("depthstrider", depthStrider);
ALIASENCHANTMENTS.put("depth", depthStrider);
ALIASENCHANTMENTS.put("strider", depthStrider);
}
} catch (IllegalArgumentException ignored) {}
} catch (final IllegalArgumentException ignored) {
}
// 1.9
try {
Enchantment frostWalker = Enchantment.getByName("FROST_WALKER");
final Enchantment frostWalker = Enchantment.getByName("FROST_WALKER");
if (frostWalker != null) {
ENCHANTMENTS.put("frostwalker", frostWalker);
ALIASENCHANTMENTS.put("frost", frostWalker);
ALIASENCHANTMENTS.put("walker", frostWalker);
}
Enchantment mending = Enchantment.getByName("MENDING");
final Enchantment mending = Enchantment.getByName("MENDING");
if (mending != null) {
ENCHANTMENTS.put("mending", mending);
}
} catch (IllegalArgumentException ignored) {}
} catch (final IllegalArgumentException ignored) {
}
// 1.11
try {
Enchantment bindingCurse = Enchantment.getByName("BINDING_CURSE");
final Enchantment bindingCurse = Enchantment.getByName("BINDING_CURSE");
if (bindingCurse != null) {
ENCHANTMENTS.put("bindingcurse", bindingCurse);
ALIASENCHANTMENTS.put("bindcurse", bindingCurse);
ALIASENCHANTMENTS.put("binding", bindingCurse);
ALIASENCHANTMENTS.put("bind", bindingCurse);
}
Enchantment vanishingCurse = Enchantment.getByName("VANISHING_CURSE");
final Enchantment vanishingCurse = Enchantment.getByName("VANISHING_CURSE");
if (vanishingCurse != null) {
ENCHANTMENTS.put("vanishingcurse", vanishingCurse);
ALIASENCHANTMENTS.put("vanishcurse", vanishingCurse);
ALIASENCHANTMENTS.put("vanishing", vanishingCurse);
ALIASENCHANTMENTS.put("vanish", vanishingCurse);
}
Enchantment sweeping = Enchantment.getByName("SWEEPING_EDGE");
final Enchantment sweeping = Enchantment.getByName("SWEEPING_EDGE");
if (sweeping != null) {
ENCHANTMENTS.put("sweepingedge", sweeping);
ALIASENCHANTMENTS.put("sweepedge", sweeping);
ALIASENCHANTMENTS.put("sweeping", sweeping);
}
} catch (IllegalArgumentException ignored) {}
} catch (final IllegalArgumentException ignored) {
}
try { // 1.13
final Enchantment loyalty = Enchantment.getByName("LOYALTY");
if (loyalty != null) {
ENCHANTMENTS.put("loyalty", loyalty);
ALIASENCHANTMENTS.put("loyal", loyalty);
ALIASENCHANTMENTS.put("return", loyalty);
}
final Enchantment impaling = Enchantment.getByName("IMPALING");
if (impaling != null) {
ENCHANTMENTS.put("impaling", impaling);
ALIASENCHANTMENTS.put("impale", impaling);
ALIASENCHANTMENTS.put("oceandamage", impaling);
ALIASENCHANTMENTS.put("oceandmg", impaling);
}
final Enchantment riptide = Enchantment.getByName("RIPTIDE");
if (riptide != null) {
ENCHANTMENTS.put("riptide", riptide);
ALIASENCHANTMENTS.put("rip", riptide);
ALIASENCHANTMENTS.put("tide", riptide);
ALIASENCHANTMENTS.put("launch", riptide);
}
final Enchantment channelling = Enchantment.getByName("CHANNELING");
if (channelling != null) {
ENCHANTMENTS.put("channelling", channelling);
ALIASENCHANTMENTS.put("chanelling", channelling);
ALIASENCHANTMENTS.put("channeling", channelling);
ALIASENCHANTMENTS.put("chaneling", channelling);
ALIASENCHANTMENTS.put("channel", channelling);
}
} catch (final IllegalArgumentException ignored) {
}
try { // 1.14
final Enchantment multishot = Enchantment.getByName("MULTISHOT");
if (multishot != null) {
ENCHANTMENTS.put("multishot", multishot);
ALIASENCHANTMENTS.put("tripleshot", multishot);
}
final Enchantment quickCharge = Enchantment.getByName("QUICK_CHARGE");
if (quickCharge != null) {
ENCHANTMENTS.put("quickcharge", quickCharge);
ALIASENCHANTMENTS.put("quickdraw", quickCharge);
ALIASENCHANTMENTS.put("fastcharge", quickCharge);
ALIASENCHANTMENTS.put("fastdraw", quickCharge);
}
final Enchantment piercing = Enchantment.getByName("PIERCING");
if (piercing != null) {
ENCHANTMENTS.put("piercing", piercing);
}
} catch (final IllegalArgumentException ignored) {
}
try { // 1.16
final Enchantment soulspeed = Enchantment.getByName("SOUL_SPEED");
if (soulspeed != null) {
ENCHANTMENTS.put("soulspeed", soulspeed);
ALIASENCHANTMENTS.put("soilspeed", soulspeed);
ALIASENCHANTMENTS.put("sandspeed", soulspeed);
}
} catch (final IllegalArgumentException ignored) {
}
try {
final Class<?> namespacedKeyClass = Class.forName("org.bukkit.NamespacedKey");
final Class<?> enchantmentClass = Class.forName("org.bukkit.enchantments.Enchantment");
enchantmentClass.getDeclaredMethod("getByKey", namespacedKeyClass);
isFlat = true;
} catch (final ClassNotFoundException | NoSuchMethodException e) {
isFlat = false;
}
}
public static Enchantment getByName(String name) {
Enchantment enchantment;
if (NumberUtil.isInt(name)) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
private Enchantments() {
}
public static Enchantment getByName(final String name) {
Enchantment enchantment = null;
if (isFlat) { // 1.13+ only
enchantment = Enchantment.getByKey(NamespacedKey.minecraft(name.toLowerCase()));
}
if (enchantment == null) {
enchantment = Enchantment.getByName(name.toUpperCase());
}
if (enchantment == null) {
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
@@ -17,8 +17,17 @@
*/
package com.earth2me.essentials;
import com.earth2me.essentials.commands.*;
import com.earth2me.essentials.metrics.Metrics;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.commands.QuietAbortException;
import com.earth2me.essentials.items.AbstractItemDb;
import com.earth2me.essentials.items.CustomItemResolver;
import com.earth2me.essentials.items.FlatItemDb;
import com.earth2me.essentials.items.LegacyItemDb;
import com.earth2me.essentials.metrics.MetricsWrapper;
import com.earth2me.essentials.perm.PermissionsDefaults;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.signs.SignBlockListener;
@@ -28,35 +37,51 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import net.ess3.api.*;
import com.earth2me.essentials.utils.VersionUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.Economy;
import net.ess3.api.IEssentials;
import net.ess3.api.IItemDb;
import net.ess3.api.IJails;
import net.ess3.api.ISettings;
import net.ess3.nms.PotionMetaProvider;
import net.ess3.nms.SpawnEggProvider;
import net.ess3.nms.SpawnerProvider;
import net.ess3.nms.legacy.LegacyPotionMetaProvider;
import net.ess3.nms.refl.ReflSpawnEggProvider;
import net.ess3.nms.updatedmeta.BasePotionDataProvider;
import net.ess3.nms.updatedmeta.BlockMetaSpawnerProvider;
import net.ess3.nms.legacy.LegacySpawnEggProvider;
import net.ess3.nms.legacy.LegacySpawnerProvider;
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 net.ess3.nms.refl.providers.ReflServerStateProvider;
import net.ess3.nms.refl.providers.ReflSpawnEggProvider;
import net.ess3.nms.refl.providers.ReflSpawnerBlockProvider;
import net.ess3.nms.refl.providers.ReflKnownCommandsProvider;
import net.ess3.provider.ContainerProvider;
import net.ess3.provider.KnownCommandsProvider;
import net.ess3.provider.PotionMetaProvider;
import net.ess3.provider.ProviderListener;
import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SpawnEggProvider;
import net.ess3.provider.SpawnerBlockProvider;
import net.ess3.provider.SpawnerItemProvider;
import net.ess3.provider.providers.BasePotionDataProvider;
import net.ess3.provider.providers.BlockMetaSpawnerItemProvider;
import net.ess3.provider.providers.BukkitSpawnerBlockProvider;
import net.ess3.provider.providers.FlatSpawnEggProvider;
import net.ess3.provider.providers.LegacyPotionMetaProvider;
import net.ess3.provider.providers.LegacySpawnEggProvider;
import net.ess3.provider.providers.PaperContainerProvider;
import net.ess3.provider.providers.PaperKnownCommandsProvider;
import net.ess3.provider.providers.PaperRecipeBookListener;
import net.ess3.provider.providers.PaperServerStateProvider;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.*;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
@@ -72,54 +97,63 @@ import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private static final Logger LOGGER = Logger.getLogger("Essentials");
private transient ISettings settings;
private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this);
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private transient ISettings settings;
private transient Jails jails;
private transient Warps warps;
private transient Worth worth;
private transient List<IConf> confList;
private transient Backup backup;
private transient ItemDb itemDb;
private transient final Methods paymentMethod = new Methods();
private transient AbstractItemDb itemDb;
private transient CustomItemResolver customItemResolver;
private transient PermissionsHandler permissionsHandler;
private transient AlternativeCommandsHandler alternativeCommandsHandler;
private transient UserMap userMap;
private transient ExecuteTimer execTimer;
private transient I18n i18n;
private transient Metrics metrics;
private transient MetricsWrapper metrics;
private transient EssentialsTimer timer;
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private transient Method oldGetOnlinePlayers;
private transient SpawnerProvider spawnerProvider;
private transient SpawnerItemProvider spawnerItemProvider;
private transient SpawnerBlockProvider spawnerBlockProvider;
private transient SpawnEggProvider spawnEggProvider;
private transient PotionMetaProvider potionMetaProvider;
private transient ServerStateProvider serverStateProvider;
private transient ContainerProvider containerProvider;
private transient KnownCommandsProvider knownCommandsProvider;
private transient ProviderListener recipeBookEventProvider;
private transient Kits kits;
private transient RandomTeleport randomTeleport;
static {
// TODO: improve legacy code
Methods.init();
}
public Essentials() {
}
public Essentials(final Server server) {
super(new JavaPluginLoader(server), new PluginDescriptionFile("Essentials", "", "com.earth2me.essentials.Essentials"), null, null);
protected Essentials(final JavaPluginLoader loader, final PluginDescriptionFile description, final File dataFolder, final File file) {
super(loader, description, dataFolder, file);
}
@SuppressWarnings("unused")
public void forceLoadClasses() {
try {
Class.forName(OfflinePlayer.class.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
public Essentials(final Server server) {
super(new JavaPluginLoader(server), new PluginDescriptionFile("Essentials", "", "com.earth2me.essentials.Essentials"), null, null);
}
@Override
@@ -139,7 +173,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);
@@ -163,71 +197,145 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
i18n = new I18n(this);
i18n.onEnable();
execTimer.mark("I18n1");
Console.setInstance(this);
switch (VersionUtil.getServerSupportStatus()) {
case UNSTABLE:
getLogger().severe(tl("serverUnsupportedMods"));
break;
case OUTDATED:
getLogger().severe(tl("serverUnsupported"));
break;
case LIMITED:
getLogger().info(tl("serverUnsupportedLimitedApi"));
break;
}
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins()) {
for (final Plugin plugin : pm.getPlugins()) {
if (plugin.getDescription().getName().startsWith("Essentials") && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) {
getLogger().warning(tl("versionMismatch", plugin.getDescription().getName()));
}
}
for (Method method : Server.class.getDeclaredMethods()) {
if (method.getName().endsWith("getOnlinePlayers") && method.getReturnType() == Player[].class) {
oldGetOnlinePlayers = method;
break;
}
}
forceLoadClasses();
try {
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
kits = new Kits(this);
confList.add(kits);
upgrade.convertKits();
execTimer.mark("Kits");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
execTimer.mark("Init(Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
execTimer.mark("Init(Worth)");
itemDb = getItemDbFromConfig();
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
execTimer.mark("Init(ItemDB)");
randomTeleport = new RandomTeleport(this);
if (randomTeleport.getPreCache()) {
randomTeleport.cacheRandomLocations(randomTeleport.getCenter(), randomTeleport.getMinRange(), randomTeleport.getMaxRange());
}
confList.add(randomTeleport);
execTimer.mark("Init(RandomTeleport)");
customItemResolver = new CustomItemResolver(this);
try {
itemDb.registerResolver(this, "custom_items", customItemResolver);
confList.add(customItemResolver);
} catch (final Exception e) {
e.printStackTrace();
customItemResolver = null;
}
execTimer.mark("Init(CustomItemResolver)");
jails = new Jails(this);
confList.add(jails);
spawnerProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
BlockMetaSpawnerProvider.class,
v1_8_R2SpawnerProvider.class,
v1_8_R1SpawnerProvider.class,
LegacySpawnerProvider.class
), "mob spawner").getProvider();
spawnEggProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
ReflSpawnEggProvider.class,
LegacySpawnEggProvider.class
), "spawn egg").getProvider();
potionMetaProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
BasePotionDataProvider.class,
LegacyPotionMetaProvider.class
), "potion meta").getProvider();
execTimer.mark("Init(Jails)");
//Spawner item provider only uses one but it's here for legacy...
spawnerItemProvider = new BlockMetaSpawnerItemProvider();
//Spawner block providers
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) {
spawnerBlockProvider = new ReflSpawnerBlockProvider();
} else {
spawnerBlockProvider = new BukkitSpawnerBlockProvider();
}
//Spawn Egg Providers
if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_8_8_R01)) {
spawnEggProvider = new LegacySpawnEggProvider();
} else if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_12_2_R01)) {
spawnEggProvider = new ReflSpawnEggProvider();
} else {
spawnEggProvider = new FlatSpawnEggProvider();
}
//Potion Meta Provider
if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_8_8_R01)) {
potionMetaProvider = new LegacyPotionMetaProvider();
} else {
potionMetaProvider = new BasePotionDataProvider();
}
//Server State Provider
//Container Provider
if (PaperLib.isPaper() && VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_15_2_R01)) {
serverStateProvider = new PaperServerStateProvider();
containerProvider = new PaperContainerProvider();
} else {
serverStateProvider = new ReflServerStateProvider(getLogger());
}
//Event Providers
if (PaperLib.isPaper()) {
try {
Class.forName("com.destroystokyo.paper.event.player.PlayerRecipeBookClickEvent");
recipeBookEventProvider = new PaperRecipeBookListener(event -> {
if (this.getUser(((PlayerEvent) event).getPlayer()).isRecipeSee()) {
((Cancellable) event).setCancelled(true);
}
});
} catch (final ClassNotFoundException ignored) {
}
}
//Known Commands Provider
if (PaperLib.isPaper() && VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_11_2_R01)) {
knownCommandsProvider = new PaperKnownCommandsProvider();
} else {
knownCommandsProvider = new ReflKnownCommandsProvider();
}
execTimer.mark("Init(Providers)");
reload();
} catch (YAMLException exception) {
// The item spawn blacklist is loaded with all other settings, before the item
// DB, but it depends on the item DB, so we need to reload it again here:
((Settings) settings)._lateLoadItemSpawnBlacklist();
} catch (final YAMLException exception) {
if (pm.getPlugin("EssentialsUpdate") != null) {
LOGGER.log(Level.SEVERE, tl("essentialsHelp2"));
} else {
@@ -246,23 +354,23 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
Economy.setEss(this);
execTimer.mark("RegHandler");
metrics = new Metrics(this);
if (!metrics.isOptOut()) {
getLogger().info("Starting Metrics. Opt-out using the global bStats config.");
} else {
getLogger().info("Metrics disabled per bStats config.");
}
// Register /hat and /back default permissions
PermissionsDefaults.registerAllBackDefaults();
PermissionsDefaults.registerAllHatDefaults();
metrics = new MetricsWrapper(this, 858, true);
final String timeroutput = execTimer.end();
if (getSettings().isDebug()) {
LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput);
}
} catch (NumberFormatException ex) {
} catch (final NumberFormatException ex) {
handleCrash(ex);
} catch (Error ex) {
} catch (final Error ex) {
handleCrash(ex);
throw ex;
}
getBackup().setPendingShutdown(false);
}
@Override
@@ -270,7 +378,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
// We don't use any of the bukkit config writing, as this breaks our config file formatting.
}
private void registerListeners(PluginManager pm) {
private void registerListeners(final PluginManager pm) {
HandlerList.unregisterAll(this);
if (getSettings().isDebug()) {
@@ -307,25 +415,49 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
pm.registerEvents(tntListener, this);
if (recipeBookEventProvider != null) {
pm.registerEvents(recipeBookEventProvider, this);
}
jails.resetListener();
}
@Override
public void onDisable() {
for (User user : getOnlineUsers()) {
final boolean stopping = getServerStateProvider().isStopping();
if (!stopping) {
LOGGER.log(Level.SEVERE, tl("serverReloading"));
}
getBackup().setPendingShutdown(true);
for (final User user : getOnlineUsers()) {
if (user.isVanished()) {
user.setVanished(false);
user.sendMessage(tl("unvanishedReload"));
}
user.stopTransaction();
if (stopping) {
user.setLastLocation();
if (!user.isHidden()) {
user.setLastLogout(System.currentTimeMillis());
}
user.cleanup();
} else {
user.stopTransaction();
}
}
cleanupOpenInventories();
if (getBackup().getTaskLock() != null && !getBackup().getTaskLock().isDone()) {
LOGGER.log(Level.SEVERE, tl("backupInProgress"));
getBackup().getTaskLock().join();
}
if (i18n != null) {
i18n.onDisable();
}
if (backup != null) {
backup.stopTask();
}
this.getPermissionsHandler().unregisterContexts();
Economy.setEss(null);
Trade.closeLog();
getUserMap().getUUIDMap().shutdown();
@@ -337,19 +469,26 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
public void reload() {
Trade.closeLog();
for (IConf iConf : confList) {
for (final IConf iConf : confList) {
iConf.reloadConfig();
execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")");
}
i18n.updateLocale(settings.getLocale());
for (final String commandName : this.getDescription().getCommands().keySet()) {
final Command command = this.getCommand(commandName);
if (command != null) {
command.setDescription(tl(commandName + "CommandDescription"));
command.setUsage(tl(commandName + "CommandUsage"));
}
}
final PluginManager pm = getServer().getPluginManager();
registerListeners(pm);
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String commandLabel, String[] args) {
public List<String> onTabComplete(final CommandSender sender, final Command command, final String commandLabel, final String[] args) {
return onTabCompleteEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(),
"com.earth2me.essentials.commands.Command", "essentials.", null);
}
@@ -362,7 +501,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel);
if (pc != null) {
try {
TabCompleter completer = pc.getTabCompleter();
final TabCompleter completer = pc.getTabCompleter();
if (completer != null) {
return completer.onTabComplete(cSender, command, commandLabel, args);
}
@@ -379,19 +518,19 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
user = getUser((Player) cSender);
}
CommandSource sender = new CommandSource(cSender);
final CommandSource sender = new CommandSource(cSender);
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel)) {
return Collections.emptyList();
}
IEssentialsCommand cmd;
final IEssentialsCommand cmd;
try {
cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
cmd.setEssentialsModule(module);
} catch (Exception ex) {
} catch (final Exception ex) {
sender.sendMessage(tl("commandNotLoaded", commandLabel));
LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex);
return Collections.emptyList();
@@ -413,13 +552,13 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
} else {
return cmd.tabComplete(getServer(), user, commandLabel, command, args);
}
} catch (Exception ex) {
} catch (final Exception ex) {
showError(sender, ex, commandLabel);
// Tab completion shouldn't fail
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex);
return Collections.emptyList();
}
} catch (Throwable ex) {
} catch (final Throwable ex) {
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex);
return Collections.emptyList();
}
@@ -427,6 +566,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) {
metrics.markCommand(command.getName(), true);
return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null);
}
@@ -441,7 +581,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return pc.execute(cSender, commandLabel, args);
} catch (final Exception ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
cSender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
cSender.sendMessage(tl("internalError"));
return true;
}
}
@@ -454,17 +594,19 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
if (cSender instanceof Player) {
user = getUser((Player) cSender);
} else if (cSender instanceof BlockCommandSender) {
BlockCommandSender bsender = (BlockCommandSender) cSender;
final BlockCommandSender bsender = (BlockCommandSender) cSender;
bSenderBlock = bsender.getBlock();
}
if (bSenderBlock != null) {
Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[]{bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)});
if (getSettings().logCommandBlockCommands()) {
Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[] {bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)});
}
} else if (user == null) {
Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[]{cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)});
Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[] {cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)});
}
CommandSource sender = new CommandSource(cSender);
final CommandSource sender = new CommandSource(cSender);
// New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) {
@@ -479,15 +621,16 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel)) {
sender.sendMessage(tl("commandDisabled", commandLabel));
return true;
}
IEssentialsCommand cmd;
final IEssentialsCommand cmd;
try {
cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
cmd.setEssentialsModule(module);
} catch (Exception ex) {
} catch (final Exception ex) {
sender.sendMessage(tl("commandNotLoaded", commandLabel));
LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex);
return true;
@@ -517,32 +660,33 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
} catch (NoChargeException ex) {
} catch (final NoChargeException | QuietAbortException ex) {
return true;
} catch (QuietAbortException ex) {
return true;
} catch (NotEnoughArgumentsException ex) {
} catch (final NotEnoughArgumentsException ex) {
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
if (!ex.getMessage().isEmpty()) {
sender.sendMessage(ex.getMessage());
}
if (ex.getCause() != null && settings.isDebug()) {
ex.getCause().printStackTrace();
}
return true;
} catch (Exception ex) {
} catch (final Exception ex) {
showError(sender, ex, commandLabel);
if (settings.isDebug()) {
ex.printStackTrace();
}
return true;
}
} catch (Throwable ex) {
} catch (final Throwable ex) {
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex);
return true;
}
}
public void cleanupOpenInventories() {
for (User user : getOnlineUsers()) {
for (final User user : getOnlineUsers()) {
if (user.isRecipeSee()) {
user.getBase().getOpenInventory().getTopInventory().clear();
user.getBase().getOpenInventory().close();
@@ -595,13 +739,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
}
@Override
public Metrics getMetrics() {
return metrics;
}
@Override
public void setMetrics(Metrics metrics) {
this.metrics = metrics;
public RandomTeleport getRandomTeleport() {
return randomTeleport;
}
@Deprecated
@@ -675,7 +814,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return user;
}
private void handleCrash(Throwable exception) {
private void handleCrash(final Throwable exception) {
final PluginManager pm = getServer().getPluginManager();
LOGGER.log(Level.SEVERE, exception.toString());
exception.printStackTrace();
@@ -685,7 +824,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, this);
for (Player player : getOnlinePlayers()) {
for (final Player player : getOnlinePlayers()) {
player.sendMessage("Essentials failed to load, read the log file.");
}
this.setEnabled(false);
@@ -707,27 +846,27 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
confList.add(listener);
}
@Override
public Methods getPaymentMethod() {
return paymentMethod;
}
@Override
public int broadcastMessage(final String message) {
return broadcastMessage(null, null, message, true);
return broadcastMessage(null, null, message, true, u -> false);
}
@Override
public int broadcastMessage(final IUser sender, final String message) {
return broadcastMessage(sender, null, message, false);
return broadcastMessage(sender, null, message, false, u -> false);
}
@Override
public int broadcastMessage(final IUser sender, final String message, final Predicate<IUser> shouldExclude) {
return broadcastMessage(sender, null, message, false, shouldExclude);
}
@Override
public int broadcastMessage(final String permission, final String message) {
return broadcastMessage(null, permission, message, false);
return broadcastMessage(null, permission, message, false, u -> false);
}
private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords) {
private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords, final Predicate<IUser> shouldExclude) {
if (sender != null && sender.isHidden()) {
return 0;
}
@@ -735,14 +874,16 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
IText broadcast = new SimpleTextInput(message);
final Collection<Player> players = getOnlinePlayers();
for (Player player : players) {
for (final Player player : players) {
final User user = getUser(player);
if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) || (permission != null && user.isAuthorized(permission))) {
if (shouldExclude.test(user)) {
continue;
}
if (keywords) {
broadcast = new KeywordReplacer(broadcast, new CommandSource(player), this, false);
}
for (String messageText : broadcast.getLines()) {
for (final String messageText : broadcast.getLines()) {
user.sendMessage(messageText);
}
}
@@ -828,33 +969,26 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override
public Collection<Player> getOnlinePlayers() {
try {
return (Collection<Player>) getServer().getOnlinePlayers(); // Needed for sanity here, the Bukkit API is a bit broken in the sense it only allows subclasses of Player to this list
} catch (NoSuchMethodError ex) {
try {
return Arrays.asList((Player[]) oldGetOnlinePlayers.invoke(getServer()));
} catch (InvocationTargetException ex1) {
throw Throwables.propagate(ex.getCause());
} catch (IllegalAccessException ex1) {
throw new RuntimeException("Error invoking oldGetOnlinePlayers", ex1);
}
}
return (Collection<Player>) getServer().getOnlinePlayers();
}
@Override
public Iterable<User> getOnlineUsers() {
return Iterables.transform(getOnlinePlayers(), new Function<Player, User>() {
@Override
public User apply(Player player) {
return getUser(player);
}
});
final List<User> onlineUsers = new ArrayList<>();
for (final Player player : getOnlinePlayers()) {
onlineUsers.add(getUser(player));
}
return onlineUsers;
}
@Override
public SpawnerProvider getSpawnerProvider() {
return spawnerProvider;
public SpawnerItemProvider getSpawnerItemProvider() {
return spawnerItemProvider;
}
@Override
public SpawnerBlockProvider getSpawnerBlockProvider() {
return spawnerBlockProvider;
}
@Override
@@ -867,18 +1001,58 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return potionMetaProvider;
}
@Override
public CustomItemResolver getCustomItemResolver() {
return customItemResolver;
}
@Override
public ServerStateProvider getServerStateProvider() {
return serverStateProvider;
}
@Override
public ContainerProvider getContainerProvider() {
return containerProvider;
}
@Override
public KnownCommandsProvider getKnownCommandsProvider() {
return knownCommandsProvider;
}
private AbstractItemDb getItemDbFromConfig() {
final String setting = settings.getItemDbType();
if (setting.equalsIgnoreCase("json")) {
return new FlatItemDb(this);
} else if (setting.equalsIgnoreCase("csv")) {
return new LegacyItemDb(this);
} else {
final VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion();
if (version.isHigherThanOrEqualTo(VersionUtil.v1_13_0_R01)) {
return new FlatItemDb(this);
} else {
return new LegacyItemDb(this);
}
}
}
private static class EssentialsWorldListener implements Listener, Runnable {
private transient final IEssentials ess;
public EssentialsWorldListener(final IEssentials ess) {
EssentialsWorldListener(final IEssentials ess) {
this.ess = ess;
}
@EventHandler(priority = EventPriority.LOW)
public void onWorldLoad(final WorldLoadEvent event) {
PermissionsDefaults.registerBackDefaultFor(event.getWorld());
ess.getJails().onReload();
ess.getWarps().reloadConfig();
for (IConf iConf : ((Essentials) ess).confList) {
for (final IConf iConf : ((Essentials) ess).confList) {
if (iConf instanceof IEssentialsModule) {
iConf.reloadConfig();
}
@@ -889,7 +1063,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
public void onWorldUnload(final WorldUnloadEvent event) {
ess.getJails().onReload();
ess.getWarps().reloadConfig();
for (IConf iConf : ((Essentials) ess).confList) {
for (final IConf iConf : ((Essentials) ess).confList) {
if (iConf instanceof IEssentialsModule) {
iConf.reloadConfig();
}
@@ -1,9 +1,9 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import net.ess3.api.IEssentials;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
@@ -15,7 +15,6 @@ import org.bukkit.inventory.ItemStack;
import java.util.Locale;
public class EssentialsBlockListener implements Listener {
private final transient IEssentials ess;
@@ -28,15 +27,16 @@ public class EssentialsBlockListener implements Listener {
// Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663
final ItemStack is = LocationUtil.convertBlockToItem(event.getBlockPlaced());
if (is == null) {
return;
}
if (is.getType() == Material.MOB_SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == Material.MOB_SPAWNER) {
if (is.getType() == MaterialUtil.SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == MaterialUtil.SPAWNER) {
final BlockState blockState = event.getBlockPlaced().getState();
if (blockState instanceof CreatureSpawner) {
final CreatureSpawner spawner = (CreatureSpawner) blockState;
final EntityType type = ess.getSpawnerProvider().getEntityType(event.getItemInHand());
final EntityType type = ess.getSpawnerItemProvider().getEntityType(event.getItemInHand());
if (type != null && Mob.fromBukkitType(type) != null) {
if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + Mob.fromBukkitType(type).name().toLowerCase(Locale.ENGLISH))) {
spawner.setSpawnedType(type);
@@ -55,6 +55,7 @@ public class EssentialsBlockListener implements Listener {
user.getBase().updateInventory();
}
}
ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask());
}
}
@@ -2,8 +2,11 @@ package com.earth2me.essentials;
import com.google.common.io.Files;
import net.ess3.api.InvalidWorldException;
import org.bukkit.*;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -11,15 +14,30 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -31,23 +49,33 @@ import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsConf extends YamlConfiguration {
protected static final Logger LOGGER = Logger.getLogger("Essentials");
protected final File configFile;
protected String templateName = null;
protected static final Charset UTF8 = Charset.forName("UTF-8");
private Class<?> resourceClass = EssentialsConf.class;
protected static final Charset UTF8 = StandardCharsets.UTF_8;
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
protected final File configFile;
private final AtomicInteger pendingDiskWrites = new AtomicInteger(0);
private final AtomicBoolean transaction = new AtomicBoolean(false);
private final byte[] bytebuffer = new byte[1024];
protected String templateName = null;
private Class<?> resourceClass = EssentialsConf.class;
public EssentialsConf(final File configFile) {
super();
this.configFile = configFile.getAbsoluteFile();
}
private final byte[] bytebuffer = new byte[1024];
public static BigDecimal toBigDecimal(final String input, final BigDecimal def) {
if (input == null || input.isEmpty()) {
return def;
} else {
try {
return new BigDecimal(input, MathContext.DECIMAL128);
} catch (final NumberFormatException | ArithmeticException e) {
return def;
}
}
}
public synchronized void load() {
if (pendingDiskWrites.get() != 0) {
@@ -68,16 +96,16 @@ public class EssentialsConf extends YamlConfiguration {
input.close();
configFile.delete();
}
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
try {
input.close();
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
} catch (FileNotFoundException ex) {
} catch (final FileNotFoundException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
@@ -95,10 +123,9 @@ public class EssentialsConf extends YamlConfiguration {
}
}
try {
try (FileInputStream inputStream = new FileInputStream(configFile)) {
long startSize = configFile.length();
try (final FileInputStream inputStream = new FileInputStream(configFile)) {
final long startSize = configFile.length();
if (startSize > Integer.MAX_VALUE) {
throw new InvalidConfigurationException("File too big");
}
@@ -106,22 +133,23 @@ public class EssentialsConf extends YamlConfiguration {
int length;
while ((length = inputStream.read(bytebuffer)) != -1) {
if (length > buffer.remaining()) {
ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining());
int resizePosition = buffer.position();
buffer.rewind();
final ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining());
final int resizePosition = buffer.position();
// Fix builds compiled against Java 9+ breaking on Java 8
((Buffer) buffer).rewind();
resize.put(buffer);
resize.position(resizePosition);
buffer = resize;
}
buffer.put(bytebuffer, 0, length);
}
buffer.rewind();
((Buffer) buffer).rewind();
final CharBuffer data = CharBuffer.allocate(buffer.capacity());
CharsetDecoder decoder = UTF8.newDecoder();
CoderResult result = decoder.decode(buffer, data, true);
if (result.isError()) {
buffer.rewind();
data.clear();
((Buffer) buffer).rewind();
((Buffer) data).clear();
LOGGER.log(Level.INFO, "File " + configFile.getAbsolutePath() + " is not utf-8 encoded, trying " + Charset.defaultCharset().displayName());
decoder = Charset.defaultCharset().newDecoder();
result = decoder.decode(buffer, data, true);
@@ -134,13 +162,13 @@ public class EssentialsConf extends YamlConfiguration {
decoder.flush(data);
}
final int end = data.position();
data.rewind();
((Buffer) data).rewind();
super.loadFromString(data.subSequence(0, end).toString());
}
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
} catch (InvalidConfigurationException ex) {
File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis());
} catch (final InvalidConfigurationException ex) {
final File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis());
configFile.renameTo(broken);
LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause());
}
@@ -172,28 +200,28 @@ public class EssentialsConf extends YamlConfiguration {
return;
}
ostr = new FileOutputStream(configFile);
byte[] buffer = new byte[1024];
final byte[] buffer = new byte[1024];
int length = 0;
length = istr.read(buffer);
while (length > 0) {
ostr.write(buffer, 0, length);
length = istr.read(buffer);
}
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex);
} finally {
try {
if (istr != null) {
istr.close();
}
} catch (IOException ex) {
} catch (final IOException ex) {
Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (ostr != null) {
ostr.close();
}
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex);
}
}
@@ -224,7 +252,7 @@ public class EssentialsConf extends YamlConfiguration {
public void save() {
try {
save(configFile);
} catch (IOException ex) {
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -244,11 +272,11 @@ public class EssentialsConf extends YamlConfiguration {
//This needs fixed to discard outstanding save requests.
public synchronized void forceSave() {
try {
Future<?> future = delayedSave(configFile);
final Future<?> future = delayedSave(configFile);
if (future != null) {
future.get();
}
} catch (InterruptedException | ExecutionException ex) {
} catch (final InterruptedException | ExecutionException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -273,60 +301,6 @@ public class EssentialsConf extends YamlConfiguration {
return EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites));
}
private static class WriteRunner implements Runnable {
private final File configFile;
private final String data;
private final AtomicInteger pendingDiskWrites;
private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) {
this.configFile = configFile;
this.data = data;
this.pendingDiskWrites = pendingDiskWrites;
}
@Override
public void run() {
//long startTime = System.nanoTime();
synchronized (configFile) {
if (pendingDiskWrites.get() > 1) {
// Writes can be skipped, because they are stored in a queue (in the executor).
// Only the last is actually written.
pendingDiskWrites.decrementAndGet();
//LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec.");
return;
}
try {
Files.createParentDirs(configFile);
if (!configFile.exists()) {
try {
LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
if (!configFile.createNewFile()) {
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
return;
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
return;
}
}
try (FileOutputStream fos = new FileOutputStream(configFile)) {
try (OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8)) {
writer.write(data);
}
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} finally {
//LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec.");
pendingDiskWrites.decrementAndGet();
}
}
}
}
public boolean hasProperty(final String path) {
return isSet(path);
}
@@ -358,7 +332,7 @@ public class EssentialsConf extends YamlConfiguration {
final ItemStack stack = new ItemStack(Material.valueOf(getString(path + ".type", "AIR")), getInt(path + ".amount", 1), (short) getInt(path + ".damage", 0));
final ConfigurationSection enchants = getConfigurationSection(path + ".enchant");
if (enchants != null) {
for (String enchant : enchants.getKeys(false)) {
for (final String enchant : enchants.getKeys(false)) {
final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH));
if (enchantment == null) {
continue;
@@ -370,8 +344,8 @@ public class EssentialsConf extends YamlConfiguration {
return stack;
/*
* ,
* (byte)getInt(path + ".data", 0)
*/
* (byte)getInt(path + ".data", 0)
*/
}
public void setProperty(final String path, final ItemStack stack) {
@@ -379,10 +353,10 @@ public class EssentialsConf extends YamlConfiguration {
map.put("type", stack.getType().toString());
map.put("amount", stack.getAmount());
map.put("damage", stack.getDurability());
Map<Enchantment, Integer> enchantments = stack.getEnchantments();
final Map<Enchantment, Integer> enchantments = stack.getEnchantments();
if (!enchantments.isEmpty()) {
Map<String, Integer> enchant = new HashMap<>();
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
final Map<String, Integer> enchant = new HashMap<>();
for (final Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue());
}
map.put("enchant", enchant);
@@ -392,15 +366,15 @@ public class EssentialsConf extends YamlConfiguration {
set(path, map);
}
public void setProperty(String path, List object) {
public void setProperty(final String path, final List object) {
set(path, new ArrayList(object));
}
public void setProperty(String path, Map object) {
public void setProperty(final String path, final Map object) {
set(path, new LinkedHashMap(object));
}
public Object getProperty(String path) {
public Object getProperty(final String path) {
return get(path);
}
@@ -408,21 +382,21 @@ public class EssentialsConf extends YamlConfiguration {
set(path, bigDecimal.toString());
}
public void setProperty(String path, Object object) {
public void setProperty(final String path, final Object object) {
set(path, object);
}
public void removeProperty(String path) {
public void removeProperty(final String path) {
set(path, null);
}
@Override
public synchronized Object get(String path) {
public synchronized Object get(final String path) {
return super.get(path);
}
@Override
public synchronized Object get(String path, Object def) {
public synchronized Object get(final String path, final Object def) {
return super.get(path, def);
}
@@ -431,52 +405,38 @@ public class EssentialsConf extends YamlConfiguration {
return toBigDecimal(input, def);
}
public static BigDecimal toBigDecimal(final String input, final BigDecimal def) {
if (input == null || input.isEmpty()) {
return def;
} else {
try {
return new BigDecimal(input, MathContext.DECIMAL128);
} catch (NumberFormatException e) {
return def;
} catch (ArithmeticException e) {
return def;
}
}
}
@Override
public synchronized boolean getBoolean(String path) {
public synchronized boolean getBoolean(final String path) {
return super.getBoolean(path);
}
@Override
public synchronized boolean getBoolean(String path, boolean def) {
public synchronized boolean getBoolean(final String path, final boolean def) {
return super.getBoolean(path, def);
}
@Override
public synchronized List<Boolean> getBooleanList(String path) {
public synchronized List<Boolean> getBooleanList(final String path) {
return super.getBooleanList(path);
}
@Override
public synchronized List<Byte> getByteList(String path) {
public synchronized List<Byte> getByteList(final String path) {
return super.getByteList(path);
}
@Override
public synchronized List<Character> getCharacterList(String path) {
public synchronized List<Character> getCharacterList(final String path) {
return super.getCharacterList(path);
}
@Override
public synchronized ConfigurationSection getConfigurationSection(String path) {
public synchronized ConfigurationSection getConfigurationSection(final String path) {
return super.getConfigurationSection(path);
}
@Override
public synchronized double getDouble(String path) {
public synchronized double getDouble(final String path) {
return super.getDouble(path);
}
@@ -486,52 +446,52 @@ public class EssentialsConf extends YamlConfiguration {
}
@Override
public synchronized List<Double> getDoubleList(String path) {
public synchronized List<Double> getDoubleList(final String path) {
return super.getDoubleList(path);
}
@Override
public synchronized List<Float> getFloatList(String path) {
public synchronized List<Float> getFloatList(final String path) {
return super.getFloatList(path);
}
@Override
public synchronized int getInt(String path) {
public synchronized int getInt(final String path) {
return super.getInt(path);
}
@Override
public synchronized int getInt(String path, int def) {
public synchronized int getInt(final String path, final int def) {
return super.getInt(path, def);
}
@Override
public synchronized List<Integer> getIntegerList(String path) {
public synchronized List<Integer> getIntegerList(final String path) {
return super.getIntegerList(path);
}
@Override
public synchronized ItemStack getItemStack(String path, ItemStack def) {
public synchronized ItemStack getItemStack(final String path, final ItemStack def) {
return super.getItemStack(path, def);
}
@Override
public synchronized Set<String> getKeys(boolean deep) {
public synchronized Set<String> getKeys(final boolean deep) {
return super.getKeys(deep);
}
@Override
public synchronized List<?> getList(String path) {
public synchronized List<?> getList(final String path) {
return super.getList(path);
}
@Override
public synchronized List<?> getList(String path, List<?> def) {
public synchronized List<?> getList(final String path, final List<?> def) {
return super.getList(path, def);
}
@Override
public synchronized long getLong(String path) {
public synchronized long getLong(final String path) {
return super.getLong(path);
}
@@ -541,7 +501,7 @@ public class EssentialsConf extends YamlConfiguration {
}
@Override
public synchronized List<Long> getLongList(String path) {
public synchronized List<Long> getLongList(final String path) {
return super.getLongList(path);
}
@@ -550,112 +510,165 @@ public class EssentialsConf extends YamlConfiguration {
}
@Override
public synchronized List<Map<?, ?>> getMapList(String path) {
public synchronized List<Map<?, ?>> getMapList(final String path) {
return super.getMapList(path);
}
@Override
public synchronized OfflinePlayer getOfflinePlayer(String path) {
public synchronized OfflinePlayer getOfflinePlayer(final String path) {
return super.getOfflinePlayer(path);
}
@Override
public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) {
public synchronized OfflinePlayer getOfflinePlayer(final String path, final OfflinePlayer def) {
return super.getOfflinePlayer(path, def);
}
@Override
public synchronized List<Short> getShortList(String path) {
public synchronized List<Short> getShortList(final String path) {
return super.getShortList(path);
}
@Override
public synchronized String getString(String path) {
public synchronized String getString(final String path) {
return super.getString(path);
}
@Override
public synchronized String getString(String path, String def) {
public synchronized String getString(final String path, final String def) {
return super.getString(path, def);
}
@Override
public synchronized List<String> getStringList(String path) {
public synchronized List<String> getStringList(final String path) {
return super.getStringList(path);
}
@Override
public synchronized Map<String, Object> getValues(boolean deep) {
public synchronized Map<String, Object> getValues(final boolean deep) {
return super.getValues(deep);
}
@Override
public synchronized Vector getVector(String path) {
public synchronized Vector getVector(final String path) {
return super.getVector(path);
}
@Override
public synchronized Vector getVector(String path, Vector def) {
public synchronized Vector getVector(final String path, final Vector def) {
return super.getVector(path, def);
}
@Override
public synchronized boolean isBoolean(String path) {
public synchronized boolean isBoolean(final String path) {
return super.isBoolean(path);
}
@Override
public synchronized boolean isConfigurationSection(String path) {
public synchronized boolean isConfigurationSection(final String path) {
return super.isConfigurationSection(path);
}
@Override
public synchronized boolean isDouble(String path) {
public synchronized boolean isDouble(final String path) {
return super.isDouble(path);
}
@Override
public synchronized boolean isInt(String path) {
public synchronized boolean isInt(final String path) {
return super.isInt(path);
}
@Override
public synchronized boolean isItemStack(String path) {
public synchronized boolean isItemStack(final String path) {
return super.isItemStack(path);
}
@Override
public synchronized boolean isList(String path) {
public synchronized boolean isList(final String path) {
return super.isList(path);
}
@Override
public synchronized boolean isLong(String path) {
public synchronized boolean isLong(final String path) {
return super.isLong(path);
}
@Override
public synchronized boolean isOfflinePlayer(String path) {
public synchronized boolean isOfflinePlayer(final String path) {
return super.isOfflinePlayer(path);
}
@Override
public synchronized boolean isSet(String path) {
public synchronized boolean isSet(final String path) {
return super.isSet(path);
}
@Override
public synchronized boolean isString(String path) {
public synchronized boolean isString(final String path) {
return super.isString(path);
}
@Override
public synchronized boolean isVector(String path) {
public synchronized boolean isVector(final String path) {
return super.isVector(path);
}
@Override
public synchronized void set(String path, Object value) {
public synchronized void set(final String path, final Object value) {
super.set(path, value);
}
private static final class WriteRunner implements Runnable {
private final File configFile;
private final String data;
private final AtomicInteger pendingDiskWrites;
private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) {
this.configFile = configFile;
this.data = data;
this.pendingDiskWrites = pendingDiskWrites;
}
@Override
public void run() {
//long startTime = System.nanoTime();
synchronized (configFile) {
if (pendingDiskWrites.get() > 1) {
// Writes can be skipped, because they are stored in a queue (in the executor).
// Only the last is actually written.
pendingDiskWrites.decrementAndGet();
//LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec.");
return;
}
try {
Files.createParentDirs(configFile);
if (!configFile.exists()) {
try {
LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
if (!configFile.createNewFile()) {
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
return;
}
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
return;
}
}
try (final FileOutputStream fos = new FileOutputStream(configFile)) {
try (final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8)) {
writer.write(data);
}
}
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} finally {
//LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec.");
pendingDiskWrites.decrementAndGet();
}
}
}
}
}
@@ -1,13 +1,30 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
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.EntityCombustByEntityEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.inventory.ItemStack;
import java.util.List;
@@ -17,13 +34,12 @@ import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsEntityListener implements Listener {
private static final Logger LOGGER = Logger.getLogger("Essentials");
private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}");
private final IEssentials ess;
public EssentialsEntityListener(IEssentials ess) {
public EssentialsEntityListener(final IEssentials ess) {
this.ess = ess;
}
@@ -39,7 +55,7 @@ public class EssentialsEntityListener implements Listener {
} else if (eDefend instanceof Ageable) {
final ItemStack hand = attacker.getBase().getItemInHand();
if (ess.getSettings().isMilkBucketEasterEggEnabled()
&& hand != null && hand.getType() == Material.MILK_BUCKET) {
&& hand != null && hand.getType() == Material.MILK_BUCKET) {
((Ageable) eDefend).setBaby();
hand.setType(Material.BUCKET);
attacker.getBase().setItemInHand(hand);
@@ -92,10 +108,11 @@ public class EssentialsEntityListener implements Listener {
class PowerToolInteractTask implements Runnable {
@Override
public void run() {
attacker.getServer().dispatchCommand(attacker.getBase(), command);
attacker.getBase().chat("/" + command);
LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command));
}
}
ess.scheduleSyncDelayedTask(new PowerToolInteractTask());
event.setCancelled(true);
@@ -124,10 +141,14 @@ public class EssentialsEntityListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityCombustByEntity(final EntityCombustByEntityEvent event) {
if (event.getCombuster() instanceof Arrow) {
Arrow combuster = (Arrow) event.getCombuster();
if (event.getCombuster() instanceof Arrow && event.getEntity() instanceof Player) {
final Arrow combuster = (Arrow) event.getCombuster();
if (combuster.getShooter() instanceof Player) {
final User srcCombuster = ess.getUser(((Player) combuster.getShooter()).getUniqueId());
final Player shooter = (Player) combuster.getShooter();
if (shooter.hasMetadata("NPC")) {
return;
}
final User srcCombuster = ess.getUser(shooter.getUniqueId());
if (srcCombuster.isGodModeEnabled() && !srcCombuster.isAuthorized("essentials.god.pvp")) {
event.setCancelled(true);
}
@@ -140,7 +161,15 @@ public class EssentialsEntityListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerDeathEvent(final PlayerDeathEvent event) {
final Entity entity = event.getEntity();
if (entity.hasMetadata("NPC")) {
return;
}
final User user = ess.getUser(event.getEntity());
if (ess.getSettings().infoAfterDeath()) {
final Location loc = user.getLocation();
user.sendMessage(tl("infoAfterDeath", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) {
user.setLastLocation();
user.sendMessage(tl("backAfterDeath"));
@@ -159,6 +188,66 @@ public class EssentialsEntityListener implements Listener {
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeathInvEvent(final PlayerDeathEvent event) {
final User user = ess.getUser(event.getEntity());
if (user.isAuthorized("essentials.keepinv")) {
event.setKeepInventory(true);
event.getDrops().clear();
final ISettings.KeepInvPolicy vanish = ess.getSettings().getVanishingItemsPolicy();
final ISettings.KeepInvPolicy bind = ess.getSettings().getBindingItemsPolicy();
if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_11_2_R01) && (vanish != ISettings.KeepInvPolicy.KEEP || bind != ISettings.KeepInvPolicy.KEEP)) {
for (final ItemStack stack : event.getEntity().getInventory()) {
if (stack != null) {
if (stack.getEnchantments().containsKey(Enchantment.VANISHING_CURSE)) {
if (vanish == ISettings.KeepInvPolicy.DELETE) {
event.getEntity().getInventory().remove(stack);
} else if (vanish == ISettings.KeepInvPolicy.DROP) {
event.getDrops().add(stack);
event.getEntity().getInventory().remove(stack);
}
}
if (stack.getEnchantments().containsKey(Enchantment.BINDING_CURSE)) {
if (bind == ISettings.KeepInvPolicy.DELETE) {
event.getEntity().getInventory().remove(stack);
} else if (bind == ISettings.KeepInvPolicy.DROP) {
event.getEntity().getInventory().remove(stack);
event.getDrops().add(stack);
}
}
}
}
final ItemStack[] armor = event.getEntity().getInventory().getArmorContents();
for (int i = 0; i < armor.length; i++) {
final ItemStack stack = armor[i];
if (stack != null) {
if (stack.getEnchantments().containsKey(Enchantment.VANISHING_CURSE)) {
if (vanish == ISettings.KeepInvPolicy.DELETE) {
armor[i] = null;
} else if (vanish == ISettings.KeepInvPolicy.DROP) {
if (!event.getDrops().contains(stack)) {
event.getDrops().add(stack);
}
armor[i] = null;
}
}
if (stack.getEnchantments().containsKey(Enchantment.BINDING_CURSE)) {
if (bind == ISettings.KeepInvPolicy.DELETE) {
armor[i] = null;
} else if (bind == ISettings.KeepInvPolicy.DROP) {
if (!event.getDrops().contains(stack)) {
event.getDrops().add(stack);
}
armor[i] = null;
}
}
}
}
event.getEntity().getInventory().setArmorContents(armor);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onFoodLevelChange(final FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
@@ -182,7 +271,7 @@ public class EssentialsEntityListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPotionSplashEvent(final PotionSplashEvent event) {
for (LivingEntity entity : event.getAffectedEntities()) {
for (final LivingEntity entity : event.getAffectedEntities()) {
if (entity instanceof Player && ess.getUser((Player) entity).isGodModeEnabled()) {
event.setIntensity(entity, 0d);
}
@@ -190,7 +279,7 @@ public class EssentialsEntityListener implements Listener {
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityShootBow(EntityShootBowEvent event) {
public void onEntityShootBow(final EntityShootBowEvent event) {
if (event.getEntity() instanceof Player) {
final User user = ess.getUser((Player) event.getEntity());
if (user.isAfk()) {
@@ -200,7 +289,7 @@ public class EssentialsEntityListener implements Listener {
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityTarget(EntityTargetEvent event) {
public void onEntityTarget(final EntityTargetEvent event) {
if (event.getTarget() instanceof Player) {
final User user = ess.getUser((Player) event.getTarget());
if (user.isVanished()) {
@@ -1,19 +1,23 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.Commandfireball;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.VersionUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.BanEntry;
import org.bukkit.BanList;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
@@ -24,8 +28,21 @@ import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.*;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
@@ -33,20 +50,23 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsPlayerListener implements Listener {
private static final Logger LOGGER = Logger.getLogger("Essentials");
private final transient IEssentials ess;
@@ -55,12 +75,48 @@ public class EssentialsPlayerListener implements Listener {
this.ess = parent;
}
private static boolean isEntityPickupEvent() {
try {
Class.forName("org.bukkit.event.entity.EntityPickupItemEvent");
return true;
} catch (final ClassNotFoundException ignored) {
return false;
}
}
private static boolean isCommandSendEvent() {
try {
Class.forName("org.bukkit.event.player.PlayerCommandSendEvent");
return true;
} catch (final ClassNotFoundException ignored) {
return false;
}
}
private static boolean isArrowPickupEvent() {
try {
Class.forName("org.bukkit.event.player.PlayerPickupArrowEvent");
return true;
} catch (final ClassNotFoundException ignored) {
return false;
}
}
public void registerEvents() {
ess.getServer().getPluginManager().registerEvents(this, ess);
if (ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_12_R1)) {
ess.getServer().getPluginManager().registerEvents(new PlayerListenerPre1_12(), ess);
if (isArrowPickupEvent()) {
ess.getServer().getPluginManager().registerEvents(new ArrowPickupListener(), ess);
}
if (isEntityPickupEvent()) {
ess.getServer().getPluginManager().registerEvents(new PickupListener1_12(), ess);
} else {
ess.getServer().getPluginManager().registerEvents(new PlayerListener1_12(), ess);
ess.getServer().getPluginManager().registerEvents(new PickupListenerPre1_12(), ess);
}
if (isCommandSendEvent()) {
ess.getServer().getPluginManager().registerEvents(new CommandSendListener(), ess);
}
}
@@ -80,7 +136,14 @@ public class EssentialsPlayerListener implements Listener {
final User user = ess.getUser(event.getPlayer());
if (user.isMuted()) {
event.setCancelled(true);
user.sendMessage(tl("voiceSilenced"));
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) {
user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced"));
} else {
user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
}
LOGGER.info(tl("mutedUserSpeaks", user.getName(), event.getMessage()));
}
try {
@@ -91,7 +154,7 @@ public class EssentialsPlayerListener implements Listener {
it.remove();
}
}
} catch (UnsupportedOperationException ex) {
} catch (final UnsupportedOperationException ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Ignore could not block chat due to custom chat plugin event.", ex);
} else {
@@ -133,26 +196,32 @@ public class EssentialsPlayerListener implements Listener {
to.setZ(from.getZ());
try {
event.setTo(LocationUtil.getSafeDestination(to));
} catch (Exception ex) {
} catch (final Exception ex) {
event.setTo(to);
}
return;
}
final Location afk = user.getAfkPosition();
if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) {
user.updateActivityOnMove(true);
}
final Location afk = user.getAfkPosition();
if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) {
user.updateActivityOnMove(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerQuit(final PlayerQuitEvent event) {
final User user = ess.getUser(event.getPlayer());
if (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit")) {
if (hideJoinQuitMessages() || (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit"))) {
event.setQuitMessage(null);
} else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) {
final Player player = event.getPlayer();
event.setQuitMessage(ess.getSettings().getCustomQuitMessage().replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName()));
final String msg = ess.getSettings().getCustomQuitMessage()
.replace("{PLAYER}", player.getDisplayName())
.replace("{USERNAME}", player.getName())
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()))
.replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()));
event.setQuitMessage(msg.isEmpty() ? null : msg);
}
user.startTransaction();
@@ -167,16 +236,17 @@ public class EssentialsPlayerListener implements Listener {
user.getBase().getOpenInventory().getTopInventory().clear();
}
for (HumanEntity viewer : user.getBase().getInventory().getViewers()) {
final ArrayList<HumanEntity> viewers = new ArrayList<>(user.getBase().getInventory().getViewers());
for (final HumanEntity viewer : viewers) {
if (viewer instanceof Player) {
User uviewer = ess.getUser((Player) viewer);
final User uviewer = ess.getUser((Player) viewer);
if (uviewer.isInvSee()) {
uviewer.getBase().closeInventory();
}
}
}
user.updateActivityOnInteract(false);
user.updateActivity(false, AfkStatusChangeEvent.Cause.QUIT);
if (!user.isHidden()) {
user.setLastLogout(System.currentTimeMillis());
}
@@ -188,17 +258,17 @@ public class EssentialsPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event) {
final String joinMessage = event.getJoinMessage();
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
delayedJoin(event.getPlayer(), joinMessage);
}
});
if (ess.getSettings().allowSilentJoinQuit() || ess.getSettings().isCustomJoinMessage()) {
ess.runTaskAsynchronously(() -> delayedJoin(event.getPlayer(), joinMessage));
if (hideJoinQuitMessages() || ess.getSettings().allowSilentJoinQuit() || ess.getSettings().isCustomJoinMessage()) {
event.setJoinMessage(null);
}
}
private boolean hideJoinQuitMessages() {
return ess.getSettings().hasJoinQuitMessagePlayerCount() && ess.getServer().getOnlinePlayers().size() > ess.getSettings().getJoinQuitMessagePlayerCount();
}
public void delayedJoin(final Player player, final String message) {
if (!player.isOnline()) {
return;
@@ -214,7 +284,7 @@ public class EssentialsPlayerListener implements Listener {
final long currentTime = System.currentTimeMillis();
dUser.checkMuteTimeout(currentTime);
dUser.updateActivityOnInteract(false);
dUser.updateActivity(false, AfkStatusChangeEvent.Cause.JOIN);
dUser.stopTransaction();
class DelayJoinTask implements Runnable {
@@ -234,8 +304,8 @@ public class EssentialsPlayerListener implements Listener {
updateCompass(user);
if (!ess.getVanishedPlayersNew().isEmpty() && !user.isAuthorized("essentials.vanish.see")) {
for (String p : ess.getVanishedPlayersNew()) {
Player toVanish = ess.getServer().getPlayerExact(p);
for (final String p : ess.getVanishedPlayersNew()) {
final Player toVanish = ess.getServer().getPlayerExact(p);
if (toVanish != null && toVanish.isOnline()) {
user.getBase().hidePlayer(toVanish);
if (ess.getSettings().isDebug()) {
@@ -253,19 +323,23 @@ public class EssentialsPlayerListener implements Listener {
if (user.isAuthorized("essentials.silentjoin.vanish")) {
user.setVanished(true);
}
} else if (message == null) {
} else if (message == null || hideJoinQuitMessages()) {
//NOOP
} else if (ess.getSettings().isCustomJoinMessage()) {
String msg = ess.getSettings().getCustomJoinMessage()
final String msg = ess.getSettings().getCustomJoinMessage()
.replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())
.replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers()));
ess.getServer().broadcastMessage(msg);
.replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers()))
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()))
.replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()));
if (!msg.isEmpty()) {
ess.getServer().broadcastMessage(msg);
}
} else if (ess.getSettings().allowSilentJoinQuit()) {
ess.getServer().broadcastMessage(message);
}
int motdDelay = ess.getSettings().getMotdDelay() / 50;
DelayMotdTask motdTask = new DelayMotdTask(user);
final int motdDelay = ess.getSettings().getMotdDelay() / 50;
final DelayMotdTask motdTask = new DelayMotdTask(user);
if (motdDelay > 0) {
ess.scheduleSyncDelayedTask(motdTask, motdDelay);
} else {
@@ -309,13 +383,16 @@ public class EssentialsPlayerListener implements Listener {
ess.getLogger().log(Level.INFO, "Set god mode to false for {0} because they had it enabled without permission.", user.getName());
}
user.setConfirmingClearCommand(null);
user.getConfirmingPayments().clear();
user.stopTransaction();
}
class DelayMotdTask implements Runnable {
private User user;
private final User user;
public DelayMotdTask(User user) {
DelayMotdTask(final User user) {
this.user = user;
}
@@ -326,7 +403,7 @@ public class EssentialsPlayerListener implements Listener {
if (!ess.getSettings().isCommandDisabled("motd")) {
try {
tempInput = new TextInput(user.getSource(), "motd", true, ess);
} catch (IOException ex) {
} catch (final IOException ex) {
if (ess.getSettings().isDebug()) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
} else {
@@ -350,54 +427,52 @@ public class EssentialsPlayerListener implements Listener {
}
// Makes the compass item ingame always point to the first essentials home. #EasterEgg
// EssentialsX: This can now optionally require a permission to enable, if set in the config.
private void updateCompass(final User user) {
Location loc = user.getHome(user.getLocation());
if (ess.getSettings().isCompassTowardsHomePerm() && !user.isAuthorized("essentials.home.compass")) return;
final Location loc = user.getHome(user.getLocation());
if (loc == null) {
loc = user.getBase().getBedSpawnLocation();
}
if (loc != null) {
user.getBase().setCompassTarget(loc);
PaperLib.getBedSpawnLocationAsync(user.getBase(), false).thenAccept(location -> {
if (location != null) {
user.getBase().setCompassTarget(location);
}
});
return;
}
user.getBase().setCompassTarget(loc);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLoginBanned(final PlayerLoginEvent event) {
switch (event.getResult()) {
case KICK_BANNED:
BanEntry banEntry = ess.getServer().getBanList(BanList.Type.NAME).getBanEntry(event.getPlayer().getName());
if (banEntry != null) {
Date banExpiry = banEntry.getExpiration();
if (banExpiry != null) {
String expiry = DateUtil.formatDateDiff(banExpiry.getTime());
event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason()));
} else {
event.setKickMessage(tl("banJoin", banEntry.getReason()));
}
if (event.getResult() == Result.KICK_BANNED) {
BanEntry banEntry = ess.getServer().getBanList(BanList.Type.NAME).getBanEntry(event.getPlayer().getName());
if (banEntry != null) {
final Date banExpiry = banEntry.getExpiration();
if (banExpiry != null) {
final String expiry = DateUtil.formatDateDiff(banExpiry.getTime());
event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason()));
} else {
banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress());
if (banEntry != null) {
event.setKickMessage(tl("banIpJoin", banEntry.getReason()));
}
event.setKickMessage(tl("banJoin", banEntry.getReason()));
}
break;
default:
break;
} else {
banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress());
if (banEntry != null) {
event.setKickMessage(tl("banIpJoin", banEntry.getReason()));
}
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerLogin(final PlayerLoginEvent event) {
switch (event.getResult()) {
case KICK_FULL:
final User kfuser = ess.getUser(event.getPlayer());
if (kfuser.isAuthorized("essentials.joinfullserver")) {
event.allow();
return;
}
event.disallow(Result.KICK_FULL, tl("serverFull"));
break;
default:
break;
if (event.getResult() == Result.KICK_FULL) {
final User kfuser = ess.getUser(event.getPlayer());
if (kfuser.isAuthorized("essentials.joinfullserver")) {
event.allow();
return;
}
event.disallow(Result.KICK_FULL, tl("serverFull"));
}
}
@@ -406,9 +481,13 @@ public class EssentialsPlayerListener implements Listener {
final boolean backListener = ess.getSettings().registerBackInListener();
final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability();
if (backListener || teleportInvulnerability) {
final User user = ess.getUser(event.getPlayer());
final Player player = event.getPlayer();
if (player.hasMetadata("NPC")) {
return;
}
final User user = ess.getUser(player);
//There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports.
if (backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) {
if (user.isAuthorized("essentials.back.onteleport") && backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) {
user.setLastLocation();
}
if (teleportInvulnerability && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) {
@@ -432,12 +511,7 @@ public class EssentialsPlayerListener implements Listener {
final User user = ess.getUser(event.getPlayer());
if (user.hasUnlimited(new ItemStack(event.getBucket()))) {
event.getItemStack().setType(event.getBucket());
ess.scheduleSyncDelayedTask(new Runnable() {
@Override
public void run() {
user.getBase().updateInventory();
}
});
ess.scheduleSyncDelayedTask(user.getBase()::updateInventory);
}
}
@@ -446,19 +520,18 @@ public class EssentialsPlayerListener implements Listener {
final Player player = event.getPlayer();
final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH);
PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd);
final PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd);
if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) {
if (pluginCommand == null
|| (!pluginCommand.getName().equals("msg") && !pluginCommand.getName().equals("r"))) { // /msg and /r are handled in SimpleMessageRecipient
User user = ess.getUser(player);
|| (!pluginCommand.getName().equals("msg") && !pluginCommand.getName().equals("r"))) { // /msg and /r are handled in SimpleMessageRecipient
final User user = ess.getUser(player);
if (!user.isAuthorized("essentials.chat.spy.exempt")) {
for (User spyer : ess.getOnlineUsers()) {
for (final User spyer : ess.getOnlineUsers()) {
if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) {
if (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers()) {
spyer.sendMessage(tl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage());
}
else {
} else {
spyer.sendMessage(tl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage());
}
}
@@ -467,13 +540,19 @@ public class EssentialsPlayerListener implements Listener {
}
}
if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) {
final User user = ess.getUser(player);
if (user.isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) {
event.setCancelled(true);
player.sendMessage(tl("voiceSilenced"));
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) {
player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced"));
} else {
player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
}
LOGGER.info(tl("mutedUserSpeaks", player.getName(), event.getMessage()));
return;
}
boolean broadcast = true; // whether to broadcast the updated activity
boolean update = true; // Only modified when the command is afk
@@ -482,28 +561,30 @@ public class EssentialsPlayerListener implements Listener {
switch (pluginCommand.getName()) {
case "afk":
update = false;
// fall through
case "vanish":
broadcast = false;
break;
}
}
final User user = ess.getUser(player);
if (update) {
user.updateActivityOnInteract(broadcast);
}
if (ess.getSettings().isCommandCooldownsEnabled() && pluginCommand != null
&& !user.isAuthorized("essentials.commandcooldowns.bypass")) {
int argStartIndex = event.getMessage().indexOf(" ");
String args = argStartIndex == -1 ? "" // No arguments present
final int argStartIndex = event.getMessage().indexOf(" ");
final String args = argStartIndex == -1 ? "" // No arguments present
: " " + event.getMessage().substring(argStartIndex); // arguments start at argStartIndex; substring from there.
String fullCommand = pluginCommand.getName() + args;
final String fullCommand = pluginCommand.getName() + args;
// Used to determine whether a user already has an existing cooldown
// If so, no need to check for (and write) new ones.
boolean cooldownFound = false;
// Iterate over a copy of getCommandCooldowns in case of concurrent modifications
for (Entry<Pattern, Long> entry : new HashMap<>(user.getCommandCooldowns()).entrySet()) {
for (final Entry<Pattern, Long> entry : new HashMap<>(user.getCommandCooldowns()).entrySet()) {
// Remove any expired cooldowns
if (entry.getValue() <= System.currentTimeMillis()) {
user.clearCommandCooldown(entry.getKey());
@@ -511,7 +592,7 @@ public class EssentialsPlayerListener implements Listener {
} else if (entry.getKey().matcher(fullCommand).matches()) {
// User's current cooldown hasn't expired, inform and terminate cooldown code.
if (entry.getValue() > System.currentTimeMillis()) {
String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue());
final String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue());
user.sendMessage(tl("commandCooldown", commandCooldownTime));
cooldownFound = true;
event.setCancelled(true);
@@ -521,13 +602,13 @@ public class EssentialsPlayerListener implements Listener {
}
if (!cooldownFound) {
Entry<Pattern, Long> cooldownEntry = ess.getSettings().getCommandCooldownEntry(fullCommand);
final Entry<Pattern, Long> cooldownEntry = ess.getSettings().getCommandCooldownEntry(fullCommand);
if (cooldownEntry != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Applying " + cooldownEntry.getValue() + "ms cooldown on /" + fullCommand + " for" + user.getName() + ".");
}
Date expiry = new Date(System.currentTimeMillis() + cooldownEntry.getValue());
final Date expiry = new Date(System.currentTimeMillis() + cooldownEntry.getValue());
user.addCommandCooldown(cooldownEntry.getKey(), expiry, ess.getSettings().isCommandCooldownPersistent(fullCommand));
}
}
@@ -537,27 +618,31 @@ public class EssentialsPlayerListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChangedWorldFlyReset(final PlayerChangedWorldEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.getBase().getGameMode() != GameMode.CREATIVE
// COMPAT: String compare for 1.7.10
&& !user.getBase().getGameMode().name().equals("SPECTATOR")
&& !user.isAuthorized("essentials.fly")) {
user.getBase().setFallDistance(0f);
user.getBase().setAllowFlight(false);
}
if (!user.isAuthorized("essentials.speed")) {
user.getBase().setFlySpeed(0.1f);
user.getBase().setWalkSpeed(0.2f);
} else {
if (user.getBase().getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass")) {
user.getBase().setFlySpeed((float) ess.getSettings().getMaxFlySpeed());
} else {
user.getBase().setFlySpeed(user.getBase().getFlySpeed() * 0.99999f);
}
if (user.getBase().getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass")) {
user.getBase().setWalkSpeed((float) ess.getSettings().getMaxWalkSpeed());
if (ess.getSettings().isWorldChangeFlyResetEnabled()) {
if (user.getBase().getGameMode() != GameMode.CREATIVE
// COMPAT: String compare for 1.7.10
&& !user.getBase().getGameMode().name().equals("SPECTATOR")
&& !user.isAuthorized("essentials.fly")) {
user.getBase().setFallDistance(0f);
user.getBase().setAllowFlight(false);
}
}
if (ess.getSettings().isWorldChangeSpeedResetEnabled()) {
if (!user.isAuthorized("essentials.speed")) {
user.getBase().setFlySpeed(0.1f);
user.getBase().setWalkSpeed(0.2f);
} else {
user.getBase().setWalkSpeed(user.getBase().getWalkSpeed() * 0.99999f);
if (user.getBase().getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass")) {
user.getBase().setFlySpeed((float) ess.getSettings().getMaxFlySpeed());
} else {
user.getBase().setFlySpeed(user.getBase().getFlySpeed() * 0.99999f);
}
if (user.getBase().getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass")) {
user.getBase().setWalkSpeed((float) ess.getSettings().getMaxWalkSpeed());
}
}
}
}
@@ -584,13 +669,18 @@ public class EssentialsPlayerListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteract(final PlayerInteractEvent event) {
boolean updateActivity = true;
switch (event.getAction()) {
case RIGHT_CLICK_BLOCK:
if (!event.isCancelled() && event.getClickedBlock().getType() == Material.BED_BLOCK && ess.getSettings().getUpdateBedAtDaytime()) {
User player = ess.getUser(event.getPlayer());
if (player.isAuthorized("essentials.sethome.bed")) {
if (!event.isCancelled() && MaterialUtil.isBed(event.getClickedBlock().getType()) && ess.getSettings().getUpdateBedAtDaytime()) {
final User player = ess.getUser(event.getPlayer());
if (player.isAuthorized("essentials.sethome.bed") && player.getWorld().getEnvironment().equals(World.Environment.NORMAL)) {
player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation());
player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()));
// In 1.15 and above, vanilla sends its own bed spawn message.
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) {
player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()));
}
}
}
break;
@@ -602,16 +692,25 @@ public class EssentialsPlayerListener implements Listener {
break;
}
}
// fall through
case LEFT_CLICK_BLOCK:
if (event.getItem() != null && event.getItem().getType() != Material.AIR) {
final User user = ess.getUser(event.getPlayer());
if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getTypeId())) {
if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getType())) {
event.setCancelled(true);
}
}
break;
case PHYSICAL:
updateActivity = false;
break;
default:
break;
}
if (updateActivity) {
ess.getUser(event.getPlayer()).updateActivityOnInteract(true);
}
}
// This method allows the /jump lock feature to work, allows teleporting while flying #EasterEgg
@@ -622,25 +721,26 @@ public class EssentialsPlayerListener implements Listener {
class DelayedClickJumpTask implements Runnable {
@Override
public void run() {
Location loc = user.getLocation();
final Location loc = user.getLocation();
loc.setX(otarget.getX());
loc.setZ(otarget.getZ());
while (LocationUtil.isBlockDamaging(loc.getWorld(), loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())) {
loc.setY(loc.getY() + 1d);
}
user.getBase().teleport(loc, TeleportCause.PLUGIN);
PaperLib.teleportAsync(user.getBase(), loc, TeleportCause.PLUGIN);
}
}
ess.scheduleSyncDelayedTask(new DelayedClickJumpTask());
} catch (Exception ex) {
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
private boolean usePowertools(final User user, final int id) {
final List<String> commandList = user.getPowertool(id);
private boolean usePowertools(final User user, final Material material) {
final List<String> commandList = user.getPowertool(material);
if (commandList == null || commandList.isEmpty()) {
return false;
}
@@ -648,7 +748,6 @@ public class EssentialsPlayerListener implements Listener {
// We need to loop through each command and execute
for (final String command : commandList) {
if (command.contains("{player}")) {
continue;
} else if (command.startsWith("c:")) {
used = true;
user.getBase().chat(command.substring(2));
@@ -658,10 +757,11 @@ public class EssentialsPlayerListener implements Listener {
class PowerToolUseTask implements Runnable {
@Override
public void run() {
user.getServer().dispatchCommand(user.getBase(), command);
user.getBase().chat("/" + command);
LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command));
}
}
ess.scheduleSyncDelayedTask(new PowerToolUseTask());
}
@@ -685,7 +785,7 @@ public class EssentialsPlayerListener implements Listener {
if (type == InventoryType.PLAYER) {
final User user = ess.getUser((Player) event.getWhoClicked());
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity) {
if (invHolder instanceof HumanEntity) {
final User invOwner = ess.getUser((Player) invHolder);
if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify") || invOwner.isAuthorized("essentials.invsee.preventmodify") || !invOwner.getBase().isOnline())) {
event.setCancelled(true);
@@ -694,12 +794,12 @@ public class EssentialsPlayerListener implements Listener {
}
} else if (type == InventoryType.ENDER_CHEST) {
final User user = ess.getUser((Player) event.getWhoClicked());
if (user.isEnderSee() && (!user.isAuthorized("essentials.enderchest.modify"))) {
if (user.isEnderSee() && !user.isAuthorized("essentials.enderchest.modify")) {
event.setCancelled(true);
refreshPlayer = user.getBase();
}
} else if (type == InventoryType.WORKBENCH) {
User user = ess.getUser((Player) event.getWhoClicked());
final User user = ess.getUser((Player) event.getWhoClicked());
if (user.isRecipeSee()) {
event.setCancelled(true);
refreshPlayer = user.getBase();
@@ -707,14 +807,15 @@ public class EssentialsPlayerListener implements Listener {
} else if (type == InventoryType.CHEST && top.getSize() == 9) {
final User user = ess.getUser((Player) event.getWhoClicked());
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity && user.isInvSee()) {
if (invHolder instanceof HumanEntity && user.isInvSee()) {
event.setCancelled(true);
refreshPlayer = user.getBase();
}
} else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER) {
if (ess.getSettings().isDirectHatAllowed() && event.getClick() == ClickType.LEFT && event.getSlot() == 39
&& event.getCursor().getType() != Material.AIR && event.getCursor().getType().getMaxDurability() == 0
&& ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat")) {
&& !MaterialUtil.isSkull(event.getCursor().getType())
&& ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat") && !ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat.prevent-type." + event.getCursor().getType().name().toLowerCase())) {
event.setCancelled(true);
final PlayerInventory inv = (PlayerInventory) clickedInventory;
final ItemStack head = inv.getHelmet();
@@ -724,13 +825,7 @@ public class EssentialsPlayerListener implements Listener {
}
if (refreshPlayer != null) {
final Player player = refreshPlayer;
ess.scheduleSyncDelayedTask(new Runnable() {
@Override
public void run() {
player.updateInventory();
}
}, 1);
ess.scheduleSyncDelayedTask(refreshPlayer::updateInventory, 1);
}
}
@@ -756,7 +851,7 @@ public class EssentialsPlayerListener implements Listener {
}
} else if (type == InventoryType.CHEST && top.getSize() == 9) {
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity) {
if (invHolder instanceof HumanEntity) {
final User user = ess.getUser((Player) event.getPlayer());
user.setInvSee(false);
refreshPlayer = user.getBase();
@@ -764,36 +859,39 @@ public class EssentialsPlayerListener implements Listener {
}
if (refreshPlayer != null) {
final Player player = refreshPlayer;
ess.scheduleSyncDelayedTask(new Runnable() {
@Override
public void run() {
player.updateInventory();
}
}, 1);
ess.scheduleSyncDelayedTask(refreshPlayer::updateInventory, 1);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerFishEvent(final PlayerFishEvent event) {
final User user = ess.getUser(event.getPlayer());
user.updateActivityOnInteract(true);
user.updateActivityOnInteract(true);
}
private final class PlayerListenerPre1_12 implements Listener {
private static final class ArrowPickupListener implements Listener {
@EventHandler(priority = EventPriority.LOW)
public void onArrowPickup(final org.bukkit.event.player.PlayerPickupArrowEvent event) {
if (event.getItem().hasMetadata(Commandfireball.FIREBALL_META_KEY)) {
event.setCancelled(true);
}
}
}
private final class PickupListenerPre1_12 implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerPickupItem(final org.bukkit.event.player.PlayerPickupItemEvent event) {
if (ess.getSettings().getDisableItemPickupWhileAfk()) {
if (event.getItem().hasMetadata(Commandfireball.FIREBALL_META_KEY)) {
event.setCancelled(true);
} else if (ess.getSettings().getDisableItemPickupWhileAfk()) {
if (ess.getUser(event.getPlayer()).isAfk()) {
event.setCancelled(true);
}
}
}
}
private final class PlayerListener1_12 implements Listener {
private final class PickupListener1_12 implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerPickupItem(final org.bukkit.event.entity.EntityPickupItemEvent event) {
if (ess.getSettings().getDisableItemPickupWhileAfk() && event.getEntity() instanceof Player) {
@@ -803,4 +901,46 @@ public class EssentialsPlayerListener implements Listener {
}
}
}
private final class CommandSendListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onCommandSend(final PlayerCommandSendEvent event) {
final User user = ess.getUser(event.getPlayer());
final Set<PluginCommand> checked = new HashSet<>();
final Set<PluginCommand> toRemove = new HashSet<>();
event.getCommands().removeIf(label -> {
if (isEssentialsCommand(label)) {
final PluginCommand command = ess.getServer().getPluginCommand(label);
if (!checked.contains(command)) {
checked.add(command);
if (!user.isAuthorized(command.getName().equals("r") ? "essentials.msg" : "essentials." + command.getName())) {
toRemove.add(command);
}
}
return toRemove.contains(command);
}
return false;
});
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Removed commands: " + toRemove.toString());
}
}
/**
* Returns true if all of the following are true:
* - The command is a plugin command
* - The plugin command is from a plugin in an essentials-controlled package
* - There is no known alternative OR the alternative is overridden by Essentials
*/
private boolean isEssentialsCommand(final String label) {
final PluginCommand command = ess.getServer().getPluginCommand(label);
return command != null
&& (command.getPlugin() == ess || command.getPlugin().getClass().getName().startsWith("com.earth2me.essentials"))
&& (ess.getSettings().isCommandOverridden(label) || (ess.getAlternativeCommandsHandler().getAlternative(label) == null));
}
}
}
@@ -10,7 +10,6 @@ import org.bukkit.event.server.PluginEnableEvent;
import java.util.logging.Level;
public class EssentialsPluginListener implements Listener, IConf {
private final transient IEssentials ess;
@@ -27,7 +26,7 @@ public class EssentialsPluginListener implements Listener, IConf {
ess.getPermissionsHandler().checkPermissions();
ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin());
if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) {
ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")");
ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + Methods.getMethod().getVersion() + ")");
}
}
@@ -36,9 +35,10 @@ public class EssentialsPluginListener implements Listener, IConf {
if (event.getPlugin().getName().equals("EssentialsChat")) {
ess.getSettings().setEssentialsChatActive(false);
}
ess.getPermissionsHandler().checkPermissions();
ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin());
// Check to see if the plugin thats being disabled is the one we are using
if (ess.getPaymentMethod() != null && Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) {
if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) {
Methods.reset();
ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments.");
}
@@ -10,16 +10,22 @@ import org.bukkit.event.server.ServerListPingEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
public class EssentialsServerListener implements Listener {
private static final List<String> ignoredSLPECallers = Arrays.asList(
".LegacyPingHandler.channelRead(", // CB responding to pings from pre-Netty clients
"de.dytanic.cloudnet.bridge.BukkitBootstrap", // CloudNet v2 doing... something
"de.dytanic.cloudnet.ext.bridge.bukkit.BukkitCloudNetBridgePlugin" // CloudNet v3 doing... something else
);
private final transient IEssentials ess;
private final boolean isPaperSample;
private boolean unsupportedLogged = false;
private boolean npeWarned = false;
private boolean isPaperSample;
private Method setSampleText;
private Method getSampleText;
@@ -31,13 +37,13 @@ public class EssentialsServerListener implements Listener {
setSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "setSampleText", List.class);
getSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "getSampleText");
if (setSampleText != null && getSampleText != null) {
ess.getLogger().info("Using Paper 1.12+ ServerListPingEvent methods");
ess.getLogger().info("ServerListPingEvent: Paper 1.12.2 setSampleText API");
isPaperSample = true;
return;
}
}
ess.getLogger().info("Using Spigot 1.7.10+ ServerListPingEvent iterator");
ess.getLogger().info("ServerListPingEvent: Spigot iterator API");
isPaperSample = false;
}
@@ -45,46 +51,66 @@ public class EssentialsServerListener implements Listener {
public void onServerListPing(final ServerListPingEvent event) throws Exception {
if (isPaperSample) {
try {
List<String> playerNames = (List<String>) getSampleText.invoke(event, null);
Iterator<String> iterator = playerNames.iterator();
while (iterator.hasNext()) {
String player = iterator.next();
if (ess.getUser(player).isVanished()) {
iterator.remove();
}
}
final List<String> playerNames = (List<String>) getSampleText.invoke(event, null);
playerNames.removeIf(player -> ess.getUser(player).isVanished());
setSampleText.invoke(event, playerNames);
} catch (IllegalAccessException | InvocationTargetException | ClassCastException e) {
if (!unsupportedLogged) {
} catch (final IllegalAccessException | InvocationTargetException | ClassCastException e) {
if (!unsupportedLogged && shouldWarnSLPECaller(e)) {
ess.getLogger().log(Level.WARNING, "Unable to hide players from server list ping "
+ "using Paper 1.12+ method!", e);
+ "using Paper 1.12 method!", e);
unsupportedLogged = true;
}
} catch (NullPointerException e) {
if (!npeWarned) {
} catch (final NullPointerException e) {
if (!npeWarned && shouldWarnSLPECaller(e)) {
npeWarned = true;
Exception ex = new Exception("A plugin has fired a ServerListPingEvent "
+ "without implementing Paper's methods. Point the author to https://git.io/v7Xzl.");
final Exception ex = new Exception("A plugin has fired a ServerListPingEvent "
+ "without implementing Paper's methods. Point the author to https://git.io/v7Xzl.");
ex.setStackTrace(e.getStackTrace());
throw ex;
}
}
} else {
try {
Iterator<Player> iterator = event.iterator();
final Iterator<Player> iterator = event.iterator();
while (iterator.hasNext()) {
Player player = iterator.next();
final Player player = iterator.next();
if (ess.getUser(player).isVanished()) {
iterator.remove();
}
}
} catch (UnsupportedOperationException e) {
if (!unsupportedLogged) {
ess.getLogger().warning("Current server implementation does not support "
+ "hiding players from server list ping. Update or contact the maintainers.");
} catch (final UnsupportedOperationException e) {
if (!unsupportedLogged && shouldWarnSLPECaller(e)) {
ess.getLogger().log(Level.WARNING, "Could not hide vanished players while handling " + event.getClass().getName(), e);
unsupportedLogged = true;
}
}
}
}
/**
* Should we warn about this SLPE caller, or should we silently ignore it?
* This checks against the ignoredSLPECallers strings, and if it matches one of those, we
* return false.
*
* @param throwable A throwable caught by a catch block
* @return Whether or not to send a warning about this particular caller
*/
private boolean shouldWarnSLPECaller(final Throwable throwable) {
final int maxStackDepth = 20; // Limit the depth when searching through the stack trace
int depth = 0;
for (final StackTraceElement element : throwable.getStackTrace()) {
depth++;
if (depth > maxStackDepth) {
break;
}
for (final String ignoredString : ignoredSLPECallers) {
if (element.toString().contains(ignoredString)) {
return false; // We know about this error and should ignore it, so don't warn
}
}
}
return true; // We don't know for certain that we can ignore this, so warn just to be safe
}
}
@@ -3,19 +3,24 @@ package com.earth2me.essentials;
import net.ess3.api.IEssentials;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
public class EssentialsTimer implements Runnable {
private final transient IEssentials ess;
private final transient Set<UUID> onlineUsers = new HashSet<>(); // Field is necessary for hidden users
private transient long lastPoll = System.nanoTime();
private final LinkedList<Double> history = new LinkedList<>();
@SuppressWarnings("FieldCanBeLocal")
private final long maxTime = 10 * 1000000;
@SuppressWarnings("FieldCanBeLocal")
private final long tickInterval = 50;
private transient long lastPoll = System.nanoTime();
private int skip1 = 0;
private int skip2 = 0;
private final long maxTime = 10 * 1000000;
private final long tickInterval = 50;
EssentialsTimer(final IEssentials ess) {
this.ess = ess;
@@ -33,13 +38,13 @@ public class EssentialsTimer implements Runnable {
if (history.size() > 10) {
history.remove();
}
double tps = tickInterval * 1000000.0 / timeSpent;
final double tps = tickInterval * 1000000.0 / timeSpent;
if (tps <= 21) {
history.add(tps);
}
lastPoll = startTime;
int count = 0;
for (Player player : ess.getOnlinePlayers()) {
for (final Player player : ess.getOnlinePlayers()) {
count++;
if (skip1 > 0) {
skip1--;
@@ -56,7 +61,7 @@ public class EssentialsTimer implements Runnable {
onlineUsers.add(user.getBase().getUniqueId());
user.setLastOnlineActivity(currentTime);
user.checkActivity();
} catch (Exception e) {
} catch (final Exception e) {
ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e);
}
}
@@ -96,7 +101,7 @@ public class EssentialsTimer implements Runnable {
public double getAverageTPS() {
double avg = 0;
for (Double f : history) {
for (final Double f : history) {
if (f != null) {
avg += f;
}
@@ -14,12 +14,29 @@ import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
@@ -27,9 +44,13 @@ import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsUpgrade {
private final static Logger LOGGER = Logger.getLogger("Essentials");
private static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml");
private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$";
private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX);
private static final String PATTERN_CONFIG_NAME_REGEX = "(?mi)^lastAccountName:\\s*[\"\']?(\\w+)[\"\']?\\s*$";
private static final Pattern PATTERN_CONFIG_NAME = Pattern.compile(PATTERN_CONFIG_NAME_REGEX);
private final transient IEssentials ess;
private final transient EssentialsConf doneFile;
@@ -42,24 +63,157 @@ public class EssentialsUpgrade {
doneFile.load();
}
public static void uuidFileConvert(final IEssentials ess, final Boolean ignoreUFCache) {
ess.getLogger().info("Starting Essentials UUID userdata conversion");
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
int countFiles = 0;
int countFails = 0;
int countEssCache = 0;
int countBukkit = 0;
ess.getLogger().info("Found " + userdir.list().length + " files to convert...");
for (final String string : userdir.list()) {
if (!string.endsWith(".yml") || string.length() < 5) {
continue;
}
final int showProgress = countFiles % 250;
if (showProgress == 0) {
ess.getUserMap().getUUIDMap().forceWriteUUIDMap();
ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length);
}
countFiles++;
final String name = string.substring(0, string.length() - 4);
final EssentialsUserConf config;
UUID uuid = null;
try {
uuid = UUID.fromString(name);
} catch (final IllegalArgumentException ex) {
final File file = new File(userdir, string);
final EssentialsConf conf = new EssentialsConf(file);
conf.load();
conf.setProperty("lastAccountName", name);
conf.save();
final String uuidConf = ignoreUFCache ? "force-uuid" : "uuid";
final String uuidString = conf.getString(uuidConf, null);
for (int i = 0; i < 4; i++) {
try {
uuid = UUID.fromString(uuidString);
countEssCache++;
break;
} catch (final Exception ex2) {
if (conf.getBoolean("npc", false)) {
uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8));
break;
}
final org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name);
uuid = player.getUniqueId();
}
if (uuid != null) {
countBukkit++;
break;
}
}
if (uuid != null) {
conf.forceSave();
config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml"));
config.convertLegacyFile();
ess.getUserMap().trackUUID(uuid, name, false);
continue;
}
countFails++;
}
}
ess.getUserMap().getUUIDMap().forceWriteUUIDMap();
ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete.");
ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails);
ess.getLogger().info("To rerun the conversion type /essentials uuidconvert");
}
public void convertIgnoreList() {
final Pattern pattern = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
if (doneFile.getBoolean("updateUsersIgnoreListUUID", false)) {
return;
}
LOGGER.info("Attempting to migrate ignore list to UUIDs");
final File userdataFolder = new File(ess.getDataFolder(), "userdata");
if (!userdataFolder.exists() || !userdataFolder.isDirectory()) {
return;
}
final File[] userFiles = userdataFolder.listFiles();
for (final File file : userFiles) {
if (!file.isFile() || !file.getName().endsWith(".yml")) {
continue;
}
final EssentialsConf config = new EssentialsConf(file);
try {
config.load();
if (config.hasProperty("ignore")) {
final List<String> migratedIgnores = new ArrayList<>();
for (final String name : Collections.synchronizedList(config.getStringList("ignore"))) {
if (name == null) {
continue;
}
if (pattern.matcher(name.trim()).matches()) {
LOGGER.info("Detected already migrated ignore list!");
return;
}
final User user = ess.getOfflineUser(name);
if (user != null && user.getBase() != null) {
migratedIgnores.add(user.getBase().getUniqueId().toString());
}
}
config.removeProperty("ignore");
config.setProperty("ignore", migratedIgnores);
config.forceSave();
}
} catch (final RuntimeException ex) {
LOGGER.log(Level.INFO, "File: " + file.toString());
throw ex;
}
}
doneFile.setProperty("updateUsersIgnoreListUUID", true);
doneFile.save();
LOGGER.info("Done converting ignore list.");
}
public void convertKits() {
Kits kits = ess.getKits();
EssentialsConf config = kits.getConfig();
final Kits kits = ess.getKits();
final EssentialsConf config = kits.getConfig();
if (doneFile.getBoolean("kitsyml", false)) {
return;
}
LOGGER.info("Attempting to convert old kits in config.yml to new kits.yml");
ConfigurationSection section = ess.getSettings().getKitSection();
final ConfigurationSection section = ess.getSettings().getKitSection();
if (section == null) {
LOGGER.info("No kits found to migrate.");
return;
}
Map<String, Object> legacyKits = ess.getSettings().getKitSection().getValues(true);
final Map<String, Object> legacyKits = ess.getSettings().getKitSection().getValues(true);
for (Map.Entry<String, Object> entry : legacyKits.entrySet()) {
for (final Map.Entry<String, Object> entry : legacyKits.entrySet()) {
LOGGER.info("Converting " + entry.getKey());
config.set("kits." + entry.getKey(), entry.getValue());
}
@@ -70,7 +224,7 @@ public class EssentialsUpgrade {
LOGGER.info("Done converting kits.");
}
private void moveMotdRulesToFile(String name) {
private void moveMotdRulesToFile(final String name) {
if (doneFile.getBoolean("move" + name + "ToFile", false)) {
return;
}
@@ -85,26 +239,26 @@ public class EssentialsUpgrade {
}
final EssentialsConf conf = new EssentialsConf(configFile);
conf.load();
List<String> lines = conf.getStringList(name);
final List<String> lines = conf.getStringList(name);
if (lines != null && !lines.isEmpty()) {
if (!file.createNewFile()) {
throw new IOException("Failed to create file " + file);
}
PrintWriter writer = new PrintWriter(file);
final PrintWriter writer = new PrintWriter(file);
for (String line : lines) {
for (final String line : lines) {
writer.println(line);
}
writer.close();
}
doneFile.setProperty("move" + name + "ToFile", true);
doneFile.save();
} catch (IOException e) {
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e);
}
}
private void removeLinesFromConfig(File file, String regex, String info) throws Exception {
private void removeLinesFromConfig(final File file, final String regex, final String info) throws Exception {
boolean needUpdate = false;
final BufferedReader bReader = new BufferedReader(new FileReader(file));
final File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder());
@@ -155,7 +309,7 @@ public class EssentialsUpgrade {
}
final File[] userFiles = userdataFolder.listFiles();
for (File file : userFiles) {
for (final File file : userFiles) {
if (!file.isFile() || !file.getName().endsWith(".yml")) {
continue;
}
@@ -163,20 +317,20 @@ public class EssentialsUpgrade {
try {
config.load();
if (config.hasProperty("powertools")) {
@SuppressWarnings("unchecked") final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false);
final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false);
if (powertools == null) {
continue;
}
for (Map.Entry<String, Object> entry : powertools.entrySet()) {
for (final Map.Entry<String, Object> entry : powertools.entrySet()) {
if (entry.getValue() instanceof String) {
List<String> temp = new ArrayList<>();
final List<String> temp = new ArrayList<>();
temp.add((String) entry.getValue());
powertools.put(entry.getKey(), temp);
}
}
config.forceSave();
}
} catch (RuntimeException ex) {
} catch (final RuntimeException ex) {
LOGGER.log(Level.INFO, "File: " + file.toString());
throw ex;
}
@@ -195,7 +349,7 @@ public class EssentialsUpgrade {
}
final File[] userFiles = userdataFolder.listFiles();
for (File file : userFiles) {
for (final File file : userFiles) {
if (!file.isFile() || !file.getName().endsWith(".yml")) {
continue;
}
@@ -204,20 +358,20 @@ public class EssentialsUpgrade {
config.load();
if (config.hasProperty("home") && config.hasProperty("home.default")) {
@SuppressWarnings("unchecked") final String defworld = (String) config.getProperty("home.default");
final String defworld = (String) config.getProperty("home.default");
final Location defloc = getFakeLocation(config, "home.worlds." + defworld);
if (defloc != null) {
config.setProperty("homes.home", defloc);
}
Set<String> worlds = config.getConfigurationSection("home.worlds").getKeys(false);
final Set<String> worlds = config.getConfigurationSection("home.worlds").getKeys(false);
Location loc;
String worldName;
if (worlds == null) {
continue;
}
for (String world : worlds) {
for (final String world : worlds) {
if (defworld.equalsIgnoreCase(world)) {
continue;
}
@@ -234,7 +388,7 @@ public class EssentialsUpgrade {
config.forceSave();
}
} catch (RuntimeException ex) {
} catch (final RuntimeException ex) {
LOGGER.log(Level.INFO, "File: " + file.toString());
throw ex;
}
@@ -252,7 +406,7 @@ public class EssentialsUpgrade {
return;
}
final File[] listOfFiles = usersFolder.listFiles();
for (File listOfFile : listOfFiles) {
for (final File listOfFile : listOfFiles) {
final String filename = listOfFile.getName();
if (!listOfFile.isFile() || !filename.endsWith(".yml")) {
continue;
@@ -288,12 +442,12 @@ public class EssentialsUpgrade {
return null;
}
public Location getFakeLocation(EssentialsConf config, String path) {
String worldName = config.getString((path != null ? path + "." : "") + "world");
public Location getFakeLocation(final EssentialsConf config, final String path) {
final String worldName = config.getString((path != null ? path + "." : "") + "world");
if (worldName == null || worldName.isEmpty()) {
return null;
}
World world = getFakeWorld(worldName);
final World world = getFakeWorld(worldName);
if (world == null) {
return null;
}
@@ -313,21 +467,21 @@ public class EssentialsUpgrade {
oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24
oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf
MessageDigest digest = ManagedFile.getDigest();
final MessageDigest digest = ManagedFile.getDigest();
final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
final byte[] buffer = new byte[1024];
try (DigestInputStream dis = new DigestInputStream(bis, digest)) {
try (final DigestInputStream dis = new DigestInputStream(bis, digest)) {
while (dis.read(buffer) != -1) {
}
}
BigInteger hash = new BigInteger(1, digest.digest());
final BigInteger hash = new BigInteger(1, digest.digest());
if (oldconfigs.contains(hash) && !file.delete()) {
throw new IOException("Could not delete file " + file.toString());
}
doneFile.setProperty("deleteOldItemsCsv", true);
doneFile.save();
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -345,19 +499,19 @@ public class EssentialsUpgrade {
config.load();
if (!config.hasProperty("spawns")) {
final Spawns spawns = new Spawns();
Set<String> keys = config.getKeys(false);
for (String group : keys) {
Location loc = getFakeLocation(config, group);
final Set<String> keys = config.getKeys(false);
for (final String group : keys) {
final Location loc = getFakeLocation(config, group);
spawns.getSpawns().put(group.toLowerCase(Locale.ENGLISH), loc);
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) {
throw new Exception(tl("fileRenameError", "spawn.yml"));
}
try (PrintWriter writer = new PrintWriter(configFile)) {
try (final PrintWriter writer = new PrintWriter(configFile)) {
new YamlStorageWriter(writer).save(spawns);
}
}
} catch (Exception ex) {
} catch (final Exception ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -377,19 +531,19 @@ public class EssentialsUpgrade {
config.load();
if (!config.hasProperty("jails")) {
final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails();
Set<String> keys = config.getKeys(false);
for (String jailName : keys) {
Location loc = getFakeLocation(config, jailName);
final Set<String> keys = config.getKeys(false);
for (final String jailName : keys) {
final Location loc = getFakeLocation(config, jailName);
jails.getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) {
throw new Exception(tl("fileRenameError", "jail.yml"));
}
try (PrintWriter writer = new PrintWriter(configFile)) {
try (final PrintWriter writer = new PrintWriter(configFile)) {
new YamlStorageWriter(writer).save(jails);
}
}
} catch (Exception ex) {
} catch (final Exception ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -410,7 +564,7 @@ public class EssentialsUpgrade {
return;
}
Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false);
final Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false);
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
@@ -419,7 +573,7 @@ public class EssentialsUpgrade {
int countFiles = 0;
int countReqFiles = 0;
for (String string : userdir.list()) {
for (final String string : userdir.list()) {
if (!string.endsWith(".yml") || string.length() < 5) {
continue;
}
@@ -431,7 +585,7 @@ public class EssentialsUpgrade {
try {
uuid = UUID.fromString(name);
} catch (IllegalArgumentException ex) {
} catch (final IllegalArgumentException ex) {
countReqFiles++;
}
@@ -449,7 +603,7 @@ public class EssentialsUpgrade {
try {
Thread.sleep(15000);
} catch (InterruptedException ex) {
} catch (final InterruptedException ex) {
// NOOP
}
@@ -459,89 +613,6 @@ public class EssentialsUpgrade {
doneFile.save();
}
public static void uuidFileConvert(IEssentials ess, Boolean ignoreUFCache) {
ess.getLogger().info("Starting Essentials UUID userdata conversion");
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
int countFiles = 0;
int countFails = 0;
int countEssCache = 0;
int countBukkit = 0;
ess.getLogger().info("Found " + userdir.list().length + " files to convert...");
for (String string : userdir.list()) {
if (!string.endsWith(".yml") || string.length() < 5) {
continue;
}
final int showProgress = countFiles % 250;
if (showProgress == 0) {
ess.getUserMap().getUUIDMap().forceWriteUUIDMap();
ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length);
}
countFiles++;
String name = string.substring(0, string.length() - 4);
EssentialsUserConf config;
UUID uuid = null;
try {
uuid = UUID.fromString(name);
} catch (IllegalArgumentException ex) {
File file = new File(userdir, string);
EssentialsConf conf = new EssentialsConf(file);
conf.load();
conf.setProperty("lastAccountName", name);
conf.save();
String uuidConf = ignoreUFCache ? "force-uuid" : "uuid";
String uuidString = conf.getString(uuidConf, null);
for (int i = 0; i < 4; i++) {
try {
uuid = UUID.fromString(uuidString);
countEssCache++;
break;
} catch (Exception ex2) {
if (conf.getBoolean("npc", false)) {
uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8));
break;
}
org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name);
uuid = player.getUniqueId();
}
if (uuid != null) {
countBukkit++;
break;
}
}
if (uuid != null) {
conf.forceSave();
config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml"));
config.convertLegacyFile();
ess.getUserMap().trackUUID(uuid, name, false);
continue;
}
countFails++;
}
}
ess.getUserMap().getUUIDMap().forceWriteUUIDMap();
ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete.");
ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails);
ess.getLogger().info("To rerun the conversion type /essentials uuidconvert");
}
public void banFormatChange() {
if (doneFile.getBoolean("banFormatChange", false)) {
return;
@@ -558,7 +629,7 @@ public class EssentialsUpgrade {
ess.getLogger().info("Found " + userdir.list().length + " files to convert...");
for (String string : userdir.list()) {
for (final String string : userdir.list()) {
if (!string.endsWith(".yml") || string.length() < 5) {
continue;
}
@@ -575,11 +646,11 @@ public class EssentialsUpgrade {
conf.load();
String banReason;
Long banTimeout;
long banTimeout;
try {
banReason = conf.getConfigurationSection("ban").getString("reason");
} catch (NullPointerException n) {
} catch (final NullPointerException n) {
banReason = null;
}
@@ -591,7 +662,7 @@ public class EssentialsUpgrade {
} else {
banTimeout = 0L;
}
} catch (NumberFormatException n) {
} catch (final NumberFormatException n) {
banTimeout = 0L;
}
@@ -608,7 +679,7 @@ public class EssentialsUpgrade {
ess.getLogger().info("Ban format update complete.");
}
private void updateBan(String playerName, String banReason, Long banTimeout) {
private void updateBan(final String playerName, final String banReason, final Long banTimeout) {
if (banTimeout == 0) {
Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, null, Console.NAME);
} else {
@@ -616,31 +687,18 @@ public class EssentialsUpgrade {
}
}
private static final FileFilter YML_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".yml");
}
};
private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$";
private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX);
private static final String PATTERN_CONFIG_NAME_REGEX = "(?mi)^lastAccountName:\\s*[\"\']?(\\w+)[\"\']?\\s*$";
private static final Pattern PATTERN_CONFIG_NAME = Pattern.compile(PATTERN_CONFIG_NAME_REGEX);
private void repairUserMap() {
if (doneFile.getBoolean("userMapRepaired", false)) {
return;
}
ess.getLogger().info("Starting usermap repair");
File userdataFolder = new File(ess.getDataFolder(), "userdata");
final File userdataFolder = new File(ess.getDataFolder(), "userdata");
if (!userdataFolder.isDirectory()) {
ess.getLogger().warning("Missing userdata folder, aborting");
return;
}
File[] files = userdataFolder.listFiles(YML_FILTER);
final File[] files = userdataFolder.listFiles(YML_FILTER);
final DecimalFormat format = new DecimalFormat("#0.00");
final Map<String, UUID> names = Maps.newHashMap();
@@ -656,7 +714,7 @@ public class EssentialsUpgrade {
try {
// ".yml" ending has 4 chars...
uuid = UUID.fromString(filename.substring(0, filename.length() - 4));
} catch (IllegalArgumentException ignored) {
} catch (final IllegalArgumentException ignored) {
}
}
@@ -664,7 +722,7 @@ public class EssentialsUpgrade {
if (uuidMatcher.find()) {
try {
uuid = UUID.fromString(uuidMatcher.group(1));
} catch (IllegalArgumentException ignored) {
} catch (final IllegalArgumentException ignored) {
}
}
@@ -683,7 +741,7 @@ public class EssentialsUpgrade {
if (index % 1000 == 0) {
ess.getLogger().info("Reading: " + format.format((100d * (double) index) / files.length)
+ "%");
+ "%");
}
} catch (final IOException e) {
ess.getLogger().log(Level.SEVERE, "Error while reading file: ", e);
@@ -718,5 +776,6 @@ public class EssentialsUpgrade {
banFormatChange();
warnMetrics();
repairUserMap();
convertIgnoreList();
}
}
@@ -10,7 +10,6 @@ import java.util.Locale;
import java.util.UUID;
import java.util.logging.Level;
public class EssentialsUserConf extends EssentialsConf {
public final String username;
public final UUID uuid;
@@ -32,7 +31,7 @@ public class EssentialsUserConf extends EssentialsConf {
final File file = new File(configFile.getParentFile(), username + ".yml");
try {
Files.move(file, new File(configFile.getParentFile(), uuid + ".yml"));
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex);
}
@@ -56,7 +55,7 @@ public class EssentialsUserConf extends EssentialsConf {
public void convertAltFile() {
try {
Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml"));
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex);
}
}
@@ -6,14 +6,12 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ExecuteTimer {
private final transient List<ExecuteRecord> times;
private final transient DecimalFormat decimalFormat = new DecimalFormat("#0.000", DecimalFormatSymbols.getInstance(Locale.US));
public ExecuteTimer() {
times = new ArrayList<ExecuteRecord>();
times = new ArrayList<>();
}
public void start() {
@@ -37,7 +35,7 @@ public class ExecuteTimer {
long time2 = 0;
double duration;
for (ExecuteRecord pair : times) {
for (final ExecuteRecord pair : times) {
mark = pair.getMark();
time2 = pair.getTime();
if (time1 > 0) {
@@ -54,12 +52,11 @@ public class ExecuteTimer {
return output.toString();
}
private static class ExecuteRecord {
private final String mark;
private final long time;
public ExecuteRecord(final String mark, final long time) {
ExecuteRecord(final String mark, final long time) {
this.mark = mark;
this.time = time;
}
@@ -72,4 +69,4 @@ public class ExecuteTimer {
return time;
}
}
}
}
@@ -5,44 +5,68 @@ import net.ess3.api.IEssentials;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class I18n implements net.ess3.api.II18n {
private static I18n instance;
private static final String MESSAGES = "messages";
private final transient Locale defaultLocale = Locale.getDefault();
private transient Locale currentLocale = defaultLocale;
private transient ResourceBundle customBundle;
private transient ResourceBundle localeBundle;
private final transient ResourceBundle defaultBundle;
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
private final transient IEssentials ess;
private static final Pattern NODOUBLEMARK = Pattern.compile("''");
private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() {
public Enumeration<String> getKeys() {
return null;
}
protected Object handleGetObject(String key) {
protected Object handleGetObject(final String key) {
return null;
}
};
private static I18n instance;
private final transient Locale defaultLocale = Locale.getDefault();
private final transient ResourceBundle defaultBundle;
private final transient IEssentials ess;
private transient Locale currentLocale = defaultLocale;
private transient ResourceBundle customBundle;
private transient ResourceBundle localeBundle;
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<>();
public I18n(final IEssentials ess) {
this.ess = ess;
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH, new UTF8PropertiesControl());
localeBundle = defaultBundle;
customBundle = NULL_BUNDLE;
}
public static String tl(final String string, final Object... objects) {
if (instance == null) {
return "";
}
if (objects.length == 0) {
return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'");
} else {
return instance.format(string, objects);
}
}
public static String capitalCase(final String input) {
return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1);
}
public void onEnable() {
instance = this;
}
@@ -60,40 +84,29 @@ public class I18n implements net.ess3.api.II18n {
try {
try {
return customBundle.getString(string);
} catch (MissingResourceException ex) {
} catch (final MissingResourceException ex) {
return localeBundle.getString(string);
}
} catch (MissingResourceException ex) {
} catch (final MissingResourceException ex) {
Logger.getLogger("Essentials").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex);
return defaultBundle.getString(string);
}
}
public static String tl(final String string, final Object... objects) {
if (instance == null) {
return "";
}
if (objects.length == 0) {
return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'");
} else {
return instance.format(string, objects);
}
}
public String format(final String string, final Object... objects) {
String format = translate(string);
MessageFormat messageFormat = messageFormatCache.get(format);
if (messageFormat == null) {
try {
messageFormat = new MessageFormat(format);
} catch (IllegalArgumentException e) {
} catch (final IllegalArgumentException e) {
ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage());
format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]");
messageFormat = new MessageFormat(format);
}
messageFormatCache.put(format, messageFormat);
}
return messageFormat.format(objects);
return messageFormat.format(objects).replace(' ', ' '); // replace nbsp with a space
}
public void updateLocale(final String loc) {
@@ -110,27 +123,25 @@ public class I18n implements net.ess3.api.II18n {
}
}
ResourceBundle.clearCache();
messageFormatCache = new HashMap<String, MessageFormat>();
messageFormatCache = new HashMap<>();
Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
try {
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale);
} catch (MissingResourceException ex) {
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new UTF8PropertiesControl());
} catch (final MissingResourceException ex) {
localeBundle = NULL_BUNDLE;
}
try {
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
} catch (MissingResourceException ex) {
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess), new UTF8PropertiesControl());
} catch (final MissingResourceException ex) {
customBundle = NULL_BUNDLE;
}
}
public static String capitalCase(final String input) {
return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1);
}
/**
* Attempts to load properties files from the plugin directory before falling back to the jar.
*/
private static class FileResClassLoader extends ClassLoader {
private final transient File dataFolder;
@@ -145,7 +156,7 @@ public class I18n implements net.ess3.api.II18n {
if (file.exists()) {
try {
return file.toURI().toURL();
} catch (MalformedURLException ex) {
} catch (final MalformedURLException ignored) {
}
}
return null;
@@ -157,10 +168,43 @@ public class I18n implements net.ess3.api.II18n {
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException ex) {
} catch (final FileNotFoundException ignored) {
}
}
return null;
}
}
/**
* Reads .properties files as UTF-8 instead of ISO-8859-1, which is the default on Java 8/below.
* Java 9 fixes this by defaulting to UTF-8 for .properties files.
*/
private static class UTF8PropertiesControl extends ResourceBundle.Control {
public ResourceBundle newBundle(final String baseName, final Locale locale, final String format, final ClassLoader loader, final boolean reload) throws IOException {
final String resourceName = toResourceName(toBundleName(baseName, locale), "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
final URL url = loader.getResource(resourceName);
if (url != null) {
final URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// use UTF-8 here, this is the important bit
bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
} finally {
stream.close();
}
}
return bundle;
}
}
}
@@ -3,10 +3,12 @@ package com.earth2me.essentials;
import com.earth2me.essentials.api.IItemDb;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.api.IWarps;
import com.earth2me.essentials.metrics.Metrics;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import net.ess3.nms.SpawnerProvider;
import net.ess3.provider.ContainerProvider;
import net.ess3.provider.KnownCommandsProvider;
import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SpawnerBlockProvider;
import net.ess3.provider.SpawnerItemProvider;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@@ -18,6 +20,7 @@ import org.bukkit.scheduler.BukkitTask;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
public interface IEssentials extends Plugin {
void addReloadListener(IConf listener);
@@ -47,6 +50,8 @@ public interface IEssentials extends Plugin {
int broadcastMessage(IUser sender, String message);
int broadcastMessage(IUser sender, String message, Predicate<IUser> shouldExclude);
int broadcastMessage(String permission, String message);
ISettings getSettings();
@@ -63,7 +68,7 @@ public interface IEssentials extends Plugin {
Kits getKits();
Methods getPaymentMethod();
RandomTeleport getRandomTeleport();
BukkitTask runTaskAsynchronously(Runnable run);
@@ -89,12 +94,14 @@ public interface IEssentials extends Plugin {
UserMap getUserMap();
Metrics getMetrics();
void setMetrics(Metrics metrics);
EssentialsTimer getTimer();
/**
* Get a list of players who are vanished.
*
* @return A list of players who are vanished
* @deprecated Use {@link net.ess3.api.IEssentials#getVanishedPlayersNew()} where possible.
*/
@Deprecated
List<String> getVanishedPlayers();
@@ -102,5 +109,13 @@ public interface IEssentials extends Plugin {
Iterable<User> getOnlineUsers();
SpawnerProvider getSpawnerProvider();
SpawnerItemProvider getSpawnerItemProvider();
SpawnerBlockProvider getSpawnerBlockProvider();
ServerStateProvider getServerStateProvider();
ContainerProvider getContainerProvider();
KnownCommandsProvider getKnownCommandsProvider();
}
@@ -1,5 +1,4 @@
package com.earth2me.essentials;
public interface IEssentialsModule {
}
@@ -3,8 +3,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.textreader.IText;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventPriority;
@@ -14,9 +13,9 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public interface ISettings extends IConf {
boolean areSignsDisabled();
@@ -30,6 +29,8 @@ public interface ISettings extends IConf {
long getBackupInterval();
boolean isAlwaysRunBackup();
String getChatFormat(String group);
int getChatRadius();
@@ -46,6 +47,8 @@ public interface ISettings extends IConf {
String getCurrencySymbol();
boolean isCurrencySymbolSuffixed();
int getOversizedStackSize();
int getDefaultStackSize();
@@ -87,7 +90,7 @@ public interface ISettings extends IConf {
String getNicknamePrefix();
ChatColor getOperatorColor() throws Exception;
String getOperatorColor() throws Exception;
boolean getPerWarpPermission();
@@ -95,7 +98,7 @@ public interface ISettings extends IConf {
int getProtectCreeperMaxHeight();
List<Integer> getProtectList(final String configName);
List<Material> getProtectList(final String configName);
boolean getProtectPreventSpawn(final String creatureName);
@@ -103,6 +106,8 @@ public interface ISettings extends IConf {
boolean getRespawnAtHome();
boolean isRespawnAtAnchor();
Set getMultipleHomes();
int getHomeLimit(String set);
@@ -117,6 +122,12 @@ public interface ISettings extends IConf {
boolean isForceDisableTeleportSafety();
boolean isAlwaysTeleportSafety();
boolean isTeleportPassengerDismount();
boolean isForcePassengerTeleport();
double getTeleportCooldown();
double getTeleportDelay();
@@ -131,11 +142,16 @@ public interface ISettings extends IConf {
boolean isDebug();
void setDebug(boolean debug);
boolean isEcoDisabled();
@Deprecated
boolean isTradeInStacks(int id);
List<Integer> itemSpawnBlacklist();
boolean isTradeInStacks(Material type);
List<Material> itemSpawnBlacklist();
List<EssentialsSign> enabledSigns();
@@ -155,6 +171,8 @@ public interface ISettings extends IConf {
boolean isEcoLogUpdateEnabled();
boolean realNamesOnList();
boolean removeGodOnDisconnect();
boolean changeDisplayName();
@@ -181,13 +199,23 @@ public interface ISettings extends IConf {
boolean cancelAfkOnInteract();
boolean sleepIgnoresAfkPlayers();
boolean isAfkListName();
String getAfkListName();
boolean broadcastAfkMessage();
boolean areDeathMessagesEnabled();
void setDebug(boolean debug);
KeepInvPolicy getVanishingItemsPolicy();
KeepInvPolicy getBindingItemsPolicy();
int getJoinQuitMessagePlayerCount();
boolean hasJoinQuitMessagePlayerCount();
Set<String> getNoGodWorlds();
@@ -231,6 +259,8 @@ public interface ISettings extends IConf {
void setEssentialsChatActive(boolean b);
long getMaxMute();
long getMaxTempban();
Map<String, Object> getListGroupConfig();
@@ -239,6 +269,8 @@ public interface ISettings extends IConf {
boolean ignoreColorsInMaxLength();
boolean hideDisplayNameInVanish();
int getMaxUserCacheCount();
boolean allowSilentJoinQuit();
@@ -257,8 +289,12 @@ public interface ISettings extends IConf {
boolean isLastMessageReplyRecipient();
boolean isReplyToVanished();
BigDecimal getMinimumPayAmount();
boolean isPayExcludesIgnoreList();
long getLastMessageReplyRecipientTimeout();
boolean isMilkBucketEasterEggEnabled();
@@ -277,6 +313,10 @@ public interface ISettings extends IConf {
boolean isCommandCooldownsEnabled();
boolean isWorldChangeFlyResetEnabled();
boolean isWorldChangeSpeedResetEnabled();
long getCommandCooldownMs(String label);
Entry<Pattern, Long> getCommandCooldownEntry(String label);
@@ -293,6 +333,8 @@ public interface ISettings extends IConf {
boolean isAllowBulkBuySell();
boolean isAllowSellNamedItems();
boolean isAddingPrefixInPlayerlist();
boolean isAddingSuffixInPlayerlist();
@@ -306,4 +348,39 @@ public interface ISettings extends IConf {
List<String> getDefaultEnabledConfirmCommands();
boolean isConfirmCommandEnabledByDefault(String commandName);
boolean isTeleportBackWhenFreedFromJail();
boolean isCompassTowardsHomePerm();
boolean isAllowWorldInBroadcastworld();
String getItemDbType();
boolean allowOldIdSigns();
boolean isWaterSafe();
boolean isSafeUsermap();
boolean logCommandBlockCommands();
Set<Predicate<String>> getNickBlacklist();
double getMaxProjectileSpeed();
boolean isRemovingEffectsOnHeal();
boolean isSpawnIfNoHome();
boolean isConfirmHomeOverwrite();
boolean infoAfterDeath();
enum KeepInvPolicy {
KEEP,
DELETE,
DROP
}
}
@@ -2,7 +2,6 @@ package com.earth2me.essentials;
import org.bukkit.Location;
public interface ITarget {
Location getLocation();
}
}
@@ -1,9 +1,13 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IAsyncTeleport;
import com.earth2me.essentials.commands.IEssentialsCommand;
import net.ess3.api.ITeleport;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
@@ -13,7 +17,12 @@ import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Provides access to the user abstraction and stored data. Maintainers should add methods to <i>this interface</i>.
*
* @deprecated External plugins should use {@link net.ess3.api.IUser} instead of this interface, in case future APIs are added.
*/
@Deprecated
public interface IUser {
boolean isAuthorized(String node);
@@ -21,6 +30,8 @@ public interface IUser {
boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix);
boolean isPermissionSet(String node);
void healCooldown() throws Exception;
void giveMoney(BigDecimal value) throws MaxMoneyException;
@@ -35,7 +46,7 @@ public interface IUser {
boolean canAfford(BigDecimal value);
Boolean canSpawnItem(final int itemId);
Boolean canSpawnItem(final Material material);
void setLastLocation();
@@ -50,21 +61,26 @@ public interface IUser {
*/
boolean hasOutstandingTeleportRequest();
/**
* @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.api.IAsyncTeleport IAsyncTeleport} with {@link IUser#getAsyncTeleport()}
*/
@Deprecated
ITeleport getTeleport();
IAsyncTeleport getAsyncTeleport();
BigDecimal getMoney();
void setMoney(final BigDecimal value) throws MaxMoneyException;
void setAfk(final boolean set);
void setAfk(final boolean set, final AfkStatusChangeEvent.Cause cause);
/**
* 'Hidden' Represents when a player is hidden from others. This status includes when the player is hidden via other
* supported plugins. Use isVanished() if you want to check if a user is vanished by Essentials.
*
* @return If the user is hidden or not
*
* @see isVanished
* @see IUser#isVanished()
*/
boolean isHidden();
@@ -92,8 +108,7 @@ public interface IUser {
* plugin.
*
* @return If the user is vanished or not
*
* @see isHidden
* @see IUser#isHidden()
*/
boolean isVanished();
@@ -136,10 +151,13 @@ public interface IUser {
boolean isAfk();
void setIgnoreMsg(boolean ignoreMsg);
@Deprecated
void setAfk(final boolean set);
boolean isIgnoreMsg();
void setIgnoreMsg(boolean ignoreMsg);
void setConfigProperty(String node, Object object);
Set<String> getConfigKeys();
@@ -147,13 +165,13 @@ public interface IUser {
Map<String, Object> getConfigMap();
Map<String, Object> getConfigMap(String node);
Map<Pattern, Long> getCommandCooldowns();
Date getCommandCooldownExpiry(String label);
void addCommandCooldown(Pattern pattern, Date expiresAt, boolean save);
boolean clearCommandCooldown(Pattern pattern);
/*
@@ -165,23 +183,31 @@ public interface IUser {
String getName();
String getDisplayName();
String getAfkMessage();
void setAfkMessage(final String message);
long getAfkSince();
boolean isAcceptingPay();
void setAcceptingPay(boolean acceptingPay);
boolean isPromptingPayConfirm();
void setPromptingPayConfirm(boolean prompt);
boolean isPromptingClearConfirm();
void setPromptingClearConfirm(boolean prompt);
boolean isLastMessageReplyRecipient();
void setLastMessageReplyRecipient(boolean enabled);
Map<User, BigDecimal> getConfirmingPayments();
Block getTargetBlock(int maxDistance);
}
@@ -1,484 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.block.Banner;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class ItemDb implements IConf, net.ess3.api.IItemDb {
private final transient IEssentials ess;
private final transient Map<String, Integer> items = new HashMap<>();
private final transient Map<ItemData, List<String>> names = new HashMap<>();
private final transient Map<ItemData, String> primaryName = new HashMap<>();
private final transient Map<String, Short> durabilities = new HashMap<>();
private final transient Map<String, String> nbtData = new HashMap<>();
private final transient ManagedFile file;
private final transient Pattern splitPattern = Pattern.compile("((.*)[:+',;.](\\d+))");
private final transient Pattern csvSplitPattern = Pattern.compile("(\"([^\"]*)\"|[^,]*)(,|$)");
public ItemDb(final IEssentials ess) {
this.ess = ess;
file = new ManagedFile("items.csv", ess);
}
@Override
public void reloadConfig() {
final List<String> lines = file.getLines();
if (lines.isEmpty()) {
return;
}
durabilities.clear();
items.clear();
names.clear();
primaryName.clear();
for (String line : lines) {
if (line.length() > 0 && line.charAt(0) == '#') {
continue;
}
String itemName = null;
int numeric = -1;
short data = 0;
String nbt = null;
int col = 0;
Matcher matcher = csvSplitPattern.matcher(line);
while (matcher.find()) {
String match = matcher.group(1);
if (StringUtils.stripToNull(match) == null) {
continue;
}
match = StringUtils.strip(match.trim(), "\"");
switch (col) {
case 0:
itemName = match.toLowerCase(Locale.ENGLISH);
break;
case 1:
numeric = Integer.parseInt(match);
break;
case 2:
data = Short.parseShort(match);
break;
case 3:
nbt = StringUtils.stripToNull(match);
break;
default:
continue;
}
col++;
}
// Invalid row
if (itemName == null || numeric < 0) {
continue;
}
durabilities.put(itemName, data);
items.put(itemName, numeric);
if (nbt != null) {
nbtData.put(itemName, nbt);
}
ItemData itemData = new ItemData(numeric, data);
if (names.containsKey(itemData)) {
List<String> nameList = names.get(itemData);
nameList.add(itemName);
} else {
List<String> nameList = new ArrayList<>();
nameList.add(itemName);
names.put(itemData, nameList);
primaryName.put(itemData, itemName);
}
}
for (List<String> nameList : names.values()) {
Collections.sort(nameList, LengthCompare.INSTANCE);
}
}
@Override
public ItemStack get(final String id, final int quantity) throws Exception {
final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH));
retval.setAmount(quantity);
return retval;
}
@Override
public ItemStack get(final String id) throws Exception {
int itemid = 0;
String itemname;
short metaData = 0;
Matcher parts = splitPattern.matcher(id);
if (parts.matches()) {
itemname = parts.group(2);
metaData = Short.parseShort(parts.group(3));
} else {
itemname = id;
}
if (NumberUtil.isInt(itemname)) {
itemid = Integer.parseInt(itemname);
} else if (NumberUtil.isInt(id)) {
itemid = Integer.parseInt(id);
} else {
itemname = itemname.toLowerCase(Locale.ENGLISH);
}
if (itemid < 1) {
if (items.containsKey(itemname)) {
itemid = items.get(itemname);
if (durabilities.containsKey(itemname) && metaData == 0) {
metaData = durabilities.get(itemname);
}
} else if (Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)) != null) {
Material bMaterial = Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH));
itemid = bMaterial.getId();
} else {
try {
Material bMaterial = Bukkit.getUnsafe().getMaterialFromInternalName(itemname.toLowerCase(Locale.ENGLISH));
itemid = bMaterial.getId();
} catch (Throwable throwable) {
throw new Exception(tl("unknownItemName", itemname), throwable);
}
}
}
if (itemid < 1) {
throw new Exception(tl("unknownItemName", itemname));
}
final Material mat = Material.getMaterial(itemid);
if (mat == null) {
throw new Exception(tl("unknownItemId", itemid));
}
ItemStack retval = new ItemStack(mat);
if (nbtData.containsKey(itemname)) {
String nbt = nbtData.get(itemname);
if (nbt.startsWith("*")) {
nbt = nbtData.get(nbt.substring(1));
}
retval = ess.getServer().getUnsafe().modifyItemStack(retval, nbt);
}
if (mat == Material.MOB_SPAWNER) {
if (metaData == 0) metaData = EntityType.PIG.getTypeId();
try {
retval = ess.getSpawnerProvider().setEntityType(retval, EntityType.fromId(metaData));
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from mob spawners.");
}
} else if (mat == Material.MONSTER_EGG) {
EntityType type;
try {
type = EntityType.fromId(metaData);
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from spawn eggs.");
}
retval = ess.getSpawnEggProvider().createEggItem(type);
} else if (mat.name().endsWith("POTION")
&& ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_11_R1)) { // Only apply this to pre-1.11 as items.csv might only work in 1.11
retval = ess.getPotionMetaProvider().createPotionItem(mat, metaData);
} else {
retval.setDurability(metaData);
}
retval.setAmount(mat.getMaxStackSize());
return retval;
}
@Override
public List<ItemStack> getMatching(User user, String[] args) throws Exception {
List<ItemStack> is = new ArrayList<>();
if (args.length < 1) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("hand")) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else if (args[0].equalsIgnoreCase("blocks")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else {
is.add(get(args[0]));
}
if (is.isEmpty() || is.get(0).getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
}
return is;
}
@Override
public String names(ItemStack item) {
ItemData itemData = new ItemData(item.getTypeId(), item.getDurability());
List<String> nameList = names.get(itemData);
if (nameList == null) {
itemData = new ItemData(item.getTypeId(), (short) 0);
nameList = names.get(itemData);
if (nameList == null) {
return null;
}
}
if (nameList.size() > 15) {
nameList = nameList.subList(0, 14);
}
return StringUtil.joinList(", ", nameList);
}
@Override
public String name(ItemStack item) {
ItemData itemData = new ItemData(item.getTypeId(), item.getDurability());
String name = primaryName.get(itemData);
if (name == null) {
itemData = new ItemData(item.getTypeId(), (short) 0);
name = primaryName.get(itemData);
if (name == null) {
return null;
}
}
return name;
}
@Override
public String serialize(ItemStack is) {
String mat = is.getType().name();
if (is.getData().getData() != 0) {
mat = mat + ":" + is.getData().getData();
}
int quantity = is.getAmount();
StringBuilder sb = new StringBuilder(); // Add space AFTER you add something. We can trim at end.
sb.append(mat).append(" ").append(quantity).append(" ");
// ItemMeta applies to anything.
if (is.hasItemMeta()) {
ItemMeta meta = is.getItemMeta();
if (meta.hasDisplayName()) {
sb.append("name:").append(meta.getDisplayName().replaceAll(" ", "_")).append(" ");
}
if (meta.hasLore()) {
sb.append("lore:");
boolean first = true;
for (String s : meta.getLore()) {
// Add | before the line if it's not the first one. Easy but weird way
// to do this since we need each line separated by |
if (!first) {
sb.append("|");
}
first = false;
sb.append(s.replaceAll(" ", "_"));
}
sb.append(" ");
}
if (meta.hasEnchants()) {
for (Enchantment e : meta.getEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(meta.getEnchantLevel(e)).append(" ");
}
}
Set<ItemFlag> flags = meta.getItemFlags();
if (flags != null && !flags.isEmpty()) {
sb.append("itemflags:");
boolean first = true;
for (ItemFlag flag : flags) {
if (!first) {
sb.append(",");
}
sb.append(flag.name());
first = false;
}
}
}
switch (is.getType()) {
case WRITTEN_BOOK:
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Books in that order.
// Interesting as I didn't see a way to do pages or chapters.
BookMeta bookMeta = (BookMeta) is.getItemMeta();
if (bookMeta.hasTitle()) {
sb.append("title:").append(bookMeta.getTitle()).append(" ");
}
if (bookMeta.hasAuthor()) {
sb.append("author:").append(bookMeta.getAuthor()).append(" ");
}
// Only other thing it could have is lore but that's done up there ^^^
break;
case ENCHANTED_BOOK:
EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) is.getItemMeta();
for (Enchantment e : enchantmentStorageMeta.getStoredEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(enchantmentStorageMeta.getStoredEnchantLevel(e)).append(" ");
}
break;
case FIREWORK:
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Fireworks in that order.
FireworkMeta fireworkMeta = (FireworkMeta) is.getItemMeta();
if (fireworkMeta.hasEffects()) {
for (FireworkEffect effect : fireworkMeta.getEffects()) {
if (effect.getColors() != null && !effect.getColors().isEmpty()) {
sb.append("color:");
boolean first = true;
for (Color c : effect.getColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
sb.append("shape: ").append(effect.getType().name()).append(" ");
if (effect.getFadeColors() != null && !effect.getFadeColors().isEmpty()) {
sb.append("fade:");
boolean first = true;
for (Color c : effect.getFadeColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
}
sb.append("power: ").append(fireworkMeta.getPower()).append(" ");
}
break;
case POTION:
Potion potion = Potion.fromItemStack(is);
for (PotionEffect e : potion.getEffects()) {
// long but needs to be effect:speed power:2 duration:120 in that order.
sb.append("splash:").append(potion.isSplash()).append(" ").append("effect:").append(e.getType().getName().toLowerCase()).append(" ").append("power:").append(e.getAmplifier()).append(" ").append("duration:").append(e.getDuration() / 20).append(" ");
}
break;
case SKULL_ITEM:
// item stack with meta
SkullMeta skullMeta = (SkullMeta) is.getItemMeta();
if (skullMeta != null && skullMeta.hasOwner()) {
sb.append("player:").append(skullMeta.getOwner()).append(" ");
}
break;
case LEATHER_HELMET:
case LEATHER_CHESTPLATE:
case LEATHER_LEGGINGS:
case LEATHER_BOOTS:
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) is.getItemMeta();
int rgb = leatherArmorMeta.getColor().asRGB();
sb.append("color:").append(rgb).append(" ");
break;
case BANNER:
BannerMeta bannerMeta = (BannerMeta) is.getItemMeta();
if (bannerMeta != null) {
int basecolor = bannerMeta.getBaseColor().getColor().asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
for (org.bukkit.block.banner.Pattern p : bannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
}
break;
case SHIELD:
// Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795
BlockStateMeta shieldMeta = (BlockStateMeta) is.getItemMeta();
Banner shieldBannerMeta = (Banner) shieldMeta.getBlockState();
int basecolor = shieldBannerMeta.getBaseColor().getColor().asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
for (org.bukkit.block.banner.Pattern p : shieldBannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
break;
}
return sb.toString().trim().replaceAll("§", "&");
}
@Override
public Collection<String> listNames() {
return primaryName.values();
}
static class ItemData {
final private int itemNo;
final private short itemData;
ItemData(final int itemNo, final short itemData) {
this.itemNo = itemNo;
this.itemData = itemData;
}
public int getItemNo() {
return itemNo;
}
public short getItemData() {
return itemData;
}
@Override
public int hashCode() {
return (31 * itemNo) ^ itemData;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof ItemData)) {
return false;
}
ItemData pairo = (ItemData) o;
return this.itemNo == pairo.getItemNo() && this.itemData == pairo.getItemData();
}
}
static class LengthCompare implements java.util.Comparator<String> {
private static final LengthCompare INSTANCE = new LengthCompare();
public LengthCompare() {
super();
}
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
}
@@ -16,6 +16,7 @@ import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
@@ -24,13 +25,17 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.plugin.PluginManager;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Jails> implements net.ess3.api.IJails {
private static final transient Logger LOGGER = Bukkit.getLogger();
private static transient boolean enabled = false;
@@ -71,7 +76,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
private void checkRegister() {
if (enabled == false && getCount() > 0) {
if (!enabled && getCount() > 0) {
registerListeners();
}
}
@@ -83,7 +88,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
if (getData().getJails() == null || jailName == null || !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("jailNotExist"));
}
Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH));
final Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH));
if (loc == null || loc.getWorld() == null) {
throw new Exception(tl("jailNotExist"));
}
@@ -100,7 +105,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
if (getData().getJails() == null) {
return Collections.emptyList();
}
return new ArrayList<String>(getData().getJails().keySet());
return new ArrayList<>(getData().getJails().keySet());
} finally {
unlock();
}
@@ -119,12 +124,16 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
}
/**
* @deprecated This method does not use asynchronous teleportation. Use {@link Jails#sendToJail(IUser, String, CompletableFuture)}
*/
@Override
@Deprecated
public void sendToJail(final IUser user, final String jail) throws Exception {
acquireReadLock();
try {
if (user.getBase().isOnline()) {
Location loc = getJail(jail);
final Location loc = getJail(jail);
user.getTeleport().now(loc, false, TeleportCause.COMMAND);
}
user.setJail(jail);
@@ -133,12 +142,28 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
}
@Override
public void sendToJail(final IUser user, final String jail, final CompletableFuture<Boolean> future) throws Exception {
acquireReadLock();
try {
if (user.getBase().isOnline()) {
final Location loc = getJail(jail);
user.getAsyncTeleport().now(loc, false, TeleportCause.COMMAND, future);
future.thenAccept(success -> user.setJail(jail));
return;
}
user.setJail(jail);
} finally {
unlock();
}
}
@Override
public void setJail(final String jailName, final Location loc) throws Exception {
acquireWriteLock();
try {
if (getData().getJails() == null) {
getData().setJails(new HashMap<String, Location>());
getData().setJails(new HashMap<>());
}
getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
} finally {
@@ -150,17 +175,16 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
public int getCount() {
try {
return getList().size();
} catch (Exception ex) {
} catch (final Exception ex) {
return 0;
}
}
private class JailListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onJailBlockBreak(final BlockBreakEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.isJailed()) {
if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-break")) {
event.setCancelled(true);
}
}
@@ -168,7 +192,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onJailBlockPlace(final BlockPlaceEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.isJailed()) {
if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-place")) {
event.setCancelled(true);
}
}
@@ -176,7 +200,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onJailBlockDamage(final BlockDamageEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.isJailed()) {
if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-block-damage")) {
event.setCancelled(true);
}
}
@@ -197,6 +221,14 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onJailPlayerInteract(final PlayerInteractEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-interact")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onJailPlayerGameModeChange(final PlayerGameModeChangeEvent event) {
final User user = ess.getUser(event.getPlayer());
if (user.isJailed()) {
event.setCancelled(true);
@@ -212,7 +244,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
try {
event.setRespawnLocation(getJail(user.getJail()));
} catch (Exception ex) {
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
} else {
@@ -230,7 +262,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
try {
event.setTo(getJail(user.getJail()));
} catch (Exception ex) {
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
} else {
@@ -249,16 +281,22 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
return;
}
try {
sendToJail(user, user.getJail());
} catch (Exception ex) {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
future.exceptionally(ex -> {
if (ess.getSettings().isDebug()) {
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
} else {
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
return false;
});
future.thenAccept(success -> user.sendMessage(tl("jailMessage")));
try {
sendToJail(user, user.getJail(), future);
} catch (final Exception ex) {
future.completeExceptionally(ex);
}
user.sendMessage(tl("jailMessage"));
}
}
}
+69 -27
View File
@@ -7,18 +7,23 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials;
import net.ess3.api.events.KitClaimEvent;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
import java.util.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Kit {
final IEssentials ess;
final String kitName;
@@ -47,10 +52,9 @@ public class Kit {
}
public void checkDelay(final User user) throws Exception {
long nextUse = getNextUse(user);
final long nextUse = getNextUse(user);
if (nextUse == 0L) {
return;
} else if (nextUse < 0L) {
user.sendMessage(tl("kitOnce"));
throw new NoChargeException();
@@ -84,7 +88,7 @@ public class Kit {
try {
// Make sure delay is valid
delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d;
} catch (Exception e) {
} catch (final Exception e) {
throw new Exception(tl("kitError2"));
}
@@ -122,10 +126,10 @@ public class Kit {
throw new Exception(tl("kitNotFound"));
}
try {
final List<String> itemList = new ArrayList<String>();
final List<String> itemList = new ArrayList<>();
final Object kitItems = kit.get("items");
if (kitItems instanceof List) {
for (Object item : (List) kitItems) {
for (final Object item : (List) kitItems) {
if (item instanceof String) {
itemList.add(item.toString());
continue;
@@ -135,36 +139,44 @@ public class Kit {
return itemList;
}
throw new Exception("Invalid item list");
} catch (Exception e) {
} catch (final Exception e) {
ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage());
throw new Exception(tl("kitError2"), e);
}
}
public void expandItems(final User user) throws Exception {
expandItems(user, getItems(user));
public boolean expandItems(final User user) throws Exception {
return expandItems(user, getItems(user));
}
public void expandItems(final User user, final List<String> items) throws Exception {
public boolean expandItems(final User user, final List<String> items) throws Exception {
try {
IText input = new SimpleTextInput(items);
IText output = new KeywordReplacer(input, user.getSource(), ess, true, true);
final IText input = new SimpleTextInput(items);
final IText output = new KeywordReplacer(input, user.getSource(), ess, true, true);
final KitClaimEvent event = new KitClaimEvent(user, this);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return false;
}
boolean spew = false;
final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments();
for (String kitItem : output.getLines()) {
if (kitItem.startsWith(ess.getSettings().getCurrencySymbol())) {
BigDecimal value = new BigDecimal(kitItem.substring(ess.getSettings().getCurrencySymbol().length()).trim());
Trade t = new Trade(value, ess);
t.pay(user, OverflowType.DROP);
final boolean currencyIsSuffix = ess.getSettings().isCurrencySymbolSuffixed();
final List<ItemStack> itemList = new ArrayList<>();
final List<String> commandQueue = new ArrayList<>();
final List<String> moneyQueue = new ArrayList<>();
for (final String kitItem : output.getLines()) {
if (!currencyIsSuffix ? kitItem.startsWith(ess.getSettings().getCurrencySymbol()) : kitItem.endsWith(ess.getSettings().getCurrencySymbol())) {
moneyQueue.add(NumberUtil.sanitizeCurrencyString(kitItem, ess));
continue;
}
if (kitItem.startsWith("/")) {
String command = kitItem.substring(1);
String name = user.getName();
final String name = user.getName();
command = command.replace("{player}", name);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
commandQueue.add(command);
continue;
}
@@ -182,17 +194,22 @@ public class Kit {
metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess);
}
final Map<Integer, ItemStack> overfilled;
final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks");
itemList.add(metaStack.getItemStack());
}
final Map<Integer, ItemStack> overfilled;
final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks");
final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull();
if (isDropItemsIfFull) {
if (allowOversizedStacks) {
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack());
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[0]));
} else {
overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack());
overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[0]));
}
for (ItemStack itemStack : overfilled.values()) {
for (final ItemStack itemStack : overfilled.values()) {
int spillAmount = itemStack.getAmount();
if (!allowOversizedStacks) {
itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize());
itemStack.setAmount(Math.min(spillAmount, itemStack.getMaxStackSize()));
}
while (spillAmount > 0) {
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
@@ -200,15 +217,40 @@ public class Kit {
}
spew = true;
}
} else {
if (allowOversizedStacks) {
overfilled = InventoryWorkaround.addAllOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[0]));
} else {
overfilled = InventoryWorkaround.addAllItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[0]));
}
if (overfilled != null) {
user.sendMessage(tl("kitInvFullNoDrop"));
return false;
}
}
user.getBase().updateInventory();
// Process money & command queues
// Done after all items have been processed so commands are not run and money is not given if
// an error occurs during the item giving process
for (final String valueString : moneyQueue) {
final BigDecimal value = new BigDecimal(valueString.trim());
final Trade t = new Trade(value, ess);
t.pay(user, OverflowType.DROP);
}
for (final String cmd : commandQueue) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd);
}
if (spew) {
user.sendMessage(tl("kitInvFull"));
}
} catch (Exception e) {
} catch (final Exception e) {
user.getBase().updateInventory();
ess.getLogger().log(Level.WARNING, e.getMessage());
throw new Exception(tl("kitError2"), e);
}
return true;
}
}
@@ -35,7 +35,7 @@ public class Kits implements IConf {
if (config.isConfigurationSection("kits")) {
final ConfigurationSection section = config.getConfigurationSection("kits");
final ConfigurationSection newSection = new MemoryConfiguration();
for (String kitItem : section.getKeys(false)) {
for (final String kitItem : section.getKeys(false)) {
if (section.isConfigurationSection(kitItem)) {
newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem));
}
@@ -64,14 +64,28 @@ public class Kits implements IConf {
// you just found if you don't toLowercase it.
if (kits.isConfigurationSection(name.toLowerCase())) {
return kits.getConfigurationSection(name.toLowerCase()).getValues(true);
} else {
}
}
return null;
}
public void addKit(String name, List<String> lines, long delay) {
// Tries to find an existing kit name that matches the given name, ignoring case. Returns null if no match.
public String matchKit(final String name) {
if (config.isConfigurationSection("kits")) {
final ConfigurationSection section = config.getConfigurationSection("kits");
if (section != null) {
for (final String kitName : section.getKeys(false)) {
if (kitName.equalsIgnoreCase(name)) {
return kitName;
}
}
}
}
return null;
}
public void addKit(final String name, final List<String> lines, final long delay) {
// Will overwrite but w/e
config.set("kits." + name + ".delay", delay);
config.set("kits." + name + ".items", lines);
@@ -79,23 +93,29 @@ public class Kits implements IConf {
config.save();
}
public void removeKit(final String name) {
config.set("kits." + name, null);
kits = _getKits();
config.save();
}
public String listKits(final net.ess3.api.IEssentials ess, final User user) throws Exception {
try {
final ConfigurationSection kits = config.getConfigurationSection("kits");
final StringBuilder list = new StringBuilder();
for (String kitItem : kits.getKeys(false)) {
for (final String kitItem : kits.getKeys(false)) {
if (user == null) {
list.append(" ").append(capitalCase(kitItem));
} else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) {
String cost = "";
String name = capitalCase(kitItem);
BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
final BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
if (costPrice.signum() > 0) {
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
}
Kit kit = new Kit(kitItem, ess);
double nextUse = kit.getNextUse(user);
final Kit kit = new Kit(kitItem, ess);
final double nextUse = kit.getNextUse(user);
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
continue;
} else if (nextUse != 0) {
@@ -106,7 +126,7 @@ public class Kits implements IConf {
}
}
return list.toString().trim();
} catch (Exception ex) {
} catch (final Exception ex) {
throw new Exception(tl("kitError"), ex);
}
@@ -2,11 +2,10 @@ package com.earth2me.essentials;
import org.bukkit.Location;
public class LocationTarget implements ITarget {
private final Location location;
LocationTarget(Location location) {
LocationTarget(final Location location) {
this.location = location;
}
@@ -14,4 +13,4 @@ public class LocationTarget implements ITarget {
public Location getLocation() {
return location;
}
}
}
@@ -3,7 +3,16 @@ package com.earth2me.essentials;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
@@ -16,7 +25,6 @@ import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class ManagedFile {
private static final int BUFFERSIZE = 1024 * 8;
private final transient File file;
@@ -29,7 +37,7 @@ public class ManagedFile {
if (checkForVersion(file, ess.getDescription().getVersion()) && !file.delete()) {
throw new IOException("Could not delete file " + file.toString());
}
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -37,20 +45,17 @@ public class ManagedFile {
if (!file.exists()) {
try {
copyResourceAscii("/" + filename, file);
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded"), ex);
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex);
}
}
}
public static void copyResourceAscii(final String resourceName, final File file) throws IOException {
final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName));
try {
try (final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName))) {
final MessageDigest digest = getDigest();
final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest);
try {
final OutputStreamWriter writer = new OutputStreamWriter(digestStream);
try {
try (final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest)) {
try (final OutputStreamWriter writer = new OutputStreamWriter(digestStream)) {
final char[] buffer = new char[BUFFERSIZE];
do {
final int length = reader.read(buffer);
@@ -66,14 +71,8 @@ public class ManagedFile {
digestStream.on(false);
digestStream.write('#');
digestStream.write(hashInt.toString(16).getBytes());
} finally {
writer.close();
}
} finally {
digestStream.close();
}
} finally {
reader.close();
}
}
@@ -81,8 +80,7 @@ public class ManagedFile {
if (file.length() < 33) {
return false;
}
final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
try {
try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
final byte[] buffer = new byte[(int) file.length()];
int position = 0;
do {
@@ -96,8 +94,7 @@ public class ManagedFile {
if (bais.skip(file.length() - 33) != file.length() - 33) {
return false;
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
try {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(bais))) {
String hash = reader.readLine();
if (hash != null && hash.matches("#[a-f0-9]{32}")) {
hash = hash.substring(1);
@@ -108,8 +105,7 @@ public class ManagedFile {
if (!versioncheck.equalsIgnoreCase(version)) {
bais.reset();
final MessageDigest digest = getDigest();
final DigestInputStream digestStream = new DigestInputStream(bais, digest);
try {
try (final DigestInputStream digestStream = new DigestInputStream(bais, digest)) {
final byte[] bytes = new byte[(int) file.length() - 33];
digestStream.read(bytes);
final BigInteger correct = new BigInteger(hash, 16);
@@ -119,17 +115,11 @@ public class ManagedFile {
} else {
Bukkit.getLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually.");
}
} finally {
digestStream.close();
}
}
}
}
} finally {
reader.close();
}
} finally {
bis.close();
}
return false;
}
@@ -137,16 +127,15 @@ public class ManagedFile {
public static MessageDigest getDigest() throws IOException {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
} catch (final NoSuchAlgorithmException ex) {
throw new IOException(ex);
}
}
public List<String> getLines() {
try {
final BufferedReader reader = new BufferedReader(new FileReader(file));
try {
final List<String> lines = new ArrayList<String>();
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
final List<String> lines = new ArrayList<>();
do {
final String line = reader.readLine();
if (line == null) {
@@ -156,10 +145,8 @@ public class ManagedFile {
}
} while (true);
return lines;
} finally {
reader.close();
}
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
return Collections.emptyList();
}
@@ -3,13 +3,13 @@ package com.earth2me.essentials;
import com.earth2me.essentials.textreader.BookInput;
import com.earth2me.essentials.textreader.BookPager;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.base.Joiner;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
@@ -19,28 +19,44 @@ import org.bukkit.block.banner.PatternType;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.Method;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class MetaItemStack {
private static final Map<String, DyeColor> colorMap = new HashMap<String, DyeColor>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<String, FireworkEffect.Type>();
private static final Map<String, DyeColor> colorMap = new HashMap<>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<>();
private static int bukkitUnbreakableSupport = -1;
private static Method spigotMethod;
private static Method setUnbreakableMethod;
private static boolean useNewSkullMethod = true;
static {
for (DyeColor color : DyeColor.values()) {
for (final DyeColor color : DyeColor.values()) {
colorMap.put(color.name(), color);
}
for (FireworkEffect.Type type : FireworkEffect.Type.values()) {
for (final FireworkEffect.Type type : FireworkEffect.Type.values()) {
fireworkShape.put(type.name(), type);
}
}
@@ -63,6 +79,24 @@ public class MetaItemStack {
this.stack = stack.clone();
}
private static void setSkullOwner(final IEssentials ess, final ItemStack stack, final String owner) {
if (!(stack.getItemMeta() instanceof SkullMeta)) return;
final SkullMeta meta = (SkullMeta) stack.getItemMeta();
if (useNewSkullMethod) {
try {
meta.setOwningPlayer(ess.getServer().getOfflinePlayer(owner));
stack.setItemMeta(meta);
return;
} catch (final NoSuchMethodError e) {
useNewSkullMethod = false;
}
}
meta.setOwner(owner);
stack.setItemMeta(meta);
}
public ItemStack getItemStack() {
return stack;
}
@@ -97,40 +131,31 @@ public class MetaItemStack {
completePotion = true;
}
private boolean isPotion(Material type) {
return type.name().endsWith("POTION");
}
public boolean canSpawn(final IEssentials ess) {
try {
ess.getServer().getUnsafe().modifyItemStack(stack.clone(), "{}");
return true;
} catch (NullPointerException npe) {
} catch (final NoSuchMethodError nsme) {
return true;
} catch (final Throwable npe) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
}
return false;
} catch (NoSuchMethodError nsme) {
return true;
} catch (Throwable throwable) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", throwable);
}
return false;
}
}
public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception {
public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, final String[] string, final int fromArg, final IEssentials ess) throws Exception {
if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess)) {
try {
stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length)));
} catch (NullPointerException npe) {
} catch (final NullPointerException npe) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
}
} catch (NoSuchMethodError nsme) {
} catch (final NoSuchMethodError nsme) {
throw new Exception(tl("noMetaJson"), nsme);
} catch (Throwable throwable) {
} catch (final Throwable throwable) {
throw new Exception(throwable.getMessage(), throwable);
}
} else {
@@ -141,8 +166,8 @@ public class MetaItemStack {
if (!hasMetaPermission(sender, "firework", true, true, ess)) {
throw new Exception(tl("noMetaFirework"));
}
FireworkEffect effect = builder.build();
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
final FireworkEffect effect = builder.build();
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.addEffect(effect);
if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) {
throw new Exception(tl("multipleCharges"));
@@ -158,16 +183,7 @@ public class MetaItemStack {
return;
}
Material banner = null;
Material shield = null;
try {
// 1.8
banner = Material.valueOf("BANNER");
// 1.9
shield = Material.valueOf("SHIELD");
} catch(IllegalArgumentException ignored){}
final Material WRITTEN_BOOK = EnumUtil.getMaterial("WRITTEN_BOOK");
if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess)) {
final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' '));
@@ -175,69 +191,73 @@ public class MetaItemStack {
meta.setDisplayName(displayName);
stack.setItemMeta(meta);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess)) {
final List<String> lore = new ArrayList<String>();
for (String line : split[1].split("\\|")) {
lore.add(FormatUtil.replaceFormat(line.replace('_', ' ')));
final List<String> lore = new ArrayList<>();
for (final String line : split[1].split("(?<!\\\\)\\|")) {
lore.add(FormatUtil.replaceFormat(line.replace('_', ' ').replace("\\|", "|")));
}
final ItemMeta meta = stack.getItemMeta();
meta.setLore(lore);
stack.setItemMeta(meta);
} else if (split[0].equalsIgnoreCase("unbreakable") && hasMetaPermission(sender, "unbreakable", false, true, ess)) {
boolean value = split.length > 1 ? Boolean.valueOf(split[1]) : true;
final boolean value = split.length <= 1 || Boolean.parseBoolean(split[1]);
setUnbreakable(stack, value);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && stack.getType() == Material.SKULL_ITEM && hasMetaPermission(sender, "head", false, true, ess)) {
if (stack.getDurability() == 3) {
} else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && hasMetaPermission(sender, "head", false, true, ess)) {
if (MaterialUtil.isPlayerHead(stack.getType(), stack.getDurability())) {
final String owner = split[1];
final SkullMeta meta = (SkullMeta) stack.getItemMeta();
meta.setOwner(owner);
stack.setItemMeta(meta);
setSkullOwner(ess, stack, owner);
} else {
throw new Exception(tl("onlyPlayerSkulls"));
}
} else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == WRITTEN_BOOK && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) {
final BookMeta meta = (BookMeta) stack.getItemMeta();
final IText input = new BookInput("book", true, ess);
final BookPager pager = new BookPager(input);
List<String> pages = pager.getPages(split[1]);
final List<String> pages = pager.getPages(split[1]);
meta.setPages(pages);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) {
final String author = FormatUtil.replaceFormat(split[1]);
final BookMeta meta = (BookMeta) stack.getItemMeta();
meta.setAuthor(author);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) {
final String title = FormatUtil.replaceFormat(split[1].replace('_', ' '));
final BookMeta meta = (BookMeta) stack.getItemMeta();
meta.setTitle(title);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("power") && stack.getType() == Material.FIREWORK && hasMetaPermission(sender, "firework-power", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("power") && MaterialUtil.isFirework(stack.getType()) && hasMetaPermission(sender, "firework-power", false, true, ess)) {
final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0;
final FireworkMeta meta = (FireworkMeta) stack.getItemMeta();
meta.setPower(power > 3 ? 4 : power);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("itemflags") && hasMetaPermission(sender, "itemflags", false, true, ess)) {
addItemFlags(string);
} else if (stack.getType() == Material.FIREWORK) {//WARNING - Meta for fireworks will be ignored after this point.
} else if (MaterialUtil.isFirework(stack.getType())) {
//WARNING - Meta for fireworks will be ignored after this point.
addFireworkMeta(sender, false, string, ess);
} else if (isPotion(stack.getType())) { //WARNING - Meta for potions will be ignored after this point.
} else if (MaterialUtil.isPotion(stack.getType())) {
//WARNING - Meta for potions will be ignored after this point.
addPotionMeta(sender, false, string, ess);
} else if (banner != null && stack.getType() == banner) { //WARNING - Meta for banners will be ignored after this point.
addBannerMeta(sender, false, string, ess);
} else if (shield != null && stack.getType() == shield) { //WARNING - Meta for shields will be ignored after this point.
addBannerMeta(sender, false, string, ess);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) && (stack.getType() == Material.LEATHER_BOOTS || stack.getType() == Material.LEATHER_CHESTPLATE || stack.getType() == Material.LEATHER_HELMET || stack.getType() == Material.LEATHER_LEGGINGS)) {
} else if (MaterialUtil.isBanner(stack.getType())) {
if (stack.getType().toString().equals("SHIELD") && Enchantments.getByName(split[0]) != null) {
parseEnchantmentStrings(sender, allowUnsafe, split, ess);
} else {
//WARNING - Meta for banners will be ignored after this point.
addBannerMeta(sender, false, string, ess);
}
} else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) && MaterialUtil.isLeatherArmor(stack.getType())) {
final String[] color = split[1].split("(\\||,)");
if(color.length == 1 && (NumberUtil.isInt(color[0]) || color[0].startsWith("#"))) { // int rgb and hex
if (color.length == 1 && (NumberUtil.isInt(color[0]) || color[0].startsWith("#"))) {
// Either integer or hexadecimal
final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta();
String input = color[0];
if(input.startsWith("#")) {
final String input = color[0];
if (input.startsWith("#")) { // Hex
meta.setColor(Color.fromRGB(
Integer.valueOf(input.substring(1, 3), 16),
Integer.valueOf(input.substring(3, 5), 16),
Integer.valueOf(input.substring(5, 7), 16)));
} else {
} else { // Int
meta.setColor(Color.fromRGB(Integer.parseInt(input)));
}
stack.setItemMeta(meta);
@@ -257,16 +277,16 @@ public class MetaItemStack {
}
public void addItemFlags(final String string) throws Exception {
String[] separate = splitPattern.split(string, 2);
final String[] separate = splitPattern.split(string, 2);
if (separate.length != 2) {
throw new Exception(tl("invalidItemFlagMeta", string));
}
String[] split = separate[1].split(",");
ItemMeta meta = stack.getItemMeta();
final String[] split = separate[1].split(",");
final ItemMeta meta = stack.getItemMeta();
for (String s : split) {
for (ItemFlag flag : ItemFlag.values()) {
for (final String s : split) {
for (final ItemFlag flag : ItemFlag.values()) {
if (s.equalsIgnoreCase(flag.name())) {
meta.addItemFlags(flag);
}
@@ -281,7 +301,7 @@ public class MetaItemStack {
}
public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (stack.getType() == Material.FIREWORK) {
if (MaterialUtil.isFirework(stack.getType())) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
return;
@@ -292,8 +312,8 @@ public class MetaItemStack {
if (!hasMetaPermission(sender, "firework", true, true, ess)) {
throw new Exception(tl("noMetaFirework"));
}
FireworkEffect effect = builder.build();
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
final FireworkEffect effect = builder.build();
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.addEffect(effect);
if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) {
throw new Exception(tl("multipleCharges"));
@@ -302,9 +322,9 @@ public class MetaItemStack {
builder = FireworkEffect.builder();
}
List<Color> primaryColors = new ArrayList<Color>();
String[] colors = split[1].split(",");
for (String color : colors) {
final List<Color> primaryColors = new ArrayList<>();
final String[] colors = split[1].split(",");
for (final String color : colors) {
if (colorMap.containsKey(color.toUpperCase())) {
validFirework = true;
primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
@@ -315,7 +335,7 @@ public class MetaItemStack {
builder.withColor(primaryColors);
} else if (split[0].equalsIgnoreCase("shape") || split[0].equalsIgnoreCase("type") || (allowShortName && (split[0].equalsIgnoreCase("s") || split[0].equalsIgnoreCase("t")))) {
FireworkEffect.Type finalEffect = null;
split[1] = (split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]);
split[1] = split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1];
if (fireworkShape.containsKey(split[1].toUpperCase())) {
finalEffect = fireworkShape.get(split[1].toUpperCase());
} else {
@@ -325,9 +345,9 @@ public class MetaItemStack {
builder.with(finalEffect);
}
} else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f"))) {
List<Color> fadeColors = new ArrayList<Color>();
String[] colors = split[1].split(",");
for (String color : colors) {
final List<Color> fadeColors = new ArrayList<>();
final String[] colors = split[1].split(",");
for (final String color : colors) {
if (colorMap.containsKey(color.toUpperCase())) {
fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
} else {
@@ -338,8 +358,8 @@ public class MetaItemStack {
builder.withFade(fadeColors);
}
} else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) {
String[] effects = split[1].split(",");
for (String effect : effects) {
final String[] effects = split[1].split(",");
for (final String effect : effects) {
if (effect.equalsIgnoreCase("twinkle")) {
builder.flicker(true);
} else if (effect.equalsIgnoreCase("trail")) {
@@ -353,7 +373,7 @@ public class MetaItemStack {
}
public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (isPotion(stack.getType())) {
if (MaterialUtil.isPotion(stack.getType())) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
@@ -381,6 +401,13 @@ public class MetaItemStack {
} else {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("amplifier") || (allowShortName && split[0].equalsIgnoreCase("a"))) {
if (NumberUtil.isInt(split[1])) {
validPotionPower = true;
power = Integer.parseInt(split[1]);
} else {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) {
if (NumberUtil.isInt(split[1])) {
validPotionDuration = true;
@@ -389,11 +416,11 @@ public class MetaItemStack {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("splash") || (allowShortName && split[0].equalsIgnoreCase("s"))) {
isSplashPotion = Boolean.valueOf(split[1]);
isSplashPotion = Boolean.parseBoolean(split[1]);
}
if (isValidPotion()) {
PotionMeta pmeta = (PotionMeta) stack.getItemMeta();
final PotionMeta pmeta = (PotionMeta) stack.getItemMeta();
pEffect = pEffectType.createEffect(duration, power);
if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) {
throw new Exception(tl("multiplePotionEffects"));
@@ -407,7 +434,7 @@ public class MetaItemStack {
stack.setType(Material.POTION);
}
} else {
Potion potion = Potion.fromItemStack(stack);
final Potion potion = Potion.fromItemStack(stack);
potion.setSplash(isSplashPotion);
potion.apply(stack);
}
@@ -426,7 +453,7 @@ public class MetaItemStack {
if (split.length > 1) {
try {
level = Integer.parseInt(split[1]);
} catch (NumberFormatException ex) {
} catch (final NumberFormatException ex) {
level = -1;
}
}
@@ -443,15 +470,14 @@ public class MetaItemStack {
}
try {
if (stack.getType().equals(Material.ENCHANTED_BOOK)) {
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta();
final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta();
if (level == 0) {
meta.removeStoredEnchant(enchantment);
} else {
meta.addStoredEnchant(enchantment, level, allowUnsafe);
}
stack.setItemMeta(meta);
} else // all other material types besides ENCHANTED_BOOK
{
} else { // all other material types besides ENCHANTED_BOOK
if (level == 0) {
stack.removeEnchantment(enchantment);
} else {
@@ -462,7 +488,7 @@ public class MetaItemStack {
}
}
}
} catch (Exception ex) {
} catch (final Exception ex) {
throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex);
}
}
@@ -482,31 +508,32 @@ public class MetaItemStack {
}
public void addBannerMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (stack.getType() == Material.BANNER && string != null) {
if (MaterialUtil.isBanner(stack.getType()) && !stack.getType().toString().equals("SHIELD") && string != null) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
throw new Exception(tl("invalidBanner", split[1]));
}
PatternType patternType = null;
try {
patternType = PatternType.valueOf(split[0]);
} catch (Exception ignored ) {}
} catch (final Exception ignored) {
}
final BannerMeta meta = (BannerMeta) stack.getItemMeta();
if (split[0].equalsIgnoreCase("basecolor")) {
Color color = Color.fromRGB(Integer.valueOf(split[1]));
final Color color = Color.fromRGB(Integer.parseInt(split[1]));
meta.setBaseColor(DyeColor.getByColor(color));
} else if (patternType != null) {
PatternType type = PatternType.valueOf(split[0]);
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.valueOf(split[1])));
org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
final PatternType type = PatternType.valueOf(split[0]);
final DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1])));
final org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
meta.addPattern(pattern);
}
stack.setItemMeta(meta);
} else if (stack.getType() == Material.SHIELD && string != null) {
} else if (stack.getType().toString().equals("SHIELD") && string != null) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
@@ -516,18 +543,19 @@ public class MetaItemStack {
PatternType patternType = null;
try {
patternType = PatternType.valueOf(split[0]);
} catch (Exception ignored ) {}
} catch (final Exception ignored) {
}
// Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795
BlockStateMeta meta = (BlockStateMeta) stack.getItemMeta();
Banner banner = (Banner) meta.getBlockState();
final BlockStateMeta meta = (BlockStateMeta) stack.getItemMeta();
final Banner banner = (Banner) meta.getBlockState();
if (split[0].equalsIgnoreCase("basecolor")) {
Color color = Color.fromRGB(Integer.valueOf(split[1]));
final Color color = Color.fromRGB(Integer.parseInt(split[1]));
banner.setBaseColor(DyeColor.getByColor(color));
} else if (patternType != null) {
PatternType type = PatternType.valueOf(split[0]);
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.valueOf(split[1])));
org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
final PatternType type = PatternType.valueOf(split[0]);
final DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1])));
final org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
banner.addPattern(pattern);
}
banner.update();
@@ -554,24 +582,34 @@ public class MetaItemStack {
}
}
private static Method spigotMethod;
private static Method setUnbreakableMethod;
private void setUnbreakable(ItemStack is, boolean unbreakable) {
ItemMeta meta = is.getItemMeta();
private void setUnbreakable(final ItemStack is, final boolean unbreakable) {
final ItemMeta meta = is.getItemMeta();
try {
if (spigotMethod == null) {
spigotMethod = meta.getClass().getDeclaredMethod("spigot");
spigotMethod.setAccessible(true);
if (bukkitUnbreakableSupport == -1) {
try {
ItemMeta.class.getDeclaredMethod("setUnbreakable", boolean.class);
bukkitUnbreakableSupport = 1;
} catch (final NoSuchMethodException | SecurityException ex) {
bukkitUnbreakableSupport = 0;
}
}
Object itemStackSpigot = spigotMethod.invoke(meta);
if (setUnbreakableMethod == null) {
setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE);
setUnbreakableMethod.setAccessible(true);
if (bukkitUnbreakableSupport == 1) {
meta.setUnbreakable(unbreakable);
} else {
if (spigotMethod == null) {
spigotMethod = meta.getClass().getDeclaredMethod("spigot");
spigotMethod.setAccessible(true);
}
final Object itemStackSpigot = spigotMethod.invoke(meta);
if (setUnbreakableMethod == null) {
setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE);
setUnbreakableMethod.setAccessible(true);
}
setUnbreakableMethod.invoke(itemStackSpigot, unbreakable);
}
setUnbreakableMethod.invoke(itemStackSpigot, unbreakable);
is.setItemMeta(meta);
} catch (Throwable t) {
} catch (final Throwable t) {
t.printStackTrace();
}
}
+80 -53
View File
@@ -1,18 +1,22 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.EnumUtil;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
// Suffixes can be appended on the end of a mob name to make it plural
// Entities without a suffix, will default to 's'
public enum Mob {
@@ -23,7 +27,8 @@ public enum Mob {
GIANT("Giant", Enemies.ENEMY, EntityType.GIANT),
HORSE("Horse", Enemies.FRIENDLY, EntityType.HORSE),
PIG("Pig", Enemies.FRIENDLY, EntityType.PIG),
PIGZOMB("PigZombie", Enemies.NEUTRAL, EntityType.PIG_ZOMBIE),
PIGZOMB("PigZombie", Enemies.NEUTRAL, MobCompat.ZOMBIFIED_PIGLIN),
ZOMBIFIED_PIGLIN("ZombifiedPiglin", Enemies.NEUTRAL, MobCompat.ZOMBIFIED_PIGLIN),
SHEEP("Sheep", Enemies.FRIENDLY, "", EntityType.SHEEP),
SKELETON("Skeleton", Enemies.ENEMY, EntityType.SKELETON),
SLIME("Slime", Enemies.ENEMY, EntityType.SLIME),
@@ -75,44 +80,36 @@ public enum Mob {
HUSK("Husk", Enemies.ENEMY, "HUSK"),
ILLUSIONER("Illusioner", Enemies.ENEMY, "ILLUSIONER"),
PARROT("Parrot", Enemies.NEUTRAL, "PARROT"),
TURTLE("Turtle", Enemies.NEUTRAL, "TURTLE"),
PHANTOM("Phantom", Enemies.ENEMY, "PHANTOM"),
COD("Cod", Enemies.NEUTRAL, "", "COD"),
SALMON("Salmon", Enemies.NEUTRAL, "", "SALMON"),
PUFFERFISH("Pufferfish", Enemies.NEUTRAL, "", "PUFFERFISH"),
TROPICAL_FISH("TropicalFish", Enemies.NEUTRAL, "", "TROPICAL_FISH"),
DROWNED("Drowned", Enemies.ENEMY, "DROWNED"),
DOLPHIN("Dolphin", Enemies.NEUTRAL, "DOLPHIN"),
CAT("Cat", Enemies.FRIENDLY, "CAT"),
FOX("Fox", Enemies.FRIENDLY, "es", "FOX"),
PANDA("Panda", Enemies.NEUTRAL, "PANDA"),
PILLAGER("Pillager", Enemies.ENEMY, "PILLAGER"),
RAVAGER("Ravager", Enemies.ENEMY, "RAVAGER"),
TRADER_LLAMA("TraderLlama", Enemies.FRIENDLY, "TRADER_LLAMA"),
WANDERING_TRADER("WanderingTrader", Enemies.FRIENDLY, "WANDERING_TRADER"),
BEE("Bee", Enemies.NEUTRAL, "BEE"),
STRAY("Stray", Enemies.ENEMY, "STRAY"),
HOGLIN("Hoglin", Enemies.ADULT_ENEMY, "HOGLIN"),
PIGLIN("Piglin", Enemies.ADULT_ENEMY, "PIGLIN"),
STRIDER("Strider", Enemies.FRIENDLY, "STRIDER"),
ZOGLIN("Zoglin", Enemies.ENEMY, "ZOGLIN"),
PIGLIN_BRUTE("PiglinBrute", Enemies.ADULT_ENEMY, "PIGLIN_BRUTE"),
;
public static final Logger logger = Logger.getLogger("Essentials");
Mob(String n, Enemies en, String s, EntityType type) {
this.suffix = s;
this.name = n;
this.type = en;
this.bukkitType = type;
}
Mob(String n, Enemies en, EntityType type) {
this.name = n;
this.type = en;
this.bukkitType = type;
}
Mob(String n, Enemies en, String typeName) {
this.name = n;
this.type = en;
EntityType entityType;
try {
entityType = EntityType.valueOf(typeName);
} catch (IllegalArgumentException ignored) {
entityType = null;
}
bukkitType = entityType;
}
public String suffix = "s";
final public String name;
final public Enemies type;
final private EntityType bukkitType;
private static final Map<String, Mob> hashMap = new HashMap<>();
private static final Map<EntityType, Mob> bukkitMap = new HashMap<>();
static {
for (Mob mob : Mob.values()) {
for (final Mob mob : Mob.values()) {
hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob);
if (mob.bukkitType != null) {
bukkitMap.put(mob.bukkitType, mob);
@@ -120,10 +117,49 @@ public enum Mob {
}
}
final public String name;
final public Enemies type;
final private EntityType bukkitType;
public String suffix = "s";
Mob(final String n, final Enemies en, final String s, final EntityType type) {
this.suffix = s;
this.name = n;
this.type = en;
this.bukkitType = type;
}
Mob(final String n, final Enemies en, final EntityType type) {
this.name = n;
this.type = en;
this.bukkitType = type;
}
Mob(final String n, final Enemies en, final String s, final String typeName) {
this.suffix = s;
this.name = n;
this.type = en;
bukkitType = EnumUtil.getEntityType(typeName);
}
Mob(final String n, final Enemies en, final String typeName) {
this.name = n;
this.type = en;
bukkitType = EnumUtil.getEntityType(typeName);
}
public static Set<String> getMobList() {
return Collections.unmodifiableSet(hashMap.keySet());
}
public static Mob fromName(final String name) {
return hashMap.get(name.toLowerCase(Locale.ENGLISH));
}
public static Mob fromBukkitType(final EntityType type) {
return bukkitMap.get(type);
}
public Entity spawn(final World world, final Server server, final Location loc) throws MobException {
final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass());
if (entity == null) {
@@ -133,31 +169,22 @@ public enum Mob {
return entity;
}
public enum Enemies {
FRIENDLY("friendly"),
NEUTRAL("neutral"),
ENEMY("enemy");
Enemies(final String type) {
this.type = type;
}
final protected String type;
}
public EntityType getType() {
return bukkitType;
}
public static Mob fromName(final String name) {
return hashMap.get(name.toLowerCase(Locale.ENGLISH));
}
public enum Enemies {
FRIENDLY("friendly"),
NEUTRAL("neutral"),
ENEMY("enemy"),
ADULT_ENEMY("adult_enemy");
public static Mob fromBukkitType(final EntityType type) {
return bukkitMap.get(type);
}
final protected String type;
Enemies(final String type) {
this.type = type;
}
}
public static class MobException extends Exception {
private static final long serialVersionUID = 1L;
@@ -0,0 +1,219 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fox;
import org.bukkit.entity.Llama;
import org.bukkit.entity.MushroomCow;
import org.bukkit.entity.Ocelot;
import org.bukkit.entity.Panda;
import org.bukkit.entity.Parrot;
import org.bukkit.entity.TropicalFish;
import org.bukkit.entity.Villager;
import java.lang.reflect.Method;
import static com.earth2me.essentials.utils.EnumUtil.getEntityType;
public final class MobCompat {
// Constants for mob interfaces added in later versions
@SuppressWarnings("rawtypes")
public static final Class RAIDER = ReflUtil.getClassCached("org.bukkit.entity.Raider");
// Constants for mobs added in later versions
public static final EntityType LLAMA = getEntityType("LLAMA");
public static final EntityType PARROT = getEntityType("PARROT");
public static final EntityType TROPICAL_FISH = getEntityType("TROPICAL_FISH");
public static final EntityType PANDA = getEntityType("PANDA");
public static final EntityType TRADER_LLAMA = getEntityType("TRADER_LLAMA");
public static final EntityType SHULKER = getEntityType("SHULKER");
public static final EntityType STRAY = getEntityType("STRAY");
public static final EntityType FOX = getEntityType("FOX");
public static final EntityType PHANTOM = getEntityType("PHANTOM");
// Constants for mobs that have changed since earlier versions
public static final EntityType CAT = getEntityType("CAT", "OCELOT");
public static final EntityType ZOMBIFIED_PIGLIN = getEntityType("ZOMBIFIED_PIGLIN", "PIG_ZOMBIE");
private MobCompat() {
}
// Older cats are Ocelots, whereas 1.14+ cats are Cats
public static void setCatType(final Entity entity, final CatType type) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
((Ocelot) entity).setCatType(Ocelot.Type.valueOf(type.ocelotTypeName));
} else {
final Class cat = ReflUtil.getClassCached("org.bukkit.entity.Cat");
final Class catType = ReflUtil.getClassCached("org.bukkit.entity.Cat$Type");
final Method setCatType = ReflUtil.getMethodCached(cat, "setCatType", catType);
try {
setCatType.invoke(entity, EnumUtil.valueOf(catType, type.catTypeName));
} catch (final Exception e) {
e.printStackTrace();
}
}
}
// Older villagers have professions and careers, 1.14+ villagers only have professions
public static void setVillagerProfession(final Entity entity, final VillagerProfession profession) {
if (!(entity instanceof Villager)) {
return;
}
final Villager villager = (Villager) entity;
villager.setProfession(profession.asEnum());
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
final Class villagerCareer = ReflUtil.getClassCached("org.bukkit.entity.Villager$Career");
final Method setCareer = ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareer);
try {
setCareer.invoke(entity, EnumUtil.valueOf(villagerCareer, profession.oldCareer));
} catch (final Exception e) {
e.printStackTrace();
}
}
}
// Only 1.14+ villagers have biome variants
public static void setVillagerType(final Entity entity, final String type) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
return;
}
if (entity instanceof Villager) {
((Villager) entity).setVillagerType(Villager.Type.valueOf(type));
}
}
// Llamas only exist in 1.11+
public static void setLlamaColor(final Entity entity, final String color) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_11_R01)) {
return;
}
if (entity instanceof Llama) {
((Llama) entity).setColor(Llama.Color.valueOf(color));
}
}
// Parrots only exist in 1.12+
public static void setParrotVariant(final Entity entity, final String variant) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) {
return;
}
if (entity instanceof Parrot) {
((Parrot) entity).setVariant(Parrot.Variant.valueOf(variant));
}
}
// Tropical fish only exist in 1.13+
public static void setTropicalFishPattern(final Entity entity, final String pattern) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) {
return;
}
if (entity instanceof TropicalFish) {
((TropicalFish) entity).setPattern(TropicalFish.Pattern.valueOf(pattern));
}
}
// Mushroom cow variant API only exists in 1.14+
public static void setMooshroomVariant(final Entity entity, final String variant) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
return;
}
if (entity instanceof MushroomCow) {
((MushroomCow) entity).setVariant(MushroomCow.Variant.valueOf(variant));
}
}
// Pandas only exists in 1.14+
public static void setPandaGene(final Entity entity, final String gene, final boolean mainGene) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
return;
}
if (entity instanceof Panda) {
final Panda panda = (Panda) entity;
final Panda.Gene pandaGene = Panda.Gene.valueOf(gene);
if (mainGene) {
panda.setMainGene(pandaGene);
} else {
panda.setHiddenGene(pandaGene);
}
}
}
// Foxes only exist in 1.14+
public static void setFoxType(final Entity entity, final String type) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) {
return;
}
if (entity instanceof Fox) {
((Fox) entity).setFoxType(Fox.Type.valueOf(type));
}
}
public enum CatType {
// These are (loosely) Mojang names for the cats
SIAMESE("SIAMESE", "SIAMESE_CAT"),
WHITE("WHITE", "SIAMESE_CAT"),
RED("RED", "RED_CAT"),
TABBY("TABBY", "RED_CAT"),
TUXEDO("BLACK", "BLACK_CAT"),
BRITISH_SHORTHAIR("BRITISH_SHORTHAIR", "SIAMESE_CAT"),
CALICO("CALICO", "RED_CAT"),
PERSIAN("PERSIAN", "RED_CAT"),
RAGDOLL("RAGDOLL", "SIAMESE_CAT"),
JELLIE("JELLIE", "SIAMESE_CAT"),
BLACK("ALL_BLACK", "BLACK_CAT"),
;
private final String catTypeName;
private final String ocelotTypeName;
CatType(final String catTypeName, final String ocelotTypeName) {
this.catTypeName = catTypeName;
this.ocelotTypeName = ocelotTypeName;
}
}
public enum VillagerProfession {
// These are 1.14+ villager professions mapped to their respective pre-V&P profession and career
NONE("FARMER", "FARMER", "NONE"),
ARMORER("BLACKSMITH", "ARMORER"),
BUTCHER("FARMER", "BUTCHER"),
CARTOGRAPHER("LIBRARIAN", "CARTOGRAPHER"),
CLERIC("PRIEST", "CLERIC"),
FARMER("FARMER", "FARMER"),
FISHERMAN("FARMER", "FISHERMAN"),
FLETCHER("FARMER", "FLETCHER"),
LEATHERWORKER("BUTCHER", "LEATHERWORKER"),
LIBRARIAN("LIBRARIAN", "LIBRARIAN"),
MASON(null, null, "MASON"),
NITWIT("NITWIT", "NITWIT"),
SHEPHERD("FARMER", "SHEPHERD"),
TOOLSMITH("BLACKSMITH", "TOOL_SMITH", "TOOLSMITH"),
WEAPONSMITH("BLACKSMITH", "WEAPON_SMITH", "WEAPONSMITH"),
;
private final String oldProfession;
private final String oldCareer;
private final String newProfession;
VillagerProfession(final String oldProfession, final String career) {
this.oldProfession = oldProfession;
this.oldCareer = career;
this.newProfession = career;
}
VillagerProfession(final String oldProfession, final String oldCareer, final String newProfession) {
this.oldProfession = oldProfession;
this.oldCareer = oldCareer;
this.newProfession = newProfession;
}
private Villager.Profession asEnum() {
return EnumUtil.valueOf(Villager.Profession.class, newProfession, oldProfession);
}
}
}
@@ -1,23 +1,47 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Phantom;
import org.bukkit.entity.Pig;
import org.bukkit.entity.Player;
import org.bukkit.entity.Raider;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.TropicalFish;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Colorable;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public enum MobData {
BABY_AGEABLE("baby", Ageable.class, Data.BABY, true),
ADULT_AGEABLE("adult", Ageable.class, Data.ADULT, true),
BABY_CAT("kitten", MobCompat.CAT, Data.BABY, false),
BABY_PIG("piglet", EntityType.PIG, Data.BABY, false),
BABY_WOLF("puppy", EntityType.WOLF, Data.BABY, false),
BABY_CHICKEN("chick", EntityType.CHICKEN, Data.BABY, false),
@@ -29,7 +53,7 @@ public enum MobData {
TAMED_TAMEABLE("tamed", Tameable.class, Data.TAMED, true),
TAME_TAMEABLE("tame", Tameable.class, Data.TAMED, false),
RANDOM_SHEEP("random", EntityType.SHEEP, Data.COLORABLE, true),
COLORABLE_SHEEP("", StringUtil.joinList(DyeColor.values()).toLowerCase(Locale.ENGLISH), EntityType.SHEEP, Data.COLORABLE, true),
COLORABLE_SHEEP("", Arrays.stream(DyeColor.values()).map(color -> color.name().toLowerCase(Locale.ENGLISH)).collect(Collectors.toList()), EntityType.SHEEP, Data.COLORABLE, true),
POLKA_HORSE("polka", EntityType.HORSE, Horse.Style.BLACK_DOTS, true),
SOOTY_HORSE("sooty", EntityType.HORSE, Horse.Style.BLACK_DOTS, false),
BLAZE_HORSE("blaze", EntityType.HORSE, Horse.Style.WHITE, true),
@@ -53,25 +77,31 @@ public enum MobData {
BAY_HORSE("bay", EntityType.HORSE, Horse.Color.BROWN, true),
BROWN_HORSE("brown", EntityType.HORSE, Horse.Color.BROWN, false),
SADDLE_HORSE("saddle", EntityType.HORSE, Data.HORSESADDLE, true),
GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, Material.GOLD_BARDING, true),
DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, Material.DIAMOND_BARDING, true),
ARMOR_HORSE("armor", EntityType.HORSE, Material.IRON_BARDING, true),
SIAMESE_CAT("siamese", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, true),
WHITE_CAT("white", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, false),
RED_CAT("red", EntityType.OCELOT, Ocelot.Type.RED_CAT, true),
ORANGE_CAT("orange", EntityType.OCELOT, Ocelot.Type.RED_CAT, false),
TABBY_CAT("tabby", EntityType.OCELOT, Ocelot.Type.RED_CAT, false),
BLACK_CAT("black", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, true),
TUXEDO_CAT("tuxedo", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, false),
GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, EnumUtil.getMaterial("GOLDEN_HORSE_ARMOR", "GOLD_BARDING"), true),
DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, EnumUtil.getMaterial("DIAMOND_HORSE_ARMOR", "DIAMOND_BARDING"), true),
ARMOR_HORSE("armor", EntityType.HORSE, EnumUtil.getMaterial("IRON_HORSE_ARMOR", "IRON_BARDING"), true),
SIAMESE_CAT("siamese", MobCompat.CAT, MobCompat.CatType.SIAMESE, true),
WHITE_CAT("white", MobCompat.CAT, MobCompat.CatType.WHITE, false),
RED_CAT("red", MobCompat.CAT, MobCompat.CatType.RED, true),
ORANGE_CAT("orange", MobCompat.CAT, MobCompat.CatType.RED, false),
TABBY_CAT("tabby", MobCompat.CAT, MobCompat.CatType.TABBY, true),
BLACK_CAT("black", MobCompat.CAT, MobCompat.CatType.BLACK, true),
TUXEDO_CAT("tuxedo", MobCompat.CAT, MobCompat.CatType.TUXEDO, true),
BRITISH_SHORTHAIR_CAT("britishshorthair", MobCompat.CAT, MobCompat.CatType.BRITISH_SHORTHAIR, true),
CALICO_CAT("calico", MobCompat.CAT, MobCompat.CatType.CALICO, true),
PERSIAN_CAT("persian", MobCompat.CAT, MobCompat.CatType.PERSIAN, true),
RAGDOLL_CAT("ragdoll", MobCompat.CAT, MobCompat.CatType.RAGDOLL, true),
JELLIE_CAT("jellie", MobCompat.CAT, MobCompat.CatType.JELLIE, true),
ALL_BLACK_CAT("allblack", MobCompat.CAT, MobCompat.CatType.BLACK, true),
BABY_ZOMBIE("baby", EntityType.ZOMBIE.getEntityClass(), Data.BABYZOMBIE, true),
ADULT_ZOMBIE("adult", EntityType.ZOMBIE.getEntityClass(), Data.ADULTZOMBIE, true),
DIAMOND_SWORD_ZOMBIE("diamondsword", EntityType.ZOMBIE.getEntityClass(), Material.DIAMOND_SWORD, true),
GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), Material.GOLD_SWORD, true),
GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD"), true),
IRON_SWORD_ZOMBIE("ironsword", EntityType.ZOMBIE.getEntityClass(), Material.IRON_SWORD, true),
STONE_SWORD_ZOMBIE("stonesword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, false),
SWORD_ZOMBIE("sword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, true),
DIAMOND_SWORD_SKELETON("diamondsword", EntityType.SKELETON, Material.DIAMOND_SWORD, true),
GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, Material.GOLD_SWORD, true),
GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD"), true),
IRON_SWORD_SKELETON("ironsword", EntityType.SKELETON, Material.IRON_SWORD, true),
STONE_SWORD_SKELETON("stonesword", EntityType.SKELETON, Material.STONE_SWORD, false),
SWORD_SKELETON("sword", EntityType.SKELETON, Material.STONE_SWORD, true),
@@ -82,71 +112,114 @@ public enum MobData {
SADDLE_PIG("saddle", EntityType.PIG, Data.PIGSADDLE, true),
ANGRY_WOLF("angry", EntityType.WOLF, Data.ANGRY, true),
RABID_WOLF("rabid", EntityType.WOLF, Data.ANGRY, false),
FARMER_VILLAGER("farmer", EntityType.VILLAGER, Villager.Profession.FARMER, true),
LIBRARIAN_VILLAGER("librarian", EntityType.VILLAGER, Villager.Profession.LIBRARIAN, true),
PRIEST_VILLAGER("priest", EntityType.VILLAGER, Villager.Profession.PRIEST, true),
FATHER_VILLAGER("father", EntityType.VILLAGER, Villager.Profession.PRIEST, false),
SMITH_VILLAGER("smith", EntityType.VILLAGER, Villager.Profession.BLACKSMITH, true),
BUTCHER_VILLAGER("butcher", EntityType.VILLAGER, Villager.Profession.BUTCHER, true),
SIZE_SLIME("", "<1-100>", EntityType.SLIME.getEntityClass(), Data.SIZE, true),
NUM_EXPERIENCE_ORB("", "<1-2000000000>", EntityType.EXPERIENCE_ORB, Data.EXP, true),
RED_PARROT("red", EntityType.PARROT, Parrot.Variant.RED, true),
GREEN_PARROT("green", EntityType.PARROT, Parrot.Variant.GREEN, true),
BLUE_PARROT("blue", EntityType.PARROT, Parrot.Variant.BLUE, true),
CYAN_PARROT("cyan", EntityType.PARROT, Parrot.Variant.CYAN, true),
GRAY_PARROT("gray", EntityType.PARROT, Parrot.Variant.GRAY, true),
VILLAGER("villager", EntityType.VILLAGER, MobCompat.VillagerProfession.NONE, true),
ARMORER_VILLAGER("armorer", EntityType.VILLAGER, MobCompat.VillagerProfession.ARMORER, true),
BUTCHER_VILLAGER("butcher", EntityType.VILLAGER, MobCompat.VillagerProfession.BUTCHER, true),
CARTOGRAPHER_VILLAGER("cartographer", EntityType.VILLAGER, MobCompat.VillagerProfession.CARTOGRAPHER, true),
CLERIC_VILLAGER("cleric", EntityType.VILLAGER, MobCompat.VillagerProfession.CLERIC, true),
FARMER_VILLAGER("farmer", EntityType.VILLAGER, MobCompat.VillagerProfession.FARMER, true),
FISHERMAN_VILLAGER("fisherman", EntityType.VILLAGER, MobCompat.VillagerProfession.FISHERMAN, true),
FLETCHER_VILLAGER("fletcher", EntityType.VILLAGER, MobCompat.VillagerProfession.FLETCHER, true),
LEATHERWORKER_VILLAGER("leatherworker", EntityType.VILLAGER, MobCompat.VillagerProfession.LEATHERWORKER, true),
LIBRARIAN_VILLAGER("librarian", EntityType.VILLAGER, MobCompat.VillagerProfession.LIBRARIAN, true),
MASON_VILLAGER("mason", EntityType.VILLAGER, MobCompat.VillagerProfession.MASON, true),
NITWIT_VILLAGER("nitwit", EntityType.VILLAGER, MobCompat.VillagerProfession.NITWIT, true),
SHEPHERD_VILLAGER("shepherd", EntityType.VILLAGER, MobCompat.VillagerProfession.SHEPHERD, true),
TOOLSMITH_VILLAGER("toolsmith", EntityType.VILLAGER, MobCompat.VillagerProfession.TOOLSMITH, true),
WEAPONSMITH_VILLAGER("weaponsmith", EntityType.VILLAGER, MobCompat.VillagerProfession.WEAPONSMITH, true),
DESERT_VILLAGER("desert", EntityType.VILLAGER, "villagertype:DESERT", true),
JUNGLE_VILLAGER("jungle", EntityType.VILLAGER, "villagertype:JUNGLE", true),
PLAINS_VILLAGER("plains", EntityType.VILLAGER, "villagertype:PLAINS", true),
SAVANNA_VILLAGER("savanna", EntityType.VILLAGER, "villagertype:SAVANNA", true),
SNOWY_VILLAGER("snowy", EntityType.VILLAGER, "villagertype:SNOWY", true),
SWAMP_VILLAGER("swamp", EntityType.VILLAGER, "villagertype:SWAMP", true),
TAIGA_VILLAGER("taiga", EntityType.VILLAGER, "villagertype:TAIGA", true),
SIZE_SLIME("", Collections.singletonList("<1-100>"), EntityType.SLIME.getEntityClass(), Data.SIZE, true),
NUM_EXPERIENCE_ORB("", Collections.singletonList("<1-2000000000>"), EntityType.EXPERIENCE_ORB, Data.EXP, true),
RED_PARROT("red", MobCompat.PARROT, "parrot:RED", true),
GREEN_PARROT("green", MobCompat.PARROT, "parrot:GREEN", true),
BLUE_PARROT("blue", MobCompat.PARROT, "parrot:BLUE", true),
CYAN_PARROT("cyan", MobCompat.PARROT, "parrot:CYAN", true),
GRAY_PARROT("gray", MobCompat.PARROT, "parrot:GRAY", true),
KOB_TROPICAL_FISH("kob", MobCompat.TROPICAL_FISH, "tropicalfish:KOB", true),
SUNSTREAK_TROPICAL_FISH("sunstreak", MobCompat.TROPICAL_FISH, "tropicalfish:SUNSTREAK", true),
SNOOPER_TROPICAL_FISH("snooper", MobCompat.TROPICAL_FISH, "tropicalfish:SNOOPER", true),
DASHER_TROPICAL_FISH("dasher", MobCompat.TROPICAL_FISH, "tropicalfish:DASHER", true),
BRINELY_TROPICAL_FISH("brinely", MobCompat.TROPICAL_FISH, "tropicalfish:BRINELY", true),
SPOTTY_TROPICAL_FISH("spotty", MobCompat.TROPICAL_FISH, "tropicalfish:SPOTTY", true),
FLOPPER_TROPICAL_FISH("flopper", MobCompat.TROPICAL_FISH, "tropicalfish:FLOPPER", true),
STRIPEY_TROPICAL_FISH("stripey", MobCompat.TROPICAL_FISH, "tropicalfish:STRIPEY", true),
GLITTER_TROPICAL_FISH("glitter", MobCompat.TROPICAL_FISH, "tropicalfish:GLITTER", true),
BLOCKFISH_TROPICAL_FISH("blockfish", MobCompat.TROPICAL_FISH, "tropicalfish:BLOCKFISH", true),
BETTY_TROPICAL_FISH("betty", MobCompat.TROPICAL_FISH, "tropicalfish:BETTY", true),
CLAYFISH_TROPICAL_FISH("clayfish", MobCompat.TROPICAL_FISH, "tropicalfish:CLAYFISH", true),
BROWN_MUSHROOM_COW("brown", EntityType.MUSHROOM_COW, "mooshroom:BROWN", true),
RED_MUSHROOM_COW("red", EntityType.MUSHROOM_COW, "mooshroom:RED", true),
AGGRESSIVE_PANDA_MAIN("aggressive", MobCompat.PANDA, "pandamain:AGGRESSIVE", true),
LAZY_PANDA_MAIN("lazy", MobCompat.PANDA, "pandamain:LAZY", true),
WORRIED_PANDA_MAIN("worried", MobCompat.PANDA, "pandamain:WORRIED", true),
PLAYFUL_PANDA_MAIN("playful", MobCompat.PANDA, "pandamain:PLAYFUL", true),
BROWN_PANDA_MAIN("brown", MobCompat.PANDA, "pandamain:BROWN", true),
WEAK_PANDA_MAIN("weak", MobCompat.PANDA, "pandamain:WEAK", true),
AGGRESSIVE_PANDA_HIDDEN("aggressive_hidden", MobCompat.PANDA, "pandahidden:AGGRESSIVE", true),
LAZY_PANDA_HIDDEN("lazy_hidden", MobCompat.PANDA, "pandahidden:LAZY", true),
WORRIED_PANDA_HIDDEN("worried_hidden", MobCompat.PANDA, "pandahidden:WORRIED", true),
PLAYFUL_PANDA_HIDDEN("playful_hidden", MobCompat.PANDA, "pandahidden:PLAYFUL", true),
BROWN_PANDA_HIDDEN("brown_hidden", MobCompat.PANDA, "pandahidden:BROWN", true),
WEAK_PANDA_HIDDEN("weak_hidden", MobCompat.PANDA, "pandahidden:WEAK", true),
CREAMY_LLAMA("creamy", MobCompat.LLAMA, "llama:CREAMY", true),
WHITE_LLAMA("white", MobCompat.LLAMA, "llama:WHITE", true),
BROWN_LLAMA("brown", MobCompat.LLAMA, "llama:BROWN", true),
GRAY_LLAMA("gray", MobCompat.LLAMA, "llama:GRAY", true),
CREAMY_TRADER_LLAMA("creamy", MobCompat.TRADER_LLAMA, "llama:CREAMY", true),
WHITE_TRADER_LLAMA("white", MobCompat.TRADER_LLAMA, "llama:WHITE", true),
BROWN_TRADER_LLAMA("brown", MobCompat.TRADER_LLAMA, "llama:BROWN", true),
GRAY_TRADER_LLAMA("gray", MobCompat.TRADER_LLAMA, "llama:GRAY", true),
RANDOM_SHULKER("random", MobCompat.SHULKER, Data.COLORABLE, true),
COLORABLE_SHULKER("", Arrays.stream(DyeColor.values()).map(color -> color.name().toLowerCase(Locale.ENGLISH)).collect(Collectors.toList()), MobCompat.SHULKER, Data.COLORABLE, true),
RED_FOX("red", MobCompat.FOX, "fox:RED", true),
SNOW_FOX("snow", MobCompat.FOX, "fox:SNOW", true),
SIZE_PHANTOM("", Collections.singletonList("<1-100>"), MobCompat.PHANTOM, Data.SIZE, true),
RAID_LEADER("leader", MobCompat.RAIDER, Data.RAID_LEADER, true),
TROPICAL_FISH_BODY_COLOR("fish_body_color", Arrays.stream(DyeColor.values()).map(color -> color.name().toLowerCase(Locale.ENGLISH) + "body").collect(Collectors.toList()), MobCompat.TROPICAL_FISH, Data.FISH_BODY_COLOR, true),
TROPICAL_FISH_PATTERN_COLOR("fish_pattern_color", Arrays.stream(DyeColor.values()).map(color -> color.name().toLowerCase(Locale.ENGLISH) + "pattern").collect(Collectors.toList()), MobCompat.TROPICAL_FISH, Data.FISH_PATTERN_COLOR, true),
;
public enum Data {
ADULT,
BABY,
CHEST,
ADULTZOMBIE,
BABYZOMBIE,
HORSESADDLE,
PIGSADDLE,
ELECTRIFIED,
ANGRY,
TAMED,
COLORABLE,
EXP,
SIZE
}
public static final Logger logger = Logger.getLogger("Essentials");
MobData(String n, Object type, Object value, boolean isPublic) {
this.nickname = n;
this.matched = n;
this.helpMessage = n;
this.type = type;
this.value = value;
this.isPublic = isPublic;
}
MobData(String n, String h, Object type, Object value, boolean isPublic) {
this.nickname = n;
this.matched = n;
this.helpMessage = h;
this.type = type;
this.value = value;
this.isPublic = isPublic;
}
final private String nickname;
final private String helpMessage;
final private List<String> suggestions;
final private Object type;
final private Object value;
final private boolean isPublic;
private String matched;
public static LinkedHashMap<String, MobData> getPossibleData(final Entity spawned, boolean publicOnly) {
LinkedHashMap<String, MobData> mobList = new LinkedHashMap<String, MobData>();
for (MobData data : MobData.values()) {
if (data.type instanceof EntityType && spawned.getType().equals(data.type) && ((publicOnly && data.isPublic) || !publicOnly)) {
MobData(final String n, final Object type, final Object value, final boolean isPublic) {
this.nickname = n;
this.matched = n;
this.suggestions = Collections.singletonList(n);
this.type = type;
this.value = value;
this.isPublic = isPublic;
}
MobData(final String n, final List<String> s, final Object type, final Object value, final boolean isPublic) {
this.nickname = n;
this.matched = n;
this.suggestions = s;
this.type = type;
this.value = value;
this.isPublic = isPublic;
}
public static LinkedHashMap<String, MobData> getPossibleData(final Entity spawned, final boolean publicOnly) {
final LinkedHashMap<String, MobData> mobList = new LinkedHashMap<>();
for (final MobData data : MobData.values()) {
if (data.type == null || (publicOnly && !data.isPublic)) {
continue;
}
if (data.type instanceof EntityType && spawned.getType().equals(data.type)) {
mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data);
} else if (data.type instanceof Class && ((Class) data.type).isAssignableFrom(spawned.getClass()) && ((publicOnly && data.isPublic) || !publicOnly)) {
} else if (data.type instanceof Class && ((Class) data.type).isAssignableFrom(spawned.getClass())) {
mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data);
}
}
@@ -155,11 +228,11 @@ public enum MobData {
}
public static List<String> getValidHelp(final Entity spawned) {
List<String> output = new ArrayList<String>();
LinkedHashMap<String, MobData> posData = getPossibleData(spawned, true);
final List<String> output = new ArrayList<>();
final LinkedHashMap<String, MobData> posData = getPossibleData(spawned, true);
for (MobData data : posData.values()) {
output.add(data.helpMessage);
for (final MobData data : posData.values()) {
output.add(StringUtil.joinList(data.suggestions));
}
return output;
}
@@ -169,10 +242,12 @@ public enum MobData {
return null;
}
LinkedHashMap<String, MobData> posData = getPossibleData(spawned, false);
for (String data : posData.keySet()) {
if (name.contains(data)) {
return posData.get(data);
final LinkedHashMap<String, MobData> posData = getPossibleData(spawned, false);
for (final MobData data : posData.values()) {
for (final String suggestion : data.suggestions) {
if (name.contains(suggestion)) {
return data;
}
}
}
return null;
@@ -196,14 +271,14 @@ public enum MobData {
} else if (this.value.equals(Data.ELECTRIFIED)) {
((Creeper) spawned).setPowered(true);
} else if (this.value.equals(Data.HORSESADDLE)) {
final Horse horse = ((Horse) spawned);
final Horse horse = (Horse) spawned;
horse.setTamed(true);
horse.setOwner(target);
horse.getInventory().setSaddle(new ItemStack(Material.SADDLE, 1));
} else if (this.value.equals(Data.PIGSADDLE)) {
((Pig) spawned).setSaddle(true);
} else if (this.value.equals(Data.TAMED)) {
final Tameable tameable = ((Tameable) spawned);
final Tameable tameable = (Tameable) spawned;
tameable.setTamed(true);
tameable.setOwner(target);
} else if (this.value.equals(Data.COLORABLE)) {
@@ -216,31 +291,36 @@ public enum MobData {
((Colorable) spawned).setColor(DyeColor.valueOf(color));
}
this.matched = rawData;
} catch (Exception e) {
} catch (final Exception e) {
throw new Exception(tl("sheepMalformedColor"), e);
}
} else if (this.value.equals(Data.EXP)) {
try {
((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData));
this.matched = rawData;
} catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
throw new Exception(tl("invalidNumber"), e);
}
} else if (this.value.equals(Data.SIZE)) {
try {
((Slime) spawned).setSize(Integer.parseInt(rawData));
final int size = Integer.parseInt(rawData);
if (spawned instanceof Slime) {
((Slime) spawned).setSize(size);
} else if (spawned.getType() == MobCompat.PHANTOM) {
((Phantom) spawned).setSize(size);
}
this.matched = rawData;
} catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
throw new Exception(tl("slimeMalformedSize"), e);
}
} else if (this.value instanceof Horse.Color) {
((Horse) spawned).setColor((Horse.Color) this.value);
} else if (this.value instanceof Horse.Style) {
((Horse) spawned).setStyle((Horse.Style) this.value);
} else if (this.value instanceof Ocelot.Type) {
((Ocelot) spawned).setCatType((Ocelot.Type) this.value);
} else if (this.value instanceof Villager.Profession) {
((Villager) spawned).setProfession((Villager.Profession) this.value);
} else if (this.value instanceof MobCompat.CatType) {
MobCompat.setCatType(spawned, (MobCompat.CatType) this.value);
} else if (this.value instanceof MobCompat.VillagerProfession) {
MobCompat.setVillagerProfession(spawned, (MobCompat.VillagerProfession) this.value);
} else if (this.value instanceof Material) {
if (this.type.equals(EntityType.HORSE)) {
((Horse) spawned).setTamed(true);
@@ -250,8 +330,75 @@ public enum MobData {
InventoryWorkaround.setItemInMainHand(invent, new ItemStack((Material) this.value, 1));
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
}
} else if (this.value instanceof Parrot.Variant) {
((Parrot) spawned).setVariant((Parrot.Variant) this.value);
} else if (this.value.equals(Data.RAID_LEADER)) {
((Raider) spawned).setPatrolLeader(true);
} else if (this.value.equals(Data.FISH_BODY_COLOR)) {
for (final String match : TROPICAL_FISH_BODY_COLOR.suggestions) {
if (rawData.contains(match)) {
this.matched = match;
final String color = match.substring(0, match.indexOf("body")).toUpperCase(Locale.ENGLISH);
((TropicalFish) spawned).setBodyColor(DyeColor.valueOf(color));
break;
}
}
} else if (this.value.equals(Data.FISH_PATTERN_COLOR)) {
for (final String match : TROPICAL_FISH_PATTERN_COLOR.suggestions) {
if (rawData.contains(match)) {
this.matched = match;
final String color = match.substring(0, match.indexOf("pattern")).toUpperCase(Locale.ENGLISH);
((TropicalFish) spawned).setPatternColor(DyeColor.valueOf(color));
break;
}
}
} else if (this.value instanceof String) {
final String[] split = ((String) this.value).split(":");
switch (split[0]) {
case "parrot":
MobCompat.setParrotVariant(spawned, split[1]);
break;
case "tropicalfish":
MobCompat.setTropicalFishPattern(spawned, split[1]);
break;
case "mooshroom":
MobCompat.setMooshroomVariant(spawned, split[1]);
break;
case "pandamain":
MobCompat.setPandaGene(spawned, split[1], true);
break;
case "pandahidden":
MobCompat.setPandaGene(spawned, split[1], false);
break;
case "llama":
MobCompat.setLlamaColor(spawned, split[1]);
break;
case "villagertype":
MobCompat.setVillagerType(spawned, split[1]);
break;
case "fox":
MobCompat.setFoxType(spawned, split[1]);
break;
}
} else {
logger.warning("Unknown mob data type: " + this.toString());
}
}
public enum Data {
ADULT,
BABY,
CHEST,
ADULTZOMBIE,
BABYZOMBIE,
HORSESADDLE,
PIGSADDLE,
ELECTRIFIED,
ANGRY,
TAMED,
COLORABLE,
EXP,
SIZE,
RAID_LEADER,
FISH_BODY_COLOR,
FISH_PATTERN_COLOR,
}
}
@@ -5,7 +5,6 @@ import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class PlayerExtension {
protected Player base;
@@ -1,20 +1,30 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public final class PlayerList {
private PlayerList() {
}
public class PlayerList {
// Cosmetic list formatting
public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) {
final StringBuilder groupString = new StringBuilder();
Collections.sort(users);
boolean needComma = false;
for (User user : users) {
for (final User user : users) {
if (needComma) {
groupString.append(seperator);
}
@@ -27,6 +37,9 @@ public class PlayerList {
}
user.setDisplayNick();
groupString.append(user.getDisplayName());
if (ess.getSettings().realNamesOnList() && !ChatColor.stripColor(user.getDisplayName()).equals(user.getName())) {
groupString.append(" (").append(user.getName()).append(")");
}
groupString.append("\u00a7f");
}
return groupString.toString();
@@ -34,18 +47,18 @@ public class PlayerList {
// Produce a user summary: There are 5 out of maximum 10 players online.
public static String listSummary(final IEssentials ess, final User user, final boolean showHidden) {
Server server = ess.getServer();
final Server server = ess.getServer();
int playerHidden = 0;
int hiddenCount = 0;
for (User onlinePlayer : ess.getOnlineUsers()) {
for (final User onlinePlayer : ess.getOnlineUsers()) {
if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase()))) {
playerHidden++;
if (showHidden || user.getBase().canSee(onlinePlayer.getBase())) {
if (showHidden || user != null && user.getBase().canSee(onlinePlayer.getBase())) {
hiddenCount++;
}
}
}
String online;
final String online;
if (hiddenCount > 0) {
online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers());
} else {
@@ -55,19 +68,14 @@ public class PlayerList {
}
// Build the basic player list, divided by groups.
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final User sender, final boolean showHidden) {
Server server = ess.getServer();
final Map<String, List<User>> playerList = new HashMap<String, List<User>>();
for (User onlineUser : ess.getOnlineUsers()) {
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final IUser sender, final boolean showHidden) {
final Map<String, List<User>> playerList = new HashMap<>();
for (final User onlineUser : ess.getOnlineUsers()) {
if ((sender == null && !showHidden && onlineUser.isHidden()) || (sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase()))) {
continue;
}
final String group = FormatUtil.stripFormat(FormatUtil.stripEssentialsFormat(onlineUser.getGroup().toLowerCase()));
List<User> list = playerList.get(group);
if (list == null) {
list = new ArrayList<User>();
playerList.put(group, list);
}
final List<User> list = playerList.computeIfAbsent(group, k -> new ArrayList<>());
list.add(onlineUser);
}
return playerList;
@@ -76,16 +84,16 @@ public class PlayerList {
// Handle the merging of groups
public static List<User> getMergedList(final IEssentials ess, final Map<String, List<User>> playerList, final String groupName) {
final Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet();
final List<User> users = new ArrayList<User>();
for (String configGroup : configGroups) {
final List<User> users = new ArrayList<>();
for (final String configGroup : configGroups) {
if (configGroup.equalsIgnoreCase(groupName)) {
String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" ");
final String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" ");
for (String groupValue : groupValues) {
groupValue = groupValue.toLowerCase(Locale.ENGLISH);
if (groupValue == null || groupValue.isEmpty()) {
if (groupValue.isEmpty()) {
continue;
}
List<User> u = playerList.get(groupValue.trim());
final List<User> u = playerList.get(groupValue.trim());
if (u == null || u.isEmpty()) {
continue;
}
@@ -104,20 +112,17 @@ public class PlayerList {
if (groupUsers != null && !groupUsers.isEmpty()) {
users.addAll(groupUsers);
}
if (users == null || users.isEmpty()) {
if (users.isEmpty()) {
throw new Exception(tl("groupDoesNotExist"));
}
final StringBuilder displayGroupName = new StringBuilder();
displayGroupName.append(Character.toTitleCase(groupName.charAt(0)));
displayGroupName.append(groupName.substring(1));
return outputFormat(displayGroupName.toString(), listUsers(ess, users, ", "));
final String displayGroupName = Character.toTitleCase(groupName.charAt(0)) +
groupName.substring(1);
return outputFormat(displayGroupName, listUsers(ess, users, ", "));
}
// Build the output string
public static String outputFormat(final String group, final String message) {
final StringBuilder outputString = new StringBuilder();
outputString.append(tl("listGroupTag", FormatUtil.replaceFormat(group)));
outputString.append(message);
return outputString.toString();
return tl("listGroupTag", FormatUtil.replaceFormat(group)) +
message;
}
}
@@ -4,11 +4,10 @@ import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class PlayerTarget implements ITarget {
private final String name;
public PlayerTarget(Player entity) {
public PlayerTarget(final Player entity) {
this.name = entity.getName();
}
@@ -16,4 +15,4 @@ public class PlayerTarget implements ITarget {
public Location getLocation() {
return Bukkit.getServer().getPlayerExact(name).getLocation();
}
}
}
@@ -9,10 +9,9 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Potions {
private static final Map<String, PotionEffectType> POTIONS = new HashMap<String, PotionEffectType>();
private static final Map<String, PotionEffectType> ALIASPOTIONS = new HashMap<String, PotionEffectType>();
public final class Potions {
private static final Map<String, PotionEffectType> POTIONS = new HashMap<>();
private static final Map<String, PotionEffectType> ALIASPOTIONS = new HashMap<>();
static {
@@ -124,10 +123,14 @@ public class Potions {
POTIONS.put("luck", PotionEffectType.LUCK);
POTIONS.put("unluck", PotionEffectType.UNLUCK);
} catch (Throwable ignored) {}
} catch (final Throwable ignored) {
}
}
public static PotionEffectType getByName(String name) {
private Potions() {
}
public static PotionEffectType getByName(final String name) {
PotionEffectType peffect;
if (NumberUtil.isInt(name)) {
peffect = PotionEffectType.getById(Integer.parseInt(name));
@@ -0,0 +1,209 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.VersionUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.InvalidWorldException;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Biome;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
public class RandomTeleport implements IConf {
private static final Random RANDOM = new Random();
private static final int HIGHEST_BLOCK_Y_OFFSET = VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_15_R01) ? 1 : 0;
private final IEssentials essentials;
private final EssentialsConf config;
private final ConcurrentLinkedQueue<Location> cachedLocations = new ConcurrentLinkedQueue<>();
public RandomTeleport(final IEssentials essentials) {
this.essentials = essentials;
final File file = new File(essentials.getDataFolder(), "tpr.yml");
config = new EssentialsConf(file);
config.setTemplateName("/tpr.yml");
config.options().copyHeader(true);
reloadConfig();
}
@Override
public void reloadConfig() {
config.load();
cachedLocations.clear();
}
public Location getCenter() {
try {
final Location center = config.getLocation("center", essentials.getServer());
if (center != null) {
return center;
}
} catch (final InvalidWorldException ignored) {
}
final Location center = essentials.getServer().getWorlds().get(0).getWorldBorder().getCenter();
center.setY(center.getWorld().getHighestBlockYAt(center) + 1);
setCenter(center);
return center;
}
public void setCenter(final Location center) {
config.setProperty("center", center);
config.save();
}
public double getMinRange() {
return config.getDouble("min-range", 0d);
}
public void setMinRange(final double minRange) {
config.setProperty("min-range", minRange);
config.save();
}
public double getMaxRange() {
return config.getDouble("max-range", getCenter().getWorld().getWorldBorder().getSize() / 2);
}
public void setMaxRange(final double maxRange) {
config.setProperty("max-range", maxRange);
config.save();
}
public Set<Biome> getExcludedBiomes() {
final List<String> biomeNames = config.getStringList("excluded-biomes");
final Set<Biome> excludedBiomes = new HashSet<>();
for (final String biomeName : biomeNames) {
try {
excludedBiomes.add(Biome.valueOf(biomeName.toUpperCase()));
} catch (final IllegalArgumentException ignored) {
}
}
return excludedBiomes;
}
public int getFindAttempts() {
return config.getInt("find-attempts", 10);
}
public int getCacheThreshold() {
return config.getInt("cache-threshold", 10);
}
public boolean getPreCache() {
return config.getBoolean("pre-cache", false);
}
public Queue<Location> getCachedLocations() {
return cachedLocations;
}
// Get a random location; cached if possible. Otherwise on demand.
public CompletableFuture<Location> getRandomLocation(final Location center, final double minRange, final double maxRange) {
final int findAttempts = this.getFindAttempts();
final Queue<Location> cachedLocations = this.getCachedLocations();
// Try to build up the cache if it is below the threshold
if (cachedLocations.size() < this.getCacheThreshold()) {
cacheRandomLocations(center, minRange, maxRange);
}
final CompletableFuture<Location> future = new CompletableFuture<>();
// Return a random location immediately if one is available, otherwise try to find one now
if (cachedLocations.isEmpty()) {
attemptRandomLocation(findAttempts, center, minRange, maxRange).thenAccept(future::complete);
} else {
future.complete(cachedLocations.poll());
}
return future;
}
// Prompts caching random valid locations, up to a maximum number of attempts
public void cacheRandomLocations(final Location center, final double minRange, final double maxRange) {
essentials.getServer().getScheduler().scheduleSyncDelayedTask(essentials, () -> {
for (int i = 0; i < this.getFindAttempts(); ++i) {
calculateRandomLocation(center, minRange, maxRange).thenAccept(location -> {
if (isValidRandomLocation(location)) {
this.getCachedLocations().add(location);
}
});
}
});
}
// Recursively attempt to find a random location. After a maximum number of attempts, the center is returned.
private CompletableFuture<Location> attemptRandomLocation(final int attempts, final Location center, final double minRange, final double maxRange) {
final CompletableFuture<Location> future = new CompletableFuture<>();
if (attempts > 0) {
calculateRandomLocation(center, minRange, maxRange).thenAccept(location -> {
if (isValidRandomLocation(location)) {
future.complete(location);
} else {
attemptRandomLocation(attempts - 1, center, minRange, maxRange).thenAccept(future::complete);
}
});
} else {
future.complete(center);
}
return future;
}
// Calculates a random location asynchronously.
private CompletableFuture<Location> calculateRandomLocation(final Location center, final double minRange, final double maxRange) {
final CompletableFuture<Location> future = new CompletableFuture<>();
// Find an equally distributed offset by randomly rotating a point inside a rectangle about the origin
final double rectX = RANDOM.nextDouble() * (maxRange - minRange) + minRange;
final double rectZ = RANDOM.nextDouble() * (maxRange + minRange) - minRange;
final double offsetX;
final double offsetZ;
final int transform = RANDOM.nextInt(4);
if (transform == 0) {
offsetX = rectX;
offsetZ = rectZ;
} else if (transform == 1) {
offsetX = -rectZ;
offsetZ = rectX;
} else if (transform == 2) {
offsetX = -rectX;
offsetZ = -rectZ;
} else {
offsetX = rectZ;
offsetZ = -rectX;
}
final Location location = new Location(
center.getWorld(),
center.getX() + offsetX,
center.getWorld().getMaxHeight(),
center.getZ() + offsetZ,
360 * RANDOM.nextFloat() - 180,
0
);
PaperLib.getChunkAtAsync(location).thenAccept(chunk -> {
if (World.Environment.NETHER.equals(center.getWorld().getEnvironment())) {
location.setY(getNetherYAt(location));
} else {
location.setY(center.getWorld().getHighestBlockYAt(location) + HIGHEST_BLOCK_Y_OFFSET);
}
future.complete(location);
});
return future;
}
// Returns an appropriate elevation for a given location in the nether, or -1 if none is found
private double getNetherYAt(final Location location) {
for (int y = 32; y < location.getWorld().getMaxHeight() / 2; ++y) {
if (!LocationUtil.isBlockUnsafe(location.getWorld(), location.getBlockX(), y, location.getBlockZ())) {
return y;
}
}
return -1;
}
private boolean isValidRandomLocation(final Location location) {
return location.getBlockY() > 0 && !this.getExcludedBiomes().contains(location.getBlock().getBiome());
}
}
File diff suppressed because it is too large. Load diff
@@ -2,6 +2,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.Mob.MobException;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.IEssentials;
@@ -9,20 +10,39 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.PigZombie;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public final class SpawnMob {
private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET");
private static final Material GOLDEN_CHESTPLATE = EnumUtil.getMaterial("GOLDEN_CHESTPLATE", "GOLD_CHESTPLATE");
private static final Material GOLDEN_LEGGINGS = EnumUtil.getMaterial("GOLDEN_LEGGINGS", "GOLD_LEGGINGS");
private static final Material GOLDEN_BOOTS = EnumUtil.getMaterial("GOLDEN_BOOTS", "GOLD_BOOTS");
private static final Material GOLDEN_SWORD = EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD");
private SpawnMob() {
}
public class SpawnMob {
public static String mobList(final User user) {
final Set<String> mobList = Mob.getMobList();
final Set<String> availableList = new HashSet<String>();
for (String mob : mobList) {
final Set<String> availableList = new HashSet<>();
for (final String mob : mobList) {
if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) {
availableList.add(mob);
}
@@ -34,24 +54,24 @@ public class SpawnMob {
}
public static List<String> mobParts(final String mobString) {
String[] mobParts = mobString.split(",");
final String[] mobParts = mobString.split(",");
List<String> mobs = new ArrayList<String>();
final List<String> mobs = new ArrayList<>();
for (String mobPart : mobParts) {
String[] mobDatas = mobPart.split(":");
for (final String mobPart : mobParts) {
final String[] mobDatas = mobPart.split(":");
mobs.add(mobDatas[0]);
}
return mobs;
}
public static List<String> mobData(final String mobString) {
String[] mobParts = mobString.split(",");
final String[] mobParts = mobString.split(",");
List<String> mobData = new ArrayList<String>();
final List<String> mobData = new ArrayList<>();
for (String mobPart : mobParts) {
String[] mobDatas = mobPart.split(":");
for (final String mobPart : mobParts) {
final String[] mobDatas = mobPart.split(":");
if (mobDatas.length == 1) {
if (mobPart.contains(":")) {
mobData.add("");
@@ -67,7 +87,7 @@ public class SpawnMob {
}
// This method spawns a mob where the user is looking, owned by user
public static void spawnmob(final IEssentials ess, final Server server, final User user, final List<String> parts, final List<String> data, int mobCount) throws Exception {
public static void spawnmob(final IEssentials ess, final Server server, final User user, final List<String> parts, final List<String> data, final int mobCount) throws Exception {
final Block block = LocationUtil.getTarget(user.getBase()).getBlock();
if (block == null) {
throw new Exception(tl("unableToSpawnMob"));
@@ -76,7 +96,7 @@ public class SpawnMob {
}
// This method spawns a mob at target, owned by target
public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List<String> parts, final List<String> data, int mobCount) throws Exception {
public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List<String> parts, final List<String> data, final int mobCount) throws Exception {
spawnmob(ess, server, sender, target, target.getLocation(), parts, data, mobCount);
}
@@ -84,8 +104,8 @@ public class SpawnMob {
public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location loc, final List<String> parts, final List<String> data, int mobCount) throws Exception {
final Location sloc = LocationUtil.getSafeDestination(loc);
for (int i = 0; i < parts.size(); i++) {
Mob mob = Mob.fromName(parts.get(i));
for (final String part : parts) {
final Mob mob = Mob.fromName(part);
checkSpawnable(ess, sender, mob);
}
@@ -104,22 +124,22 @@ public class SpawnMob {
sender.sendMessage(tl("mobSpawnLimit"));
}
Mob mob = Mob.fromName(parts.get(0)); // Get the first mob
final Mob mob = Mob.fromName(parts.get(0)); // Get the first mob
try {
for (int i = 0; i < mobCount; i++) {
spawnMob(ess, server, sender, target, sloc, parts, data);
}
sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned"));
} catch (MobException e1) {
} catch (final MobException e1) {
throw new Exception(tl("unableToSpawnMob"), e1);
} catch (NumberFormatException e2) {
} catch (final NumberFormatException e2) {
throw new Exception(tl("numberRequired"), e2);
} catch (NullPointerException np) {
} catch (final NullPointerException np) {
throw new Exception(tl("soloMob"), np);
}
}
private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List<String> parts, List<String> data) throws Exception {
private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, final List<String> parts, final List<String> data) throws Exception {
Mob mob;
Entity spawnedMob = null;
Entity spawnedMount;
@@ -135,10 +155,10 @@ public class SpawnMob {
}
}
int next = (i + 1);
if (next < parts.size()) //If it's the last mob in the list, don't set the mount
{
Mob mMob = Mob.fromName(parts.get(next));
final int next = i + 1;
// If it's the last mob in the list, don't set the mount
if (next < parts.size()) {
final Mob mMob = Mob.fromName(parts.get(next));
spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc);
defaultMobData(mMob.getType(), spawnedMount);
@@ -153,7 +173,7 @@ public class SpawnMob {
}
}
private static void checkSpawnable(IEssentials ess, CommandSource sender, Mob mob) throws Exception {
private static void checkSpawnable(final IEssentials ess, final CommandSource sender, final Mob mob) throws Exception {
if (mob == null || mob.getType() == null) {
throw new Exception(tl("invalidMob"));
}
@@ -191,16 +211,16 @@ public class SpawnMob {
invent.setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.DIAMOND_HELMET, 1));
} else if (inputData.contains("gold")) {
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.GOLD_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.GOLD_HELMET, 1));
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
invent.setLeggings(new ItemStack(GOLDEN_LEGGINGS, 1));
invent.setChestplate(new ItemStack(GOLDEN_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(GOLDEN_HELMET, 1));
} else if (inputData.contains("leather")) {
invent.setBoots(new ItemStack(Material.LEATHER_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.LEATHER_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.LEATHER_HELMET, 1));
} else {
} else if (inputData.contains("iron")) {
invent.setBoots(new ItemStack(Material.IRON_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.IRON_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.IRON_CHESTPLATE, 1));
@@ -227,30 +247,20 @@ public class SpawnMob {
final EntityEquipment invent = ((LivingEntity) spawned).getEquipment();
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(Material.BOW, 1));
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}
if (type == EntityType.PIG_ZOMBIE) {
final PigZombie zombie = ((PigZombie) spawned);
if (type == MobCompat.ZOMBIFIED_PIGLIN) {
final PigZombie zombie = (PigZombie) spawned;
setVillager(zombie, false);
final EntityEquipment invent = zombie.getEquipment();
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(Material.GOLD_SWORD, 1));
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(GOLDEN_SWORD, 1));
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}
if (type == EntityType.ZOMBIE) {
final Zombie zombie = ((Zombie) spawned);
final Zombie zombie = (Zombie) spawned;
setVillager(zombie, false);
final EntityEquipment invent = zombie.getEquipment();
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}
if (type == EntityType.HORSE) {
@@ -259,10 +269,10 @@ public class SpawnMob {
}
@SuppressWarnings("deprecation")
private static void setVillager(Zombie zombie, boolean villager) {
private static void setVillager(final Zombie zombie, final boolean villager) {
try {
zombie.setVillager(villager);
} catch (Exception ignored) {
} catch (final Exception ignored) {
}
}
}
@@ -7,7 +7,6 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
public class TNTExplodeListener implements Listener, Runnable {
private final transient IEssentials ess;
private transient boolean enabled = false;
@@ -2,8 +2,14 @@ package com.earth2me.essentials;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.api.ITeleport;
import net.ess3.api.IUser;
import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
@@ -15,27 +21,26 @@ import java.util.GregorianCalendar;
import static com.earth2me.essentials.I18n.tl;
public class Teleport implements net.ess3.api.ITeleport {
/**
* @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.AsyncTeleport AsyncTeleport}
*/
@Deprecated
public class Teleport implements ITeleport {
private final IUser teleportOwner;
private final IEssentials ess;
private TimedTeleport timedTeleport;
private TeleportType tpType;
public Teleport(IUser user, IEssentials ess) {
@Deprecated
public Teleport(final IUser user, final IEssentials ess) {
this.teleportOwner = user;
this.ess = ess;
tpType = TeleportType.NORMAL;
}
public enum TeleportType {
TPA,
BACK,
NORMAL
}
public void cooldown(boolean check) throws Exception {
@Deprecated
public void cooldown(final boolean check) throws Exception {
final Calendar time = new GregorianCalendar();
if (teleportOwner.getLastTeleportTimestamp() > 0) {
// Take the current time, and remove the delay from it.
@@ -47,7 +52,7 @@ public class Teleport implements net.ess3.api.ITeleport {
final long earliestLong = earliestTime.getTimeInMillis();
// When was the last teleportPlayer used?
final Long lastTime = teleportOwner.getLastTeleportTimestamp();
final long lastTime = teleportOwner.getLastTeleportTimestamp();
if (lastTime > time.getTimeInMillis()) {
// This is to make sure time didn't get messed up on last teleportPlayer use.
@@ -55,7 +60,7 @@ public class Teleport implements net.ess3.api.ITeleport {
teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis());
return;
} else if (lastTime > earliestLong
&& cooldownApplies()) {
&& cooldownApplies()) {
time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int) cooldown);
time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
@@ -68,27 +73,29 @@ public class Teleport implements net.ess3.api.ITeleport {
}
}
@Deprecated
private boolean cooldownApplies() {
boolean applies = true;
String globalBypassPerm = "essentials.teleport.cooldown.bypass";
final String globalBypassPerm = "essentials.teleport.cooldown.bypass";
switch (tpType) {
case NORMAL:
applies = !teleportOwner.isAuthorized(globalBypassPerm);
break;
case BACK:
applies = !(teleportOwner.isAuthorized(globalBypassPerm) &&
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.back"));
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.back"));
break;
case TPA:
applies = !(teleportOwner.isAuthorized(globalBypassPerm) &&
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.tpa"));
teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.tpa"));
break;
}
return applies;
}
@Deprecated
private void warnUser(final IUser user, final double delay) {
Calendar c = new GregorianCalendar();
final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay);
c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));
user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis())));
@@ -96,7 +103,8 @@ public class Teleport implements net.ess3.api.ITeleport {
//The now function is used when you want to skip tp delay when teleporting someone to a location or player.
@Override
public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception {
@Deprecated
public void now(final Location loc, final boolean cooldown, final TeleportCause cause) throws Exception {
if (cooldown) {
cooldown(false);
}
@@ -105,7 +113,8 @@ public class Teleport implements net.ess3.api.ITeleport {
}
@Override
public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception {
@Deprecated
public void now(final Player entity, final boolean cooldown, final TeleportCause cause) throws Exception {
if (cooldown) {
cooldown(false);
}
@@ -114,29 +123,46 @@ public class Teleport implements net.ess3.api.ITeleport {
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
}
protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception {
@Deprecated
protected void now(final IUser teleportee, final ITarget target, final TeleportCause cause) throws Exception {
cancel(false);
teleportee.setLastLocation();
Location loc = target.getLocation();
final PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
if (teleportee.isAuthorized("essentials.back.onteleport")) {
teleportee.setLastLocation();
}
if (!teleportee.getBase().isEmpty()) {
if (!ess.getSettings().isTeleportPassengerDismount()) {
throw new Exception(tl("passengerTeleportFail"));
}
teleportee.getBase().eject();
}
if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) {
if (ess.getSettings().isTeleportSafetyEnabled()) {
if (ess.getSettings().isForceDisableTeleportSafety()) {
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
} else {
teleportee.getBase().teleport(LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
}
} else {
throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
} else {
if (ess.getSettings().isForceDisableTeleportSafety()) {
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
} else {
if (ess.getSettings().isTeleportToCenterLocation()) {
loc = LocationUtil.getRoundedDestination(loc);
}
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
}
}
}
@@ -145,41 +171,53 @@ public class Teleport implements net.ess3.api.ITeleport {
//This method is nolonger used internally and will be removed.
@Deprecated
@Override
public void teleport(Location loc, Trade chargeFor) throws Exception {
public void teleport(final Location loc, final Trade chargeFor) throws Exception {
teleport(loc, chargeFor, TeleportCause.PLUGIN);
}
@Override
public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception {
@Deprecated
public void teleport(final Location loc, final Trade chargeFor, final TeleportCause cause) throws Exception {
teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause);
}
//This is used when teleporting to a player
@Override
public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception {
ITarget target = new PlayerTarget(entity);
@Deprecated
public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception {
final ITarget target = new PlayerTarget(entity);
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName()));
teleport(teleportOwner, target, chargeFor, cause);
}
//This is used when teleporting to stored location
@Override
public void teleportPlayer(IUser teleportee, Location loc, Trade chargeFor, TeleportCause cause) throws Exception {
@Deprecated
public void teleportPlayer(final IUser teleportee, final Location loc, final Trade chargeFor, final TeleportCause cause) throws Exception {
teleport(teleportee, new LocationTarget(loc), chargeFor, cause);
}
//This is used on /tphere
@Override
public void teleportPlayer(IUser teleportee, Player entity, Trade chargeFor, TeleportCause cause) throws Exception {
ITarget target = new PlayerTarget(entity);
@Deprecated
public void teleportPlayer(final IUser teleportee, final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception {
final ITarget target = new PlayerTarget(entity);
teleport(teleportee, target, chargeFor, cause);
teleportee.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
}
private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception {
@Deprecated
private void teleport(final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause) throws Exception {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
Trade cashCharge = chargeFor;
if (chargeFor != null) {
@@ -207,10 +245,60 @@ public class Teleport implements net.ess3.api.ITeleport {
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
}
@Deprecated
private void teleportOther(final IUser teleporter, final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause) throws Exception {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleporter, teleportee, cause, target, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
Trade cashCharge = chargeFor;
if (teleporter != null && chargeFor != null) {
chargeFor.isAffordableFor(teleporter);
//This code is to make sure that commandcosts are checked in the initial world, and not in the resulting world.
if (!chargeFor.getCommandCost(teleporter).equals(BigDecimal.ZERO)) {
//By converting a command cost to a regular cost, the command cost permission isn't checked when executing the charge after teleport.
cashCharge = new Trade(chargeFor.getCommandCost(teleporter), ess);
}
}
cooldown(true);
if (delay <= 0 || teleporter == null
|| teleporter.isAuthorized("essentials.teleport.timer.bypass")
|| teleportOwner.isAuthorized("essentials.teleport.timer.bypass")
|| teleportee.isAuthorized("essentials.teleport.timer.bypass")) {
cooldown(false);
now(teleportee, target, cause);
if (teleporter != null && cashCharge != null) {
cashCharge.charge(teleporter);
}
return;
}
cancel(false);
warnUser(teleportee, delay);
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
}
//The respawn function is a wrapper used to handle tp fallback, on /jail and /home
@Override
public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception {
@Deprecated
public void respawn(final Trade chargeFor, final TeleportCause cause) throws Exception {
double delay = ess.getSettings().getTeleportDelay();
final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
delay = event.getDelay();
if (chargeFor != null) {
chargeFor.isAffordableFor(teleportOwner);
}
@@ -229,9 +317,10 @@ public class Teleport implements net.ess3.api.ITeleport {
initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true);
}
protected void respawnNow(IUser teleportee, TeleportCause cause) throws Exception {
@Deprecated
void respawnNow(final IUser teleportee, final TeleportCause cause) throws Exception {
final Player player = teleportee.getBase();
Location bed = player.getBedSpawnLocation();
final Location bed = player.getBedSpawnLocation();
if (bed != null) {
now(teleportee, new LocationTarget(bed), cause);
} else {
@@ -246,8 +335,16 @@ public class Teleport implements net.ess3.api.ITeleport {
//The warp function is a wrapper used to teleportPlayer a player to a /warp
@Override
public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception {
Location loc = ess.getWarps().getWarp(warp);
@Deprecated
public void warp(final IUser teleportee, String warp, final Trade chargeFor, final TeleportCause cause) throws Exception {
final UserWarpEvent event = new UserWarpEvent(teleportee, warp, chargeFor);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
warp = event.getWarp();
final Location loc = ess.getWarps().getWarp(warp);
teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
if (!teleportee.equals(teleportOwner)) {
teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
@@ -257,32 +354,50 @@ public class Teleport implements net.ess3.api.ITeleport {
//The back function is a wrapper used to teleportPlayer a player /back to their previous location.
@Override
public void back(Trade chargeFor) throws Exception {
@Deprecated
public void back(final Trade chargeFor) throws Exception {
back(teleportOwner, chargeFor);
}
//This function is a wrapper over the other back function for cases where another player performs back for them
@Override
@Deprecated
public void back(final IUser teleporter, final Trade chargeFor) throws Exception {
tpType = TeleportType.BACK;
final Location loc = teleportOwner.getLastLocation();
teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
teleport(teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND);
teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND);
}
//This function is used to throw a user back after a jail sentence
@Override
@Deprecated
public void back() throws Exception {
now(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND);
}
public void setTpType(TeleportType tpType) {
@Deprecated
public void setTpType(final TeleportType tpType) {
this.tpType = tpType;
}
//If we need to cancelTimer a pending teleportPlayer call this method
private void cancel(boolean notifyUser) {
@Deprecated
private void cancel(final boolean notifyUser) {
if (timedTeleport != null) {
timedTeleport.cancelTimer(notifyUser);
timedTeleport = null;
}
}
private void initTimer(long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) {
@Deprecated
private void initTimer(final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) {
timedTeleport = new TimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn);
}
public enum TeleportType {
TPA,
BACK,
NORMAL
}
}
@@ -9,17 +9,15 @@ import java.util.UUID;
import static com.earth2me.essentials.I18n.tl;
@Deprecated
public class TimedTeleport implements Runnable {
private static final double MOVE_CONSTANT = 0.3;
private final IUser teleportOwner;
private final IEssentials ess;
private final Teleport teleport;
private final UUID timer_teleportee;
private int timer_task = -1;
private final long timer_started; // time this task was initiated
private final long timer_delay; // how long to delay the teleportPlayer
private double timer_health;
private final long timer_started; // time this task was initiated
private final long timer_delay; // how long to delay the teleportPlayer
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
@@ -31,9 +29,10 @@ public class TimedTeleport implements Runnable {
private final boolean timer_canMove;
private final Trade timer_chargeFor;
private final TeleportCause timer_cause;
private int timer_task;
private double timer_health;
public TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) {
TimedTeleport(final IUser user, final IEssentials ess, final Teleport teleport, final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) {
this.teleportOwner = user;
this.ess = ess;
this.teleport = teleport;
@@ -84,12 +83,12 @@ public class TimedTeleport implements Runnable {
@Override
public void run() {
timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured
timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured
final long now = System.currentTimeMillis();
if (now > timer_started + timer_delay) {
try {
teleport.cooldown(false);
} catch (Exception ex) {
} catch (final Exception ex) {
teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
if (teleportOwner != teleportUser) {
teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
@@ -99,32 +98,30 @@ public class TimedTeleport implements Runnable {
cancelTimer(false);
teleportUser.sendMessage(tl("teleportationCommencing"));
try {
if (timer_chargeFor != null) {
timer_chargeFor.isAffordableFor(teleportOwner);
}
if (timer_respawn) {
teleport.respawnNow(teleportUser, timer_cause);
} else {
teleport.now(teleportUser, timer_teleportTarget, timer_cause);
}
if (timer_chargeFor != null) {
timer_chargeFor.charge(teleportOwner);
}
} catch (Exception ex) {
if (timer_chargeFor != null) {
timer_chargeFor.isAffordableFor(teleportOwner);
}
if (timer_respawn) {
teleport.respawnNow(teleportUser, timer_cause);
} else {
teleport.now(teleportUser, timer_teleportTarget, timer_cause);
}
if (timer_chargeFor != null) {
timer_chargeFor.charge(teleportOwner);
}
} catch (Exception ex) {
} catch (final Exception ex) {
ess.showError(teleportOwner.getSource(), ex, "\\ teleport");
}
}
}
}
ess.scheduleSyncDelayedTask(new DelayedTeleportTask());
}
//If we need to cancelTimer a pending teleportPlayer call this method
public void cancelTimer(boolean notifyUser) {
void cancelTimer(final boolean notifyUser) {
if (timer_task == -1) {
return;
}
+235 -203
View File
@@ -18,13 +18,15 @@ import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class Trade {
private static FileWriter fw = null;
private final transient String command;
private final transient Trade fallbackTrade;
private final transient BigDecimal money;
@@ -32,20 +34,6 @@ public class Trade {
private final transient Integer exp;
private final transient IEssentials ess;
public enum TradeType {
MONEY,
EXP,
ITEM
}
public enum OverflowType {
ABORT,
DROP,
RETURN
}
public Trade(final String command, final IEssentials ess) {
this(command, null, null, null, null, ess);
}
@@ -80,190 +68,7 @@ public class Trade {
this.ess = ess;
}
public void isAffordableFor(final IUser user) throws ChargeException {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge.");
}
if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)));
}
if (getItemStack() != null && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
throw new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack())));
}
BigDecimal money;
if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess)));
}
if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) {
throw new ChargeException(tl("notEnoughExperience"));
}
}
public boolean pay(final IUser user) throws MaxMoneyException {
return pay(user, OverflowType.ABORT) == null;
}
public Map<Integer, ItemStack> pay(final IUser user, final OverflowType type) throws MaxMoneyException {
if (getMoney() != null && getMoney().signum() > 0) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying user " + user.getName() + " via trade " + getMoney().toPlainString());
}
user.giveMoney(getMoney());
}
if (getItemStack() != null) {
// This stores the would be overflow
Map<Integer, ItemStack> overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack());
if (overFlow != null) {
switch (type) {
case ABORT:
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "abort paying " + user.getName() + " itemstack " + getItemStack().toString() + " due to lack of inventory space ");
}
return overFlow;
case RETURN:
// Pay the user the items, and return overflow
final Map<Integer, ItemStack> returnStack = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
user.getBase().updateInventory();
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " with overflow " + returnStack.get(0).toString());
}
return returnStack;
case DROP:
// Pay the users the items directly, and drop the rest, will always return no overflow.
final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
final Location loc = user.getBase().getLocation();
for (ItemStack loStack : leftOver.values()) {
final int maxStackSize = loStack.getType().getMaxStackSize();
final int stacks = loStack.getAmount() / maxStackSize;
final int leftover = loStack.getAmount() % maxStackSize;
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++) {
final ItemStack stack = loStack.clone();
stack.setAmount(maxStackSize);
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
}
if (leftover > 0) {
final ItemStack stack = loStack.clone();
stack.setAmount(leftover);
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
}
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString());
}
}
} else if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString());
}
user.getBase().updateInventory();
}
if (getExperience() != null) {
SetExpFix.setTotalExperience(user.getBase(), SetExpFix.getTotalExperience(user.getBase()) + getExperience());
}
return null;
}
public void charge(final IUser user) throws ChargeException {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName());
}
if (getMoney() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString());
}
if (!user.canAfford(getMoney()) && getMoney().signum() > 0) {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)));
}
user.takeMoney(getMoney());
}
if (getItemStack() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString());
}
if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount())) {
throw new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
user.getBase().getInventory().removeItem(getItemStack());
user.getBase().updateInventory();
}
if (command != null) {
final BigDecimal cost = getCommandCost(user);
if (!user.canAfford(cost) && cost.signum() > 0) {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess)));
}
user.takeMoney(cost);
}
if (getExperience() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " exp " + getExperience());
}
final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0) {
throw new ChargeException(tl("notEnoughExperience"));
}
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charge user " + user.getName() + " completed");
}
}
public BigDecimal getMoney() {
return money;
}
public ItemStack getItemStack() {
return itemStack;
}
public Integer getExperience() {
return exp;
}
public TradeType getType() {
if (getExperience() != null) {
return TradeType.EXP;
}
if (getItemStack() != null) {
return TradeType.ITEM;
}
return TradeType.MONEY;
}
public BigDecimal getCommandCost(final IUser user) {
BigDecimal cost = BigDecimal.ZERO;
if (command != null && !command.isEmpty()) {
cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command);
if (cost.signum() == 0 && fallbackTrade != null) {
cost = fallbackTrade.getCommandCost(user);
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "calculated command (" + command + ") cost for " + user.getName() + " as " + cost);
}
}
if (cost.signum() != 0 && (user.isAuthorized("essentials.nocommandcost.all") || user.isAuthorized("essentials.nocommandcost." + command))) {
return BigDecimal.ZERO;
}
return cost;
}
private static FileWriter fw = null;
public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) {
public static void log(final String type, final String subtype, final String event, final String sender, final Trade charge, final String receiver, final Trade pay, final Location loc, final IEssentials ess) {
//isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg
//isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs.
@@ -273,11 +78,11 @@ public class Trade {
if (fw == null) {
try {
fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true);
} catch (IOException ex) {
} catch (final IOException ex) {
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
}
}
StringBuilder sb = new StringBuilder();
final StringBuilder sb = new StringBuilder();
sb.append(type).append(",").append(subtype).append(",").append(event).append(",\"");
sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date()));
sb.append("\",\"");
@@ -341,7 +146,7 @@ public class Trade {
try {
fw.write(sb.toString());
fw.flush();
} catch (IOException ex) {
} catch (final IOException ex) {
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
}
}
@@ -350,10 +155,237 @@ public class Trade {
if (fw != null) {
try {
fw.close();
} catch (IOException ex) {
} catch (final IOException ex) {
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
}
fw = null;
}
}
public void isAffordableFor(final IUser user) throws ChargeException {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
isAffordableFor(user, future);
if (future.isCompletedExceptionally()) {
try {
future.get();
} catch (final InterruptedException e) { //If this happens, we have bigger problems...
e.printStackTrace();
} catch (final ExecutionException e) {
throw (ChargeException) e.getCause();
}
}
}
public void isAffordableFor(final IUser user, final CompletableFuture<Boolean> future) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge.");
}
if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return;
}
if (getItemStack() != null && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack()))));
return;
}
final BigDecimal money;
if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess))));
return;
}
if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) {
future.completeExceptionally(new ChargeException(tl("notEnoughExperience")));
}
}
public boolean pay(final IUser user) throws MaxMoneyException {
return pay(user, OverflowType.ABORT) == null;
}
public Map<Integer, ItemStack> pay(final IUser user, final OverflowType type) throws MaxMoneyException {
if (getMoney() != null && getMoney().signum() > 0) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying user " + user.getName() + " via trade " + getMoney().toPlainString());
}
user.giveMoney(getMoney());
}
if (getItemStack() != null) {
// This stores the would be overflow
final Map<Integer, ItemStack> overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack());
if (overFlow != null) {
switch (type) {
case ABORT:
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "abort paying " + user.getName() + " itemstack " + getItemStack().toString() + " due to lack of inventory space ");
}
return overFlow;
case RETURN:
// Pay the user the items, and return overflow
final Map<Integer, ItemStack> returnStack = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
user.getBase().updateInventory();
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " with overflow " + returnStack.get(0).toString());
}
return returnStack;
case DROP:
// Pay the users the items directly, and drop the rest, will always return no overflow.
final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack());
final Location loc = user.getBase().getLocation();
for (final ItemStack loStack : leftOver.values()) {
final int maxStackSize = loStack.getType().getMaxStackSize();
final int stacks = loStack.getAmount() / maxStackSize;
final int leftover = loStack.getAmount() % maxStackSize;
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++) {
final ItemStack stack = loStack.clone();
stack.setAmount(maxStackSize);
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
}
if (leftover > 0) {
final ItemStack stack = loStack.clone();
stack.setAmount(leftover);
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
}
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString());
}
break;
}
} else if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString());
}
user.getBase().updateInventory();
}
if (getExperience() != null) {
SetExpFix.setTotalExperience(user.getBase(), SetExpFix.getTotalExperience(user.getBase()) + getExperience());
}
return null;
}
public void charge(final IUser user) throws ChargeException {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
charge(user, future);
if (future.isCompletedExceptionally()) {
try {
future.get();
} catch (final InterruptedException e) { //If this happens, we have bigger problems...
e.printStackTrace();
} catch (final ExecutionException e) {
throw (ChargeException) e.getCause();
}
}
}
public void charge(final IUser user, final CompletableFuture<Boolean> future) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName());
}
if (getMoney() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString());
}
if (!user.canAfford(getMoney()) && getMoney().signum() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return;
}
user.takeMoney(getMoney());
}
if (getItemStack() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString());
}
if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount())) {
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))));
return;
}
user.getBase().getInventory().removeItem(getItemStack());
user.getBase().updateInventory();
}
if (command != null) {
final BigDecimal cost = getCommandCost(user);
if (!user.canAfford(cost) && cost.signum() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess))));
return;
}
user.takeMoney(cost);
}
if (getExperience() != null) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " exp " + getExperience());
}
final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughExperience")));
return;
}
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "charge user " + user.getName() + " completed");
}
}
public BigDecimal getMoney() {
return money;
}
public ItemStack getItemStack() {
return itemStack;
}
public Integer getExperience() {
return exp;
}
public TradeType getType() {
if (getExperience() != null) {
return TradeType.EXP;
}
if (getItemStack() != null) {
return TradeType.ITEM;
}
return TradeType.MONEY;
}
public BigDecimal getCommandCost(final IUser user) {
BigDecimal cost = BigDecimal.ZERO;
if (command != null && !command.isEmpty()) {
cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command);
if (cost.signum() == 0 && fallbackTrade != null) {
cost = fallbackTrade.getCommandCost(user);
}
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "calculated command (" + command + ") cost for " + user.getName() + " as " + cost);
}
}
if (cost.signum() != 0 && (user.isAuthorized("essentials.nocommandcost.all") || user.isAuthorized("essentials.nocommandcost." + command))) {
return BigDecimal.ZERO;
}
return cost;
}
public enum TradeType {
MONEY,
EXP,
ITEM
}
public enum OverflowType {
ABORT,
DROP,
RETURN
}
}
@@ -3,40 +3,42 @@ package com.earth2me.essentials;
import com.google.common.io.Files;
import org.bukkit.Bukkit;
import java.io.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class UUIDMap {
private final transient net.ess3.api.IEssentials ess;
private File userList;
private final transient Pattern splitPattern = Pattern.compile(",");
private static boolean pendingWrite;
private static final ScheduledExecutorService writeScheduler = Executors.newScheduledThreadPool(1);
private final Runnable writeTaskRunnable;
private static boolean pendingWrite;
private static boolean loading = false;
private final transient net.ess3.api.IEssentials ess;
private final File userList;
private final transient Pattern splitPattern = Pattern.compile(",");
private final Runnable writeTaskRunnable;
public UUIDMap(final net.ess3.api.IEssentials ess) {
this.ess = ess;
userList = new File(ess.getDataFolder(), "usermap.csv");
pendingWrite = false;
writeTaskRunnable = new Runnable() {
@Override
public void run() {
if (pendingWrite) {
try {
new WriteRunner(ess.getDataFolder(), userList, ess.getUserMap().getNames()).run();
} catch (Throwable t) { // bad code to prevent task from being suppressed
t.printStackTrace();
}
writeTaskRunnable = () -> {
if (pendingWrite) {
try {
new WriteRunner(ess.getDataFolder(), userList, ess.getUserMap().getNames()).run();
} catch (final Throwable t) { // bad code to prevent task from being suppressed
t.printStackTrace();
}
}
};
@@ -61,7 +63,7 @@ public class UUIDMap {
history.clear();
loading = true;
try (BufferedReader reader = new BufferedReader(new FileReader(userList))) {
try (final BufferedReader reader = new BufferedReader(new FileReader(userList))) {
while (true) {
final String line = reader.readLine();
if (line == null) {
@@ -87,7 +89,7 @@ public class UUIDMap {
}
}
loading = false;
} catch (IOException ex) {
} catch (final IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -109,7 +111,7 @@ public class UUIDMap {
writeScheduler.shutdown();
}
private static class WriteRunner implements Runnable {
private static final class WriteRunner implements Runnable {
private final File location;
private final File endFile;
private final Map<String, UUID> names;
@@ -132,19 +134,19 @@ public class UUIDMap {
configFile = File.createTempFile("usermap", ".tmp.csv", location);
final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile));
for (Map.Entry<String, UUID> entry : names.entrySet()) {
for (final Map.Entry<String, UUID> entry : names.entrySet()) {
bWriter.write(entry.getKey() + "," + entry.getValue().toString());
bWriter.newLine();
}
bWriter.close();
Files.move(configFile, endFile);
} catch (IOException ex) {
} catch (final IOException ex) {
try {
if (configFile != null && configFile.exists()) {
Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv"));
}
} catch (Exception ex2) {
} catch (final Exception ex2) {
Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2);
}
Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex);
+247 -117
View File
@@ -8,16 +8,16 @@ import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.JailStatusChangeEvent;
import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
@@ -29,23 +29,26 @@ import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class User extends UserData implements Comparable<User>, IMessageRecipient, net.ess3.api.IUser {
private static final Logger logger = Logger.getLogger("Essentials");
private IMessageRecipient messageRecipient;
private final IMessageRecipient messageRecipient;
private transient final AsyncTeleport teleport;
private transient final Teleport legacyTeleport;
private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private transient UUID teleportRequester;
private transient boolean teleportRequestHere;
private transient Location teleportLocation;
private transient boolean vanished;
private transient final Teleport teleport;
private transient long teleportRequestTime;
private transient long lastOnlineActivity;
private transient long lastThrottledAction;
@@ -60,13 +63,15 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
private boolean ignoreMsg = false;
private String afkMessage;
private long afkSince;
private Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private String confirmingClearCommand;
private long lastNotifiedAboutMailsMs;
private String lastHomeConfirmation;
private long lastHomeConfirmationTimestamp;
public User(final Player base, final IEssentials ess) {
super(base, ess);
teleport = new Teleport(this, ess);
teleport = new AsyncTeleport(this, ess);
legacyTeleport = new Teleport(this, ess);
if (isAfk()) {
afkPosition = this.getLocation();
}
@@ -100,6 +105,11 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return result;
}
@Override
public boolean isPermissionSet(final String node) {
return isPermSetCheck(node);
}
private boolean isAuthorizedCheck(final String node) {
if (base instanceof OfflinePlayer) {
@@ -108,7 +118,25 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
try {
return ess.getPermissionsHandler().hasPermission(base, node);
} catch (Exception ex) {
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
}
return false;
}
}
private boolean isPermSetCheck(final String node) {
if (base instanceof OfflinePlayer) {
return false;
}
try {
return ess.getPermissionsHandler().isPermissionSet(base, node);
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
@@ -142,10 +170,14 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException {
giveMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void giveMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException {
if (value.signum() == 0) {
return;
}
setMoney(getMoney().add(value));
setMoney(getMoney().add(value), cause);
sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess)));
if (initiator != null) {
initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
@@ -154,13 +186,17 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public void payUser(final User reciever, final BigDecimal value) throws Exception {
payUser(reciever, value, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void payUser(final User reciever, final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws Exception {
if (value.compareTo(BigDecimal.ZERO) < 1) {
throw new Exception(tl("payMustBePositive"));
}
if (canAfford(value)) {
setMoney(getMoney().subtract(value));
reciever.setMoney(reciever.getMoney().add(value));
setMoney(getMoney().subtract(value), cause);
reciever.setMoney(reciever.getMoney().add(value), cause);
sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName()));
reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName()));
} else {
@@ -175,12 +211,16 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public void takeMoney(final BigDecimal value, final CommandSource initiator) {
takeMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void takeMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) {
if (value.signum() == 0) {
return;
}
try {
setMoney(getMoney().subtract(value));
} catch (MaxMoneyException ex) {
setMoney(getMoney().subtract(value), cause);
} catch (final MaxMoneyException ex) {
ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex);
}
sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess)));
@@ -200,18 +240,13 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final BigDecimal remainingBalance = getMoney().subtract(cost);
if (!permcheck || isAuthorized("essentials.eco.loan")) {
return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0);
return remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0;
}
return (remainingBalance.signum() >= 0);
return remainingBalance.signum() >= 0;
}
public void dispose() {
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
_dispose();
}
});
ess.runTaskAsynchronously(this::_dispose);
}
private void _dispose() {
@@ -222,8 +257,20 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
@Override
public Boolean canSpawnItem(final int itemId) {
return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
public Boolean canSpawnItem(final Material material) {
if (ess.getSettings().permissionBasedItemSpawn()) {
final String name = material.toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (isAuthorized("essentials.itemspawn.item-all") || isAuthorized("essentials.itemspawn.item-" + name))
return true;
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
final int id = material.getId();
if (isAuthorized("essentials.itemspawn.item-" + id)) return true;
}
}
return isAuthorized("essentials.itemspawn.exempt") || !ess.getSettings().itemSpawnBlacklist().contains(material);
}
@Override
@@ -251,7 +298,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public boolean hasOutstandingTeleportRequest() {
if (getTeleportRequest() != null) { // Player has outstanding teleport request.
long timeout = ess.getSettings().getTpaAcceptCancellation();
final long timeout = ess.getSettings().getTpaAcceptCancellation();
if (timeout != 0) {
if ((System.currentTimeMillis() - getTeleportRequestTime()) / 1000 <= timeout) { // Player has outstanding request
return true;
@@ -278,13 +325,27 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return teleportLocation;
}
public String getNick(final boolean longnick) {
return getNick(longnick, true, true);
public String getNick() {
return getNick(true, true);
}
/**
* Needed for backwards compatibility.
*/
public String getNick(final boolean longnick) {
return getNick(true, true);
}
/**
* Needed for backwards compatibility.
*/
public String getNick(final boolean longnick, final boolean withPrefix, final boolean withSuffix) {
return getNick(withPrefix, withSuffix);
}
public String getNick(final boolean withPrefix, final boolean withSuffix) {
final StringBuilder prefix = new StringBuilder();
String nickname;
final String nickname;
String suffix = "";
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) {
@@ -298,39 +359,38 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (this.getBase().isOp()) {
try {
final ChatColor opPrefix = ess.getSettings().getOperatorColor();
if (opPrefix != null && opPrefix.toString().length() > 0) {
prefix.insert(0, opPrefix.toString());
final String opPrefix = ess.getSettings().getOperatorColor();
if (opPrefix != null && !opPrefix.isEmpty()) {
prefix.insert(0, opPrefix);
suffix = "§r";
}
} catch (Exception e) {
} catch (final Exception e) {
if (ess.getSettings().isDebug()) {
e.printStackTrace();
}
}
}
if (ess.getSettings().addPrefixSuffix()) {
//These two extra toggles are not documented, because they are mostly redundant #EasterEgg
if (withPrefix || !ess.getSettings().disablePrefix()) {
final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§');
final String ptext = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(base));
prefix.insert(0, ptext);
suffix = "§r";
}
if (withSuffix || !ess.getSettings().disableSuffix()) {
final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§');
final String stext = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(base));
suffix = stext + "§r";
suffix = suffix.replace("§f§f", "§f").replace("§f§r", "§r").replace("§r§r", "§r");
// :YEP: WHAT ARE THEY DOING?
// :YEP: STILL. LEGACY CODE.
// :YEP: BUT WHY?
// :YEP: I CAN'T BELIEVE THIS!
// Code from 1542 BC #EasterEgg
suffix = suffix.replace("§f§r", "§r").replace("§r§r", "§r");
}
}
final String strPrefix = prefix.toString();
String output = strPrefix + nickname + suffix;
if (!longnick && output.length() > 16) {
output = strPrefix + nickname;
}
if (!longnick && output.length() > 16) {
output = FormatUtil.lastCode(strPrefix) + nickname;
}
if (!longnick && output.length() > 16) {
output = FormatUtil.lastCode(strPrefix) + nickname.substring(0, 14);
}
if (output.charAt(output.length() - 1) == '§') {
output = output.substring(0, output.length() - 1);
}
@@ -343,13 +403,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (isAfk()) {
updateAfkListName();
} else if (ess.getSettings().changePlayerListName()) {
// 1.8 enabled player list-names longer than 16 characters.
// If the server is on 1.8 or higher, provide that functionality. Otherwise, keep prior functionality.
boolean higherOrEqualTo1_8 = ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_8_R1);
String name = getNick(higherOrEqualTo1_8, ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
final String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
try {
this.getBase().setPlayerListName(name);
} catch (IllegalArgumentException e) {
} catch (final IllegalArgumentException e) {
if (ess.getSettings().isDebug()) {
logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player.");
}
@@ -358,15 +415,25 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
}
@Override
public String getDisplayName() {
return super.getBase().getDisplayName() == null ? super.getBase().getName() : super.getBase().getDisplayName();
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
}
@Override
public Teleport getTeleport() {
public AsyncTeleport getAsyncTeleport() {
return teleport;
}
/**
* @deprecated This API is not asynchronous. Use {@link User#getAsyncTeleport()}
*/
@Override
@Deprecated
public Teleport getTeleport() {
return legacyTeleport;
}
public long getLastOnlineActivity() {
return lastOnlineActivity;
}
@@ -386,6 +453,11 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return value;
}
@Override
public void setMoney(final BigDecimal value) throws MaxMoneyException {
setMoney(value, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
private BigDecimal _getMoney() {
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
@@ -401,14 +473,13 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
return BigDecimal.valueOf(account.balance());
} catch (Exception ex) {
} catch (final Exception ignored) {
}
}
return super.getMoney();
}
@Override
public void setMoney(final BigDecimal value) throws MaxMoneyException {
public void setMoney(final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException {
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Internal economy functions disabled, aborting balance change.");
@@ -416,11 +487,11 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return;
}
final BigDecimal oldBalance = _getMoney();
UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value);
final UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value, cause);
ess.getServer().getPluginManager().callEvent(updateEvent);
BigDecimal newBalance = updateEvent.getNewBalance();
final BigDecimal newBalance = updateEvent.getNewBalance();
if (Methods.hasMethod()) {
try {
final Method method = Methods.getMethod();
@@ -429,7 +500,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
account.set(newBalance.doubleValue());
} catch (Exception ex) {
} catch (final Exception ignored) {
}
}
super.setMoney(newBalance, true);
@@ -440,10 +511,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (ess.getSettings().isEcoDisabled()) {
return;
}
if (Methods.hasMethod() && super.getMoney() != value) {
if (Methods.hasMethod() && !super.getMoney().equals(value)) {
try {
super.setMoney(value, false);
} catch (MaxMoneyException ex) {
} catch (final MaxMoneyException ex) {
// We don't want to throw any errors here, just updating a cache
}
}
@@ -451,13 +522,18 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public void setAfk(final boolean set) {
final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set);
setAfk(set, AfkStatusChangeEvent.Cause.UNKNOWN);
}
@Override
public void setAfk(final boolean set, final AfkStatusChangeEvent.Cause cause) {
final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set, cause);
ess.getServer().getPluginManager().callEvent(afkEvent);
if (afkEvent.isCancelled()) {
return;
}
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set);
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") || set && ess.getSettings().sleepIgnoresAfkPlayers());
if (set && !isAfk()) {
afkPosition = this.getLocation();
this.afkSince = System.currentTimeMillis();
@@ -469,40 +545,51 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
_setAfk(set);
updateAfkListName();
}
private void updateAfkListName() {
if (ess.getSettings().isAfkListName()) {
if(isAfk()) {
String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName());
if (isAfk()) {
final String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName());
getBase().setPlayerListName(afkName);
} else {
getBase().setPlayerListName(null);
setDisplayNick();
}
}
}
@Deprecated
public boolean toggleAfk() {
setAfk(!isAfk());
return toggleAfk(AfkStatusChangeEvent.Cause.UNKNOWN);
}
public boolean toggleAfk(final AfkStatusChangeEvent.Cause cause) {
setAfk(!isAfk(), cause);
return isAfk();
}
@Override
public boolean isHiddenFrom(Player player) {
return !player.canSee(getBase());
}
@Override
public boolean isHidden() {
return hidden;
}
public boolean isHidden(final Player player) {
return hidden || !player.canSee(getBase());
}
@Override
public void setHidden(final boolean hidden) {
this.hidden = hidden;
if (hidden == true) {
if (hidden) {
setLastLogout(getLastOnlineActivity());
}
}
public boolean isHidden(final Player player) {
return hidden || !player.canSee(getBase());
}
//Returns true if status expired during this check
public boolean checkJailTimeout(final long currentTime) {
if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) {
@@ -514,13 +601,13 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setJailed(false);
sendMessage(tl("haveBeenReleased"));
setJail(null);
try {
getTeleport().back();
} catch (Exception ex) {
try {
getTeleport().respawn(null, TeleportCause.PLUGIN);
} catch (Exception ex1) {
}
if (ess.getSettings().isTeleportBackWhenFreedFromJail()) {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
getAsyncTeleport().back(future);
future.exceptionally(e -> {
getAsyncTeleport().respawn(null, TeleportCause.PLUGIN, new CompletableFuture<>());
return false;
});
}
return true;
}
@@ -531,27 +618,38 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
//Returns true if status expired during this check
public boolean checkMuteTimeout(final long currentTime) {
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) {
final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false);
final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason());
ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
setMuteTimeout(0);
sendMessage(tl("canTalkAgain"));
setMuted(false);
setMuteReason(null);
return true;
}
}
return false;
}
@Deprecated
public void updateActivity(final boolean broadcast) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.UNKNOWN);
}
public void updateActivity(final boolean broadcast, final AfkStatusChangeEvent.Cause cause) {
if (isAfk()) {
setAfk(false);
setAfk(false, cause);
if (broadcast && !isHidden()) {
setDisplayNick();
final String msg = tl("userIsNotAway", getDisplayName());
if (!msg.isEmpty()) {
ess.broadcastMessage(this, msg);
final String selfmsg = tl("userIsNotAwaySelf", getDisplayName());
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(this, msg, u -> u == this);
}
if (!selfmsg.isEmpty()) {
this.sendMessage(selfmsg);
}
}
}
@@ -559,14 +657,14 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
public void updateActivityOnMove(final boolean broadcast) {
if(ess.getSettings().cancelAfkOnMove()) {
updateActivity(broadcast);
if (ess.getSettings().cancelAfkOnMove()) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.MOVE);
}
}
public void updateActivityOnInteract(final boolean broadcast) {
if(ess.getSettings().cancelAfkOnInteract()) {
updateActivity(broadcast);
if (ess.getSettings().cancelAfkOnInteract()) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.INTERACT);
}
}
@@ -585,8 +683,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
lastActivity = 0;
this.getBase().kickPlayer(kickReason);
for (User user : ess.getOnlineUsers()) {
for (final User user : ess.getOnlineUsers()) {
if (user.isAuthorized("essentials.kick.notify")) {
user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason));
}
@@ -594,12 +691,17 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final long autoafk = ess.getSettings().getAutoAfk();
if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk.auto")) {
setAfk(true);
setAfk(true, AfkStatusChangeEvent.Cause.ACTIVITY);
if (!isHidden()) {
setDisplayNick();
final String msg = tl("userIsAway", getDisplayName());
if (!msg.isEmpty()) {
ess.broadcastMessage(this, msg);
final String selfmsg = tl("userIsAwaySelf", getDisplayName());
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(this, msg, u -> u == this);
}
if (!selfmsg.isEmpty()) {
this.sendMessage(selfmsg);
}
}
}
@@ -621,9 +723,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
if (isAfk()) {
// Protect AFK players by representing them in a god mode state to render them invulnerable to damage.
if (ess.getSettings().getFreezeAfkPlayers()) {
return true;
}
return ess.getSettings().getFreezeAfkPlayers();
}
return false;
}
@@ -708,7 +808,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
@Override
public void setIgnoreMsg(boolean ignoreMsg) {
public void setIgnoreMsg(final boolean ignoreMsg) {
this.ignoreMsg = ignoreMsg;
}
@@ -721,7 +821,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public void setVanished(final boolean set) {
vanished = set;
if (set) {
for (User user : ess.getOnlineUsers()) {
for (final User user : ess.getOnlineUsers()) {
if (!user.isAuthorized("essentials.vanish.see")) {
user.getBase().hidePlayer(getBase());
}
@@ -732,7 +832,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false));
}
} else {
for (Player p : ess.getOnlinePlayers()) {
for (final Player p : ess.getOnlinePlayers()) {
p.showPlayer(getBase());
}
setHidden(false);
@@ -753,7 +853,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public boolean isSignThrottled() {
final long minTime = lastThrottledAction + (1000 / ess.getSettings().getSignUsePerSecond());
return (System.currentTimeMillis() < minTime);
return System.currentTimeMillis() < minTime;
}
public void updateThrottle() {
@@ -764,7 +864,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return rightClickJump;
}
public void setRightClickJump(boolean rightClickJump) {
public void setRightClickJump(final boolean rightClickJump) {
this.rightClickJump = rightClickJump;
}
@@ -777,12 +877,12 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return recipeSee;
}
public void setRecipeSee(boolean recipeSee) {
public void setRecipeSee(final boolean recipeSee) {
this.recipeSee = recipeSee;
}
@Override
public void sendMessage(String message) {
public void sendMessage(final String message) {
if (!message.isEmpty()) {
base.sendMessage(message);
}
@@ -816,24 +916,29 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public String getName() {
return this.getBase().getName();
}
@Override public boolean isReachable() {
@Override
public boolean isReachable() {
return getBase().isOnline();
}
@Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) {
@Override
public MessageResponse sendMessage(final IMessageRecipient recipient, final String message) {
return this.messageRecipient.sendMessage(recipient, message);
}
@Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) {
@Override
public MessageResponse onReceiveMessage(final IMessageRecipient sender, final String message) {
return this.messageRecipient.onReceiveMessage(sender, message);
}
@Override public IMessageRecipient getReplyRecipient() {
@Override
public IMessageRecipient getReplyRecipient() {
return this.messageRecipient.getReplyRecipient();
}
@Override public void setReplyRecipient(IMessageRecipient recipient) {
@Override
public void setReplyRecipient(final IMessageRecipient recipient) {
this.messageRecipient.setReplyRecipient(recipient);
}
@@ -843,7 +948,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
@Override
public void setAfkMessage(String message) {
public void setAfkMessage(final String message) {
if (isAfk()) {
this.afkMessage = message;
}
@@ -862,8 +967,8 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public String getConfirmingClearCommand() {
return confirmingClearCommand;
}
public void setConfirmingClearCommand(String command) {
public void setConfirmingClearCommand(final String command) {
this.confirmingClearCommand = command;
}
@@ -871,22 +976,47 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
* Returns the {@link ItemStack} in the main hand or off-hand. If the main hand is empty then the offhand item is returned - also nullable.
*/
public ItemStack getItemInHand() {
if (ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_9_R1)) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_9_R01)) {
return getBase().getInventory().getItemInHand();
} else {
PlayerInventory inventory = getBase().getInventory();
final PlayerInventory inventory = getBase().getInventory();
return inventory.getItemInMainHand() != null ? inventory.getItemInMainHand() : inventory.getItemInOffHand();
}
}
public void notifyOfMail() {
List<String> mails = getMails();
final List<String> mails = getMails();
if (mails != null && !mails.isEmpty()) {
int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000;
final int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000;
if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) {
sendMessage(tl("youHaveNewMail", mails.size()));
lastNotifiedAboutMailsMs = System.currentTimeMillis();
}
}
}
public String getLastHomeConfirmation() {
return lastHomeConfirmation;
}
public void setLastHomeConfirmation(final String lastHomeConfirmation) {
this.lastHomeConfirmation = lastHomeConfirmation;
}
public long getLastHomeConfirmationTimestamp() {
return lastHomeConfirmationTimestamp;
}
public void setLastHomeConfirmationTimestamp() {
this.lastHomeConfirmationTimestamp = System.currentTimeMillis();
}
@Override
public Block getTargetBlock(int maxDistance) {
final Block block;
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_2_R01) || (block = base.getTargetBlockExact(maxDistance)) == null) {
return base.getTargetBlock(null, maxDistance);
}
return block;
}
}
@@ -7,28 +7,74 @@ import net.ess3.api.IEssentials;
import net.ess3.api.InvalidWorldException;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public abstract class UserData extends PlayerExtension implements IConf {
protected final transient IEssentials ess;
private final EssentialsUserConf config;
private final File folder;
private BigDecimal money;
private Map<String, Object> homes;
private String nickname;
private Set<Material> unlimited;
private Map<String, Object> powertools;
private Location lastLocation;
private Location logoutLocation;
private long lastTeleportTimestamp;
private long lastHealTimestamp;
private String jail;
private List<String> mails;
private boolean teleportEnabled;
private boolean autoTeleportEnabled;
private List<UUID> ignoredPlayers;
private boolean godmode;
private boolean muted;
private String muteReason;
private long muteTimeout;
private boolean jailed;
private long jailTimeout;
private long lastLogin;
private long lastLogout;
private String lastLoginAddress;
private boolean afk;
private boolean newplayer;
private String geolocation;
private boolean isSocialSpyEnabled;
private boolean isNPC;
private String lastAccountName = null;
private boolean arePowerToolsEnabled;
private Map<String, Long> kitTimestamps;
// Pattern, Date. Pattern for less pattern creations
private Map<Pattern, Long> commandCooldowns;
private boolean acceptingPay = true; // players accept pay by default
private Boolean confirmPay;
private Boolean confirmClear;
private boolean lastMessageReplyRecipient;
protected UserData(Player base, IEssentials ess) {
protected UserData(final Player base, final IEssentials ess) {
super(base);
this.ess = ess;
folder = new File(ess.getDataFolder(), "userdata");
final File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists()) {
folder.mkdirs();
}
@@ -36,7 +82,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
String filename;
try {
filename = base.getUniqueId().toString();
} catch (Throwable ex) {
} catch (final Throwable ex) {
ess.getLogger().warning("Falling back to old username system for " + base.getName());
filename = base.getName();
}
@@ -73,6 +119,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
godmode = _getGodModeEnabled();
muted = _getMuted();
muteTimeout = _getMuteTimeout();
muteReason = _getMuteReason();
jailed = _getJailed();
jailTimeout = _getJailTimeout();
lastLogin = _getLastLogin();
@@ -92,14 +139,13 @@ public abstract class UserData extends PlayerExtension implements IConf {
acceptingPay = _getAcceptingPay();
confirmPay = _getConfirmPay();
confirmClear = _getConfirmClear();
lastMessageReplyRecipient = _getLastMessageReplyRecipient();
}
private BigDecimal money;
private BigDecimal _getMoney() {
BigDecimal result = ess.getSettings().getStartingBalance();
BigDecimal maxMoney = ess.getSettings().getMaxMoney();
BigDecimal minMoney = ess.getSettings().getMinMoney();
final BigDecimal maxMoney = ess.getSettings().getMaxMoney();
final BigDecimal minMoney = ess.getSettings().getMinMoney();
// NPC banks are not actual player banks, as such they do not have player starting balance.
if (isNPC()) {
@@ -122,9 +168,9 @@ public abstract class UserData extends PlayerExtension implements IConf {
return money;
}
public void setMoney(BigDecimal value, boolean throwError) throws MaxMoneyException {
BigDecimal maxMoney = ess.getSettings().getMaxMoney();
BigDecimal minMoney = ess.getSettings().getMinMoney();
public void setMoney(final BigDecimal value, final boolean throwError) throws MaxMoneyException {
final BigDecimal maxMoney = ess.getSettings().getMaxMoney();
final BigDecimal minMoney = ess.getSettings().getMinMoney();
if (value.compareTo(maxMoney) > 0) {
if (throwError) {
throw new MaxMoneyException();
@@ -140,28 +186,25 @@ public abstract class UserData extends PlayerExtension implements IConf {
stopTransaction();
}
private Map<String, Object> homes;
private Map<String, Object> _getHomes() {
if (config.isConfigurationSection("homes")) {
return config.getConfigurationSection("homes").getValues(false);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
private String getHomeName(String search) {
if (NumberUtil.isInt(search)) {
try {
search = getHomes().get(Integer.parseInt(search) - 1);
} catch (NumberFormatException e) {
} catch (IndexOutOfBoundsException e) {
} catch (final NumberFormatException | IndexOutOfBoundsException ignored) {
}
}
return search;
}
public Location getHome(String name) throws Exception {
String search = getHomeName(name);
public Location getHome(final String name) throws Exception {
final String search = getHomeName(name);
return config.getLocation("homes." + search, this.getBase().getServer());
}
@@ -171,7 +214,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return null;
}
Location loc;
for (String home : getHomes()) {
for (final String home : getHomes()) {
loc = config.getLocation("homes." + home, this.getBase().getServer());
if (world.getWorld() == loc.getWorld()) {
return loc;
@@ -180,16 +223,16 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
loc = config.getLocation("homes." + getHomes().get(0), this.getBase().getServer());
return loc;
} catch (InvalidWorldException ex) {
} catch (final InvalidWorldException ex) {
return null;
}
}
public List<String> getHomes() {
return new ArrayList<String>(homes.keySet());
return new ArrayList<>(homes.keySet());
}
public void setHome(String name, Location loc) {
public void setHome(String name, final Location loc) {
//Invalid names will corrupt the yaml
name = StringUtil.safeString(name);
homes.put(name, loc);
@@ -197,7 +240,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
public void delHome(String name) throws Exception {
public void delHome(final String name) throws Exception {
String search = getHomeName(name);
if (!homes.containsKey(search)) {
search = StringUtil.safeString(search);
@@ -215,7 +258,9 @@ public abstract class UserData extends PlayerExtension implements IConf {
return config.hasProperty("home");
}
private String nickname;
public boolean hasHome(final String name) {
return config.hasProperty("homes." + name);
}
public String _getNickname() {
return config.getString("nickname");
@@ -225,44 +270,56 @@ public abstract class UserData extends PlayerExtension implements IConf {
return nickname;
}
public void setNickname(String nick) {
public void setNickname(final String nick) {
nickname = nick;
config.setProperty("nickname", nick);
config.save();
}
private List<Integer> unlimited;
private Set<Material> _getUnlimited() {
final Set<Material> retlist = new HashSet<>();
final List<String> configList = config.getStringList("unlimited");
for (final String s : configList) {
final Material mat = Material.matchMaterial(s);
if (mat != null) {
retlist.add(mat);
}
}
private List<Integer> _getUnlimited() {
return config.getIntegerList("unlimited");
return retlist;
}
public List<Integer> getUnlimited() {
public Set<Material> getUnlimited() {
return unlimited;
}
public boolean hasUnlimited(ItemStack stack) {
return unlimited.contains(stack.getTypeId());
public boolean hasUnlimited(final ItemStack stack) {
return unlimited.contains(stack.getType());
}
public void setUnlimited(ItemStack stack, boolean state) {
if (unlimited.contains(stack.getTypeId())) {
unlimited.remove(Integer.valueOf(stack.getTypeId()));
}
public void setUnlimited(final ItemStack stack, final boolean state) {
final boolean wasUpdated;
if (state) {
unlimited.add(stack.getTypeId());
wasUpdated = unlimited.add(stack.getType());
} else {
wasUpdated = unlimited.remove(stack.getType());
}
config.setProperty("unlimited", unlimited);
if (wasUpdated) {
applyUnlimited();
}
}
private void applyUnlimited() {
config.setProperty("unlimited", unlimited.stream().map(Enum::name).collect(Collectors.toList()));
config.save();
}
private Map<String, Object> powertools;
private Map<String, Object> _getPowertools() {
if (config.isConfigurationSection("powertools")) {
return config.getConfigurationSection("powertools").getValues(false);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
public void clearAllPowertools() {
@@ -272,20 +329,20 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
@SuppressWarnings("unchecked")
public List<String> getPowertool(ItemStack stack) {
return (List<String>) powertools.get("" + stack.getTypeId());
public List<String> getPowertool(final ItemStack stack) {
return (List<String>) powertools.get(stack.getType().name().toLowerCase(Locale.ENGLISH));
}
@SuppressWarnings("unchecked")
public List<String> getPowertool(int id) {
return (List<String>) powertools.get("" + id);
public List<String> getPowertool(final Material material) {
return (List<String>) powertools.get(material.name().toLowerCase(Locale.ENGLISH));
}
public void setPowertool(ItemStack stack, List<String> commandList) {
public void setPowertool(final ItemStack stack, final List<String> commandList) {
if (commandList == null || commandList.isEmpty()) {
powertools.remove("" + stack.getTypeId());
powertools.remove(stack.getType().name().toLowerCase(Locale.ENGLISH));
} else {
powertools.put("" + stack.getTypeId(), commandList);
powertools.put(stack.getType().name().toLowerCase(Locale.ENGLISH), commandList);
}
config.setProperty("powertools", powertools);
config.save();
@@ -295,12 +352,10 @@ public abstract class UserData extends PlayerExtension implements IConf {
return !powertools.isEmpty();
}
private Location lastLocation;
private Location _getLastLocation() {
try {
return config.getLocation("lastlocation", this.getBase().getServer());
} catch (InvalidWorldException e) {
} catch (final InvalidWorldException e) {
return null;
}
}
@@ -309,7 +364,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastLocation;
}
public void setLastLocation(Location loc) {
public void setLastLocation(final Location loc) {
if (loc == null || loc.getWorld() == null) {
return;
}
@@ -318,12 +373,10 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private Location logoutLocation;
private Location _getLogoutLocation() {
try {
return config.getLocation("logoutlocation", this.getBase().getServer());
} catch (InvalidWorldException e) {
} catch (final InvalidWorldException e) {
return null;
}
}
@@ -332,7 +385,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return logoutLocation;
}
public void setLogoutLocation(Location loc) {
public void setLogoutLocation(final Location loc) {
if (loc == null || loc.getWorld() == null) {
return;
}
@@ -341,8 +394,6 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private long lastTeleportTimestamp;
private long _getLastTeleportTimestamp() {
return config.getLong("timestamps.lastteleport", 0);
}
@@ -351,14 +402,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastTeleportTimestamp;
}
public void setLastTeleportTimestamp(long time) {
public void setLastTeleportTimestamp(final long time) {
lastTeleportTimestamp = time;
config.setProperty("timestamps.lastteleport", time);
config.save();
}
private long lastHealTimestamp;
private long _getLastHealTimestamp() {
return config.getLong("timestamps.lastheal", 0);
}
@@ -367,14 +416,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastHealTimestamp;
}
public void setLastHealTimestamp(long time) {
public void setLastHealTimestamp(final long time) {
lastHealTimestamp = time;
config.setProperty("timestamps.lastheal", time);
config.save();
}
private String jail;
private String _getJail() {
return config.getString("jail");
}
@@ -383,7 +430,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return jail;
}
public void setJail(String jail) {
public void setJail(final String jail) {
if (jail == null || jail.isEmpty()) {
this.jail = null;
config.removeProperty("jail");
@@ -394,8 +441,6 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private List<String> mails;
private List<String> _getMails() {
return config.getStringList("mail");
}
@@ -415,13 +460,11 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
public void addMail(String mail) {
public void addMail(final String mail) {
mails.add(mail);
setMails(mails);
}
private boolean teleportEnabled;
private boolean _getTeleportEnabled() {
return config.getBoolean("teleportenabled", true);
}
@@ -430,25 +473,61 @@ public abstract class UserData extends PlayerExtension implements IConf {
return teleportEnabled;
}
public void setTeleportEnabled(boolean set) {
public void setTeleportEnabled(final boolean set) {
teleportEnabled = set;
config.setProperty("teleportenabled", set);
config.save();
}
private List<String> ignoredPlayers;
public List<String> _getIgnoredPlayers() {
return Collections.synchronizedList(config.getStringList("ignore"));
private boolean _getAutoTeleportEnabled() {
return config.getBoolean("teleportauto", false);
}
public void setIgnoredPlayers(List<String> players) {
public boolean isAutoTeleportEnabled() {
return autoTeleportEnabled;
}
public void setAutoTeleportEnabled(final boolean set) {
autoTeleportEnabled = set;
config.setProperty("teleportauto", set);
config.save();
}
public List<UUID> _getIgnoredPlayers() {
final List<UUID> players = new ArrayList<>();
for (final String uuid : config.getStringList("ignore")) {
try {
players.add(UUID.fromString(uuid));
} catch (final IllegalArgumentException ignored) {
}
}
return Collections.synchronizedList(players);
}
@Deprecated
public void setIgnoredPlayers(final List<String> players) {
final List<UUID> uuids = new ArrayList<>();
for (final String player : players) {
final User user = ess.getOfflineUser(player);
if (user == null) {
return;
}
uuids.add(user.getBase().getUniqueId());
}
setIgnoredPlayerUUIDs(uuids);
}
public void setIgnoredPlayerUUIDs(final List<UUID> players) {
if (players == null || players.isEmpty()) {
ignoredPlayers = Collections.synchronizedList(new ArrayList<String>());
ignoredPlayers = Collections.synchronizedList(new ArrayList<>());
config.removeProperty("ignore");
} else {
ignoredPlayers = players;
config.setProperty("ignore", players);
final List<String> uuids = new ArrayList<>();
for (final UUID uuid : players) {
uuids.add(uuid.toString());
}
config.setProperty("ignore", uuids);
}
config.save();
}
@@ -462,21 +541,22 @@ public abstract class UserData extends PlayerExtension implements IConf {
return isIgnoredPlayer(user);
}
public boolean isIgnoredPlayer(IUser user) {
return (ignoredPlayers.contains(user.getName().toLowerCase(Locale.ENGLISH)) && !user.isIgnoreExempt());
public boolean isIgnoredPlayer(final IUser user) {
return ignoredPlayers.contains(user.getBase().getUniqueId()) && !user.isIgnoreExempt();
}
public void setIgnoredPlayer(IUser user, boolean set) {
public void setIgnoredPlayer(final IUser user, final boolean set) {
final UUID uuid = user.getBase().getUniqueId();
if (set) {
ignoredPlayers.add(user.getName().toLowerCase(Locale.ENGLISH));
if (!ignoredPlayers.contains(uuid)) {
ignoredPlayers.add(uuid);
}
} else {
ignoredPlayers.remove(user.getName().toLowerCase(Locale.ENGLISH));
ignoredPlayers.remove(uuid);
}
setIgnoredPlayers(ignoredPlayers);
setIgnoredPlayerUUIDs(ignoredPlayers);
}
private boolean godmode;
private boolean _getGodModeEnabled() {
return config.getBoolean("godmode", false);
}
@@ -485,14 +565,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return godmode;
}
public void setGodModeEnabled(boolean set) {
public void setGodModeEnabled(final boolean set) {
godmode = set;
config.setProperty("godmode", set);
config.save();
}
private boolean muted;
public boolean _getMuted() {
return config.getBoolean("muted", false);
}
@@ -505,13 +583,34 @@ public abstract class UserData extends PlayerExtension implements IConf {
return muted;
}
public void setMuted(boolean set) {
public void setMuted(final boolean set) {
muted = set;
config.setProperty("muted", set);
config.save();
}
private long muteTimeout;
public String _getMuteReason() {
return config.getString("muteReason");
}
public String getMuteReason() {
return muteReason;
}
public void setMuteReason(final String reason) {
if (reason == null) {
config.removeProperty("muteReason");
muteReason = null;
} else {
muteReason = reason;
config.setProperty("muteReason", reason);
}
config.save();
}
public boolean hasMuteReason() {
return muteReason != null;
}
private long _getMuteTimeout() {
return config.getLong("timestamps.mute", 0);
@@ -521,14 +620,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return muteTimeout;
}
public void setMuteTimeout(long time) {
public void setMuteTimeout(final long time) {
muteTimeout = time;
config.setProperty("timestamps.mute", time);
config.save();
}
private boolean jailed;
private boolean _getJailed() {
return config.getBoolean("jailed", false);
}
@@ -537,20 +634,18 @@ public abstract class UserData extends PlayerExtension implements IConf {
return jailed;
}
public void setJailed(boolean set) {
public void setJailed(final boolean set) {
jailed = set;
config.setProperty("jailed", set);
config.save();
}
public boolean toggleJailed() {
boolean ret = !isJailed();
final boolean ret = !isJailed();
setJailed(ret);
return ret;
}
private long jailTimeout;
private long _getJailTimeout() {
return config.getLong("timestamps.jail", 0);
}
@@ -559,14 +654,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return jailTimeout;
}
public void setJailTimeout(long time) {
public void setJailTimeout(final long time) {
jailTimeout = time;
config.setProperty("timestamps.jail", time);
config.save();
}
private long lastLogin;
private long _getLastLogin() {
return config.getLong("timestamps.login", 0);
}
@@ -575,12 +668,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastLogin;
}
private void _setLastLogin(long time) {
lastLogin = time;
config.setProperty("timestamps.login", time);
}
public void setLastLogin(long time) {
public void setLastLogin(final long time) {
_setLastLogin(time);
if (base.getAddress() != null && base.getAddress().getAddress() != null) {
_setLastLoginAddress(base.getAddress().getAddress().getHostAddress());
@@ -588,7 +676,10 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private long lastLogout;
private void _setLastLogin(final long time) {
lastLogin = time;
config.setProperty("timestamps.login", time);
}
private long _getLastLogout() {
return config.getLong("timestamps.logout", 0);
@@ -598,14 +689,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastLogout;
}
public void setLastLogout(long time) {
public void setLastLogout(final long time) {
lastLogout = time;
config.setProperty("timestamps.logout", time);
config.save();
}
private String lastLoginAddress;
private String _getLastLoginAddress() {
return config.getString("ipAddress", "");
}
@@ -614,13 +703,11 @@ public abstract class UserData extends PlayerExtension implements IConf {
return lastLoginAddress;
}
private void _setLastLoginAddress(String address) {
private void _setLastLoginAddress(final String address) {
lastLoginAddress = address;
config.setProperty("ipAddress", address);
}
private boolean afk;
private boolean _getAfk() {
return config.getBoolean("afk", false);
}
@@ -629,15 +716,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return afk;
}
public void _setAfk(boolean set) {
public void _setAfk(final boolean set) {
afk = set;
config.setProperty("afk", set);
config.save();
}
private boolean newplayer;
private String geolocation;
private String _getGeoLocation() {
return config.getString("geolocation");
}
@@ -646,7 +730,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return geolocation;
}
public void setGeoLocation(String geolocation) {
public void setGeoLocation(final String geolocation) {
if (geolocation == null || geolocation.isEmpty()) {
this.geolocation = null;
config.removeProperty("geolocation");
@@ -657,8 +741,6 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private boolean isSocialSpyEnabled;
private boolean _isSocialSpyEnabled() {
return config.getBoolean("socialspy", false);
}
@@ -667,14 +749,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return isSocialSpyEnabled;
}
public void setSocialSpyEnabled(boolean status) {
public void setSocialSpyEnabled(final boolean status) {
isSocialSpyEnabled = status;
config.setProperty("socialspy", status);
config.save();
}
private boolean isNPC;
private boolean _isNPC() {
return config.getBoolean("npc", false);
}
@@ -683,43 +763,39 @@ public abstract class UserData extends PlayerExtension implements IConf {
return isNPC;
}
private String lastAccountName = null;
public void setNPC(final boolean set) {
isNPC = set;
config.setProperty("npc", set);
config.save();
}
public String getLastAccountName() {
return lastAccountName;
}
public String _getLastAccountName() {
return config.getString("lastAccountName", null);
}
public void setLastAccountName(String lastAccountName) {
public void setLastAccountName(final String lastAccountName) {
this.lastAccountName = lastAccountName;
config.setProperty("lastAccountName", lastAccountName);
config.save();
ess.getUserMap().trackUUID(getConfigUUID(), lastAccountName, true);
}
public void setNPC(boolean set) {
isNPC = set;
config.setProperty("npc", set);
config.save();
public String _getLastAccountName() {
return config.getString("lastAccountName", null);
}
private boolean arePowerToolsEnabled;
public boolean arePowerToolsEnabled() {
return arePowerToolsEnabled;
}
public void setPowerToolsEnabled(boolean set) {
public void setPowerToolsEnabled(final boolean set) {
arePowerToolsEnabled = set;
config.setProperty("powertoolsenabled", set);
config.save();
}
public boolean togglePowerToolsEnabled() {
boolean ret = !arePowerToolsEnabled();
final boolean ret = !arePowerToolsEnabled();
setPowerToolsEnabled(ret);
return ret;
}
@@ -728,14 +804,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return config.getBoolean("powertoolsenabled", true);
}
private Map<String, Long> kitTimestamps;
private Map<String, Long> _getKitTimestamps() {
if (config.isConfigurationSection("timestamps.kits")) {
final ConfigurationSection section = config.getConfigurationSection("timestamps.kits");
final Map<String, Long> timestamps = new HashMap<String, Long>();
for (String command : section.getKeys(false)) {
final Map<String, Long> timestamps = new HashMap<>();
for (final String command : section.getKeys(false)) {
if (section.isLong(command)) {
timestamps.put(command.toLowerCase(Locale.ENGLISH), section.getLong(command));
} else if (section.isInt(command)) {
@@ -744,24 +818,25 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
return timestamps;
}
return new HashMap<String, Long>();
return new HashMap<>();
}
public long getKitTimestamp(String name) {
name = name.replace('.', '_').replace('/', '_');
name = name.replace('.', '_').replace('/', '_').toLowerCase(Locale.ENGLISH);
if (kitTimestamps != null && kitTimestamps.containsKey(name)) {
return kitTimestamps.get(name);
}
return 0l;
return 0L;
}
public void setKitTimestamp(final String name, final long time) {
kitTimestamps.put(name.toLowerCase(Locale.ENGLISH), time);
public void setKitTimestamp(String name, final long time) {
name = name.replace('.', '_').replace('/', '_').toLowerCase(Locale.ENGLISH);
kitTimestamps.put(name, time);
config.setProperty("timestamps.kits", kitTimestamps);
config.save();
}
public void setConfigProperty(String node, Object object) {
public void setConfigProperty(String node, final Object object) {
final String prefix = "info.";
node = prefix + node;
if (object instanceof Map) {
@@ -782,37 +857,34 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (config.isConfigurationSection("info")) {
return config.getConfigurationSection("info").getKeys(true);
}
return new HashSet<String>();
return new HashSet<>();
}
public Map<String, Object> getConfigMap() {
if (config.isConfigurationSection("info")) {
return config.getConfigurationSection("info").getValues(true);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
public Map<String, Object> getConfigMap(String node) {
public Map<String, Object> getConfigMap(final String node) {
if (config.isConfigurationSection("info." + node)) {
return config.getConfigurationSection("info." + node).getValues(true);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
// Pattern, Date. Pattern for less pattern creations
private Map<Pattern, Long> commandCooldowns;
private Map<Pattern, Long> _getCommandCooldowns() {
if (!config.isConfigurationSection("timestamps.command-cooldowns")) {
if (!config.contains("timestamps.command-cooldowns")) {
return null;
}
// See saveCommandCooldowns() for deserialization explanation
List<Map<?, ?>> section = config.getMapList("timestamps.command-cooldowns");
HashMap<Pattern, Long> result = new HashMap<>();
for (Map<?, ?> map : section) {
Pattern pattern = Pattern.compile(map.get("pattern").toString());
long expiry = ((Number) map.get("expiry")).longValue();
final List<Map<?, ?>> section = config.getMapList("timestamps.command-cooldowns");
final HashMap<Pattern, Long> result = new HashMap<>();
for (final Map<?, ?> map : section) {
final Pattern pattern = Pattern.compile(map.get("pattern").toString());
final long expiry = ((Number) map.get("expiry")).longValue();
result.put(pattern, expiry);
}
return result;
@@ -825,9 +897,9 @@ public abstract class UserData extends PlayerExtension implements IConf {
return Collections.unmodifiableMap(this.commandCooldowns);
}
public Date getCommandCooldownExpiry(String label) {
public Date getCommandCooldownExpiry(final String label) {
if (commandCooldowns != null) {
for (Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) {
for (final Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) {
if (entry.getKey().matcher(label).matches()) {
return new Date(entry.getValue());
}
@@ -836,7 +908,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
return null;
}
public void addCommandCooldown(Pattern pattern, Date expiresAt, boolean save) {
public void addCommandCooldown(final Pattern pattern, final Date expiresAt, final boolean save) {
if (this.commandCooldowns == null) {
this.commandCooldowns = new HashMap<>();
}
@@ -846,12 +918,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
}
public boolean clearCommandCooldown(Pattern pattern) {
public boolean clearCommandCooldown(final Pattern pattern) {
if (this.commandCooldowns == null) {
return false; // false for no modification
}
if(this.commandCooldowns.remove(pattern) != null) {
if (this.commandCooldowns.remove(pattern) != null) {
saveCommandCooldowns();
return true;
}
@@ -865,14 +937,14 @@ public abstract class UserData extends PlayerExtension implements IConf {
// When serializing patterns (which commonly include full stops .) Bukkit/Essentials config framework
// interprets it as a path separator, thus it breaks up the regex into sub nodes causing invalid syntax.
// Thus each command cooldown is instead stored as a Map of {pattern: .., expiry: ..} to work around this.
List<Object> serialized = new ArrayList<>();
for (Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) {
final List<Object> serialized = new ArrayList<>();
for (final Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) {
// Don't save expired cooldowns
if (entry.getValue() < System.currentTimeMillis()) {
continue;
}
Map<?, ?> map = ImmutableMap.builder()
final Map<?, ?> map = ImmutableMap.builder()
.put("pattern", entry.getKey().pattern())
.put("expiry", entry.getValue())
.build();
@@ -882,8 +954,6 @@ public abstract class UserData extends PlayerExtension implements IConf {
save();
}
private boolean acceptingPay = true; // players accept pay by default
public boolean _getAcceptingPay() {
return config.getBoolean("acceptingPay", true);
}
@@ -892,14 +962,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return acceptingPay;
}
public void setAcceptingPay(boolean acceptingPay) {
public void setAcceptingPay(final boolean acceptingPay) {
this.acceptingPay = acceptingPay;
config.setProperty("acceptingPay", acceptingPay);
save();
}
private Boolean confirmPay;
private Boolean _getConfirmPay() {
return (Boolean) config.get("confirm-pay");
}
@@ -908,14 +976,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
return confirmPay != null ? confirmPay : ess.getSettings().isConfirmCommandEnabledByDefault("pay");
}
public void setPromptingPayConfirm(boolean prompt) {
public void setPromptingPayConfirm(final boolean prompt) {
this.confirmPay = prompt;
config.setProperty("confirm-pay", prompt);
save();
}
private Boolean confirmClear;
private Boolean _getConfirmClear() {
return (Boolean) config.get("confirm-clear");
}
@@ -924,12 +990,26 @@ public abstract class UserData extends PlayerExtension implements IConf {
return confirmClear != null ? confirmClear : ess.getSettings().isConfirmCommandEnabledByDefault("clearinventory");
}
public void setPromptingClearConfirm(boolean prompt) {
public void setPromptingClearConfirm(final boolean prompt) {
this.confirmClear = prompt;
config.setProperty("confirm-clear", prompt);
save();
}
private boolean _getLastMessageReplyRecipient() {
return config.getBoolean("last-message-reply-recipient", ess.getSettings().isLastMessageReplyRecipient());
}
public boolean isLastMessageReplyRecipient() {
return this.lastMessageReplyRecipient;
}
public void setLastMessageReplyRecipient(final boolean enabled) {
this.lastMessageReplyRecipient = enabled;
config.setProperty("last-message-reply-recipient", enabled);
save();
}
public UUID getConfigUUID() {
return config.uuid;
}
@@ -13,22 +13,26 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
public class UserMap extends CacheLoader<String, User> implements IConf {
private static boolean legacy = false;
private static Method getLegacy;
private final transient IEssentials ess;
private final transient ConcurrentSkipListSet<UUID> keys = new ConcurrentSkipListSet<>();
private final transient ConcurrentSkipListMap<String, UUID> names = new ConcurrentSkipListMap<>();
private final transient ConcurrentSkipListMap<UUID, ArrayList<String>> history = new ConcurrentSkipListMap<>();
private UUIDMap uuidMap;
private final UUIDMap uuidMap;
private final transient Cache<String, User> users;
private static boolean legacy = false;
private final Pattern validUserPattern = Pattern.compile("^[a-zA-Z0-9_]{2,16}$");
public UserMap(final IEssentials ess) {
super();
@@ -36,11 +40,11 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
uuidMap = new UUIDMap(ess);
//RemovalListener<UUID, User> remListener = new UserMapRemovalListener();
//users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().removalListener(remListener).build(this);
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
int maxCount = ess.getSettings().getMaxUserCacheCount();
final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
final int maxCount = ess.getSettings().getMaxUserCacheCount();
try {
cacheBuilder.maximumSize(maxCount);
} catch (NoSuchMethodError nsme) {
} catch (final NoSuchMethodError nsme) {
legacy = true;
legacyMaximumSize(cacheBuilder, maxCount);
}
@@ -53,29 +57,26 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
}
private void loadAllUsersAsync(final IEssentials ess) {
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
synchronized (users) {
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
keys.clear();
users.invalidateAll();
for (String string : userdir.list()) {
if (!string.endsWith(".yml")) {
continue;
}
final String name = string.substring(0, string.length() - 4);
try {
keys.add(UUID.fromString(name));
} catch (IllegalArgumentException ex) {
//Ignore these users till they rejoin.
}
}
uuidMap.loadAllUsers(names, history);
ess.runTaskAsynchronously(() -> {
synchronized (users) {
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
keys.clear();
users.invalidateAll();
for (final String string : userdir.list()) {
if (!string.endsWith(".yml")) {
continue;
}
final String name = string.substring(0, string.length() - 4);
try {
keys.add(UUID.fromString(name));
} catch (final IllegalArgumentException ex) {
//Ignore these users till they rejoin.
}
}
uuidMap.loadAllUsers(names, history);
}
});
}
@@ -95,12 +96,12 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
final File userFile = getUserFileFromString(sanitizedName);
if (userFile.exists()) {
ess.getLogger().info("Importing user " + name + " to usermap.");
User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess);
final User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess);
trackUUID(user.getBase().getUniqueId(), user.getName(), true);
return user;
}
return null;
} catch (UncheckedExecutionException ex) {
} catch (final UncheckedExecutionException ex) {
return null;
}
}
@@ -112,18 +113,16 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
} else {
return legacyCacheGet(uuid);
}
} catch (ExecutionException ex) {
return null;
} catch (UncheckedExecutionException ex) {
} catch (final ExecutionException | UncheckedExecutionException ex) {
return null;
}
}
public void trackUUID(final UUID uuid, final String name, boolean replace) {
public void trackUUID(final UUID uuid, final String name, final boolean replace) {
if (uuid != null) {
keys.add(uuid);
if (name != null && name.length() > 0) {
final String keyName = StringUtil.safeString(name);
final String keyName = ess.getSettings().isSafeUsermap() ? StringUtil.safeString(name) : name;
if (!names.containsKey(keyName)) {
names.put(keyName, uuid);
uuidMap.writeUUIDMap();
@@ -144,7 +143,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
@Override
public User load(final String stringUUID) throws Exception {
UUID uuid = UUID.fromString(stringUUID);
final UUID uuid = UUID.fromString(stringUUID);
Player player = ess.getServer().getPlayer(uuid);
if (player != null) {
final User user = new User(player, ess);
@@ -180,7 +179,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
ess.getLogger().warning("Name collection is null, cannot remove user.");
return;
}
UUID uuid = names.get(name);
final UUID uuid = names.get(name);
if (uuid != null) {
keys.remove(uuid);
users.invalidate(uuid.toString());
@@ -212,6 +211,18 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
public UUIDMap getUUIDMap() {
return uuidMap;
}
// class UserMapRemovalListener implements RemovalListener
// {
// @Override
// public void onRemoval(final RemovalNotification notification)
// {
// Object value = notification.getValue();
// if (value != null)
// {
// ((User)value).cleanup();
// }
// }
// }
private File getUserFileFromID(final UUID uuid) {
final File userFolder = new File(ess.getDataFolder(), "userdata");
@@ -222,20 +233,6 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
final File userFolder = new File(ess.getDataFolder(), "userdata");
return new File(userFolder, StringUtil.sanitizeFileName(name) + ".yml");
}
// class UserMapRemovalListener implements RemovalListener
// {
// @Override
// public void onRemoval(final RemovalNotification notification)
// {
// Object value = notification.getValue();
// if (value != null)
// {
// ((User)value).cleanup();
// }
// }
// }
private final Pattern validUserPattern = Pattern.compile("^[a-zA-Z0-9_]{2,16}$");
@SuppressWarnings("deprecation")
public User getUserFromBukkit(String name) {
@@ -247,14 +244,14 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
if (name == null || !validUserPattern.matcher(name).matches()) {
return null;
}
org.bukkit.OfflinePlayer offlinePlayer = ess.getServer().getOfflinePlayer(name);
final org.bukkit.OfflinePlayer offlinePlayer = ess.getServer().getOfflinePlayer(name);
if (offlinePlayer == null) {
return null;
}
UUID uuid;
final UUID uuid;
try {
uuid = offlinePlayer.getUniqueId();
} catch (UnsupportedOperationException | NullPointerException e) {
} catch (final UnsupportedOperationException | NullPointerException e) {
return null;
}
// This is how Bukkit generates fake UUIDs
@@ -266,12 +263,10 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
}
}
private static Method getLegacy;
private User legacyCacheGet(UUID uuid) {
private User legacyCacheGet(final UUID uuid) {
if (getLegacy == null) {
Class<?> usersClass = users.getClass();
for (Method m : usersClass.getDeclaredMethods()) {
final Class<?> usersClass = users.getClass();
for (final Method m : usersClass.getDeclaredMethods()) {
if (m.getName().equals("get")) {
getLegacy = m;
getLegacy.setAccessible(true);
@@ -281,25 +276,25 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
}
try {
return (User) getLegacy.invoke(users, uuid.toString());
} catch (IllegalAccessException | InvocationTargetException e) {
} catch (final IllegalAccessException | InvocationTargetException e) {
return null;
}
}
private void legacyMaximumSize(CacheBuilder builder, int maxCount) {
private void legacyMaximumSize(final CacheBuilder builder, final int maxCount) {
try {
Method maxSizeLegacy = builder.getClass().getDeclaredMethod("maximumSize", Integer.TYPE);
final Method maxSizeLegacy = builder.getClass().getDeclaredMethod("maximumSize", Integer.TYPE);
maxSizeLegacy.setAccessible(true);
maxSizeLegacy.invoke(builder, maxCount);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
} catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private Cache<String, User> legacyBuild(CacheBuilder builder) {
private Cache<String, User> legacyBuild(final CacheBuilder builder) {
Method build = null;
for (Method method : builder.getClass().getDeclaredMethods()) {
for (final Method method : builder.getClass().getDeclaredMethods()) {
if (method.getName().equals("build")) {
build = method;
break;
@@ -310,7 +305,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
assert build != null;
build.setAccessible(true);
legacyUsers = (Cache<String, User>) build.invoke(builder, this);
} catch (IllegalAccessException | InvocationTargetException e) {
} catch (final IllegalAccessException | InvocationTargetException e) {
legacyUsers = null;
}
return legacyUsers;
@@ -9,20 +9,25 @@ import org.bukkit.Server;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
public class Warps implements IConf, net.ess3.api.IWarps {
private static final Logger logger = Logger.getLogger("Essentials");
private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>();
private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<>();
private final File warpsFolder;
private final Server server;
public Warps(Server server, File dataFolder) {
public Warps(final Server server, final File dataFolder) {
this.server = server;
warpsFolder = new File(dataFolder, "warps");
if (!warpsFolder.exists()) {
@@ -38,17 +43,17 @@ public class Warps implements IConf, net.ess3.api.IWarps {
@Override
public Collection<String> getList() {
final List<String> keys = new ArrayList<String>();
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) {
final List<String> keys = new ArrayList<>();
for (final StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) {
keys.add(stringIgnoreCase.getString());
}
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
keys.sort(String.CASE_INSENSITIVE_ORDER);
return keys;
}
@Override
public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException {
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
public Location getWarp(final String warp) throws WarpNotFoundException, InvalidWorldException {
final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null) {
throw new WarpNotFoundException();
}
@@ -56,11 +61,16 @@ public class Warps implements IConf, net.ess3.api.IWarps {
}
@Override
public void setWarp(String name, Location loc) throws Exception {
String filename = StringUtil.sanitizeFileName(name);
public void setWarp(final String name, final Location loc) throws Exception {
setWarp(null, name, loc);
}
@Override
public void setWarp(final IUser user, final String name, final Location loc) throws Exception {
final String filename = StringUtil.sanitizeFileName(name);
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
File confFile = new File(warpsFolder, filename + ".yml");
final File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists()) {
throw new Exception(tl("similarWarpExist"));
}
@@ -69,16 +79,31 @@ public class Warps implements IConf, net.ess3.api.IWarps {
}
conf.setProperty(null, loc);
conf.setProperty("name", name);
if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString());
try {
conf.saveWithError();
} catch (IOException ex) {
} catch (final IOException ex) {
throw new IOException(tl("invalidWarpName"));
}
}
@Override
public void removeWarp(String name) throws Exception {
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
public UUID getLastOwner(final String warp) throws WarpNotFoundException {
final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null) {
throw new WarpNotFoundException();
}
UUID uuid = null;
try {
uuid = UUID.fromString(conf.getString("lastowner"));
} catch (final Exception ignored) {
}
return uuid;
}
@Override
public void removeWarp(final String name) throws Exception {
final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
throw new Exception(tl("warpNotExist"));
}
@@ -91,19 +116,19 @@ public class Warps implements IConf, net.ess3.api.IWarps {
@Override
public final void reloadConfig() {
warpPoints.clear();
File[] listOfFiles = warpsFolder.listFiles();
final File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1) {
for (int i = 0; i < listOfFiles.length; i++) {
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".yml")) {
for (final File listOfFile : listOfFiles) {
final String filename = listOfFile.getName();
if (listOfFile.isFile() && filename.endsWith(".yml")) {
try {
EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
final EssentialsConf conf = new EssentialsConf(listOfFile);
conf.load();
String name = conf.getString("name");
final String name = conf.getString("name");
if (name != null) {
warpPoints.put(new StringIgnoreCase(name), conf);
}
} catch (Exception ex) {
} catch (final Exception ex) {
logger.log(Level.WARNING, tl("loadWarpError", filename), ex);
}
}
@@ -111,9 +136,12 @@ public class Warps implements IConf, net.ess3.api.IWarps {
}
}
//This is here for future 3.x api support. Not implemented here becasue storage is handled differently
/**
* @deprecated This method relates to the abandoned 3.x storage refactor and is not implemented.
*/
@Override
public File getWarpFile(String name) throws InvalidNameException {
@Deprecated
public File getWarpFile(final String name) throws InvalidNameException {
throw new UnsupportedOperationException("Not supported yet.");
}
@@ -125,7 +153,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
private static class StringIgnoreCase {
private final String string;
public StringIgnoreCase(String string) {
StringIgnoreCase(final String string) {
this.string = string;
}
@@ -135,7 +163,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
}
@Override
public boolean equals(Object o) {
public boolean equals(final Object o) {
if (o instanceof StringIgnoreCase) {
return getString().equalsIgnoreCase(((StringIgnoreCase) o).getString());
}
@@ -1,6 +1,7 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
@@ -11,73 +12,77 @@ import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Worth implements IConf {
private final EssentialsConf config;
public Worth(File dataFolder) {
public Worth(final File dataFolder) {
config = new EssentialsConf(new File(dataFolder, "worth.yml"));
config.setTemplateName("/worth.yml");
config.load();
}
public BigDecimal getPrice(ItemStack itemStack) {
String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
/**
* Get the value of an item stack from the config.
*
* @param ess The Essentials instance.
* @param itemStack The item stack to look up in the config.
* @return The price from the config.
*/
public BigDecimal getPrice(final IEssentials ess, final ItemStack itemStack) {
BigDecimal result;
//First check for matches with item name
final String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
// Check for matches with data value from stack
// Note that we always default to BigDecimal.ONE.negate(), equivalent to -1
result = config.getBigDecimal("worth." + itemname + "." + itemStack.getDurability(), BigDecimal.ONE.negate());
// Check for matches with data value 0
if (result.signum() < 0) {
final ConfigurationSection itemNameMatch = config.getConfigurationSection("worth." + itemname);
if (itemNameMatch != null && itemNameMatch.getKeys(false).size() == 1) {
result = config.getBigDecimal("worth." + itemname + ".0", BigDecimal.ONE.negate());
}
}
// Check for matches with data value wildcard
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemname + ".*", BigDecimal.ONE.negate());
}
// Check for matches with item name alone
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemname, BigDecimal.ONE.negate());
}
//Now we should check for item ID
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + "." + itemStack.getDurability(), BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
final ConfigurationSection itemNumberMatch = config.getConfigurationSection("worth." + itemStack.getTypeId());
if (itemNumberMatch != null && itemNumberMatch.getKeys(false).size() == 1) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".0", BigDecimal.ONE.negate());
}
}
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".*", BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId(), BigDecimal.ONE.negate());
}
//This is to match the old worth syntax
if (result.signum() < 0) {
result = config.getBigDecimal("worth-" + itemStack.getTypeId(), BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
return null;
}
return result;
}
public int getAmount(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception {
/**
* Get the amount of items to be sold from a player's inventory.
*
* @param ess The Essentials instance.
* @param user The user attempting to sell the item.
* @param is A stack of the item to search the inventory for.
* @param args The amount to try to sell.
* @param isBulkSell Whether or not to try and bulk sell all items.
* @return The amount of items to sell from the player's inventory.
* @throws Exception Thrown if trying to sell air or an invalid amount.
*/
public int getAmount(final IEssentials ess, final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception {
if (is == null || is.getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
}
int id = is.getTypeId();
int amount = 0;
if (args.length > 1) {
try {
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
} catch (NumberFormatException ex) {
} catch (final NumberFormatException ex) {
throw new NotEnoughArgumentsException(ex);
}
if (args[1].startsWith("-")) {
@@ -85,15 +90,15 @@ public class Worth implements IConf {
}
}
boolean stack = args.length > 1 && args[1].endsWith("s");
boolean requireStack = ess.getSettings().isTradeInStacks(id);
final boolean stack = args.length > 1 && args[1].endsWith("s");
final boolean requireStack = ess.getSettings().isTradeInStacks(is.getType());
if (requireStack && !stack) {
throw new Exception(tl("itemMustBeStacked"));
}
int max = 0;
for (ItemStack s : user.getBase().getInventory().getContents()) {
for (final ItemStack s : user.getBase().getInventory().getContents()) {
if (s == null || !s.isSimilar(is)) {
continue;
}
@@ -123,14 +128,23 @@ public class Worth implements IConf {
return amount;
}
public void setPrice(ItemStack itemStack, double price) {
if (itemStack.getType().getData() == null) {
config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), price);
} else {
/**
* Set the price of an item and save it to the config.
*
* @param ess The Essentials instance.
* @param itemStack A stack of the item to save.
* @param price The new price of the item.
*/
public void setPrice(final IEssentials ess, final ItemStack itemStack, final double price) {
String path = "worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
// Spigot 1.13+ throws an exception if a 1.13+ plugin even *attempts* to do set data.
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01) && itemStack.getType().getData() == null) {
// Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0.
config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "") + "." + itemStack.getDurability(), price);
path = path + "." + itemStack.getDurability();
}
config.removeProperty("worth-" + itemStack.getTypeId());
config.setProperty(path, price);
config.save();
}
@@ -8,6 +8,8 @@ import com.earth2me.essentials.utils.StringUtil;
import com.google.common.base.Charsets;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.UserBalanceUpdateEvent;
import org.bukkit.entity.Player;
import java.io.File;
import java.math.BigDecimal;
@@ -16,34 +18,35 @@ import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Instead of using this api directly, we recommend to use the register plugin: http://bit.ly/RegisterMethod
* You should use Vault instead of directly using this class.
*/
public class Economy {
public Economy() {
}
private static final Logger logger = Logger.getLogger("Essentials");
private static IEssentials ess;
private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded.";
public static final MathContext MATH_CONTEXT = MathContext.DECIMAL128;
private static final Logger logger = Logger.getLogger("Essentials");
private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded.";
private static IEssentials ess;
protected Economy() {
}
/**
* @param aEss the ess to set
*/
public static void setEss(IEssentials aEss) {
public static void setEss(final IEssentials aEss) {
ess = aEss;
}
private static void createNPCFile(String name) {
File folder = new File(ess.getDataFolder(), "userdata");
final File folder = new File(ess.getDataFolder(), "userdata");
name = StringUtil.safeString(name);
if (!folder.exists()) {
folder.mkdirs();
if (!folder.mkdirs()) {
throw new RuntimeException("Error while creating userdata directory!");
}
}
UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8));
EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml"));
final UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8));
final EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml"));
npcConfig.load();
npcConfig.setProperty("npc", true);
npcConfig.setProperty("lastAccountName", name);
@@ -52,40 +55,108 @@ public class Economy {
ess.getUserMap().trackUUID(npcUUID, name, false);
}
private static void deleteNPC(String name) {
User user = ess.getUser(name);
private static void deleteNPC(final String name) {
final User user = ess.getUser(name);
user.reset();
}
private static User getUserByName(String name) {
private static User getUserByName(final String name) {
if (ess == null) {
throw new RuntimeException(noCallBeforeLoad);
}
if (name == null) {
throw new RuntimeException("Economy username cannot be null");
throw new IllegalArgumentException("Economy username cannot be null");
}
return ess.getUser(name);
User user = ess.getUser(name);
if (user == null) {
/*
Attempt lookup using UUID - this prevents balance resets when accessing economy
via Vault during player join.
See: https://github.com/EssentialsX/Essentials/issues/2400
*/
final Player player = ess.getServer().getPlayerExact(name);
if (player != null) {
user = ess.getUser(player.getUniqueId());
if (user != null) {
logger.info(String.format("[Economy] Found player %s by UUID %s but not by their actual name - they may have changed their username", name, player.getUniqueId().toString()));
}
}
}
return user;
}
private static User getUserByUUID(final UUID uuid) {
if (ess == null) {
throw new RuntimeException(noCallBeforeLoad);
}
if (uuid == null) {
throw new IllegalArgumentException("Economy uuid cannot be null");
}
return ess.getUser(uuid);
}
/**
* Returns the balance of a user
*
* @param name Name of the user
*
* @return balance
*
* @throws UserDoesNotExistException
* @deprecated Use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)}
*/
@Deprecated
public static double getMoney(String name) throws UserDoesNotExistException {
return getMoneyExact(name).doubleValue();
public static double getMoney(final String name) throws UserDoesNotExistException {
final BigDecimal exactAmount = getMoneyExact(name);
double amount = exactAmount.doubleValue();
if (new BigDecimal(amount).compareTo(exactAmount) > 0) {
// closest double is bigger than the exact amount
// -> get the previous double value to not return more money than the user has
amount = Math.nextAfter(amount, Double.NEGATIVE_INFINITY);
}
return amount;
}
public static BigDecimal getMoneyExact(String name) throws UserDoesNotExistException {
User user = getUserByName(name);
/**
* @param name Name of user
* @return Exact balance of user
* @throws UserDoesNotExistException
* @deprecated Usernames can change, use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)}
*/
@Deprecated
public static BigDecimal getMoneyExact(final String name) throws UserDoesNotExistException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return getMoneyExact(user);
}
/**
* Get the exact balance of the account with the given UUID.
*
* @param uuid The UUID of the user account to retrieve the balance for
* @return The account's balance
* @throws UserDoesNotExistException If the user does not exist
*/
public static BigDecimal getMoneyExact(final UUID uuid) throws UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
return getMoneyExact(user);
}
/**
* Get the exact balance of the account with the given UUID.
*
* @param user The user account to retrieve the balance for
* @return The account's balance
*/
public static BigDecimal getMoneyExact(final User user) {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
return user.getMoney();
}
@@ -94,24 +165,64 @@ public class Economy {
*
* @param name Name of the user
* @param balance The balance you want to set
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)}
*/
@Deprecated
public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException {
public static void setMoney(final String name, final double balance) throws UserDoesNotExistException, NoLoanPermittedException {
try {
setMoney(name, BigDecimal.valueOf(balance));
} catch (ArithmeticException e) {
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e);
}
}
public static void setMoney(String name, BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException {
User user = getUserByName(name);
/**
* Sets the balance of a user
*
* @param name Name of user
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Usernames can change use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)}
*/
@Deprecated
public static void setMoney(final String name, final BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
setMoney(user, balance);
}
/**
* Sets the balance of a user
*
* @param uuid UUID of user
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void setMoney(final UUID uuid, final BigDecimal balance) throws NoLoanPermittedException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
setMoney(user, balance);
}
/**
* Sets the balance of a user
*
* @param user User
* @param balance The balance you want to set
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void setMoney(final User user, final BigDecimal balance) throws NoLoanPermittedException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) {
throw new NoLoanPermittedException();
}
@@ -119,118 +230,307 @@ public class Economy {
throw new NoLoanPermittedException();
}
try {
user.setMoney(balance);
} catch (MaxMoneyException ex) {
user.setMoney(balance, UserBalanceUpdateEvent.Cause.API);
} catch (final MaxMoneyException ex) {
//TODO: Update API to show max balance errors
}
Trade.log("API", "Set", "API", name, new Trade(balance, ess), null, null, null, ess);
Trade.log("API", "Set", "API", user.getName(), new Trade(balance, ess), null, null, null, ess);
}
/**
* Adds money to the balance of a user
* <p>
* Use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)}
*
* @param name Name of the user
* @param amount The money you want to add
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
@Deprecated
public static void add(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
try {
add(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e);
}
}
/**
* Adds money to the balance of a user
*
* @param name Name of the user
* @param amount The money you want to add
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @param amount The amount of money to be added to the user's account
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)}
*/
@Deprecated
public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
try {
add(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
logger.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e);
public static void add(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
}
public static void add(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
BigDecimal result = getMoneyExact(name).add(amount, MATH_CONTEXT);
setMoney(name, result);
Trade.log("API", "Add", "API", name, new Trade(amount, ess), null, null, null, ess);
add(user, amount);
}
/**
* Substracts money from the balance of a user
* Adds money to the balance of a user
*
* @param uuid UUID of the user
* @param amount The money you want to add
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void add(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
add(user, amount);
}
/**
* Adds money to the balance of a user
*
* @param user User
* @param amount The money you want to add
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)}
*/
public static void add(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
final BigDecimal result = getMoneyExact(user).add(amount, MATH_CONTEXT);
setMoney(user, result);
Trade.log("API", "Add", "API", user.getName(), new Trade(amount, ess), null, null, null, ess);
}
/**
* Subtracts money from the balance of a user
*
* @param name Name of the user
* @param amount The money you want to substract
*
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)}
*/
@Deprecated
public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void subtract(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
try {
substract(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
logger.log(Level.WARNING, "Failed to substract " + amount + " of balance of " + name + ": " + e.getMessage(), e);
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to subtract " + amount + " of balance of " + name + ": " + e.getMessage(), e);
}
}
public static void substract(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT);
/**
* Subtracts money from the balance of a user
*
* @param name Name of the user
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)}
*/
@Deprecated
public static void substract(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
final BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT);
setMoney(name, result);
Trade.log("API", "Subtract", "API", name, new Trade(amount, ess), null, null, null, ess);
}
/**
* Subtracts money from the balance of a user
*
* @param uuid UUID of the user
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void subtract(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
subtract(user, amount);
}
/**
* Subtracts money from the balance of a user
*
* @param user User
* @param amount The money you want to subtract
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void subtract(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
final BigDecimal result = getMoneyExact(user).subtract(amount, MATH_CONTEXT);
setMoney(user, result);
Trade.log("API", "Subtract", "API", user.getName(), new Trade(amount, ess), null, null, null, ess);
}
/**
* Divides the balance of a user by a value
*
* @param name Name of the user
* @param value The balance is divided by this value
*
* @param name Name of the user
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)}
*/
@Deprecated
public static void divide(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void divide(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
try {
divide(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e);
}
}
public static void divide(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
BigDecimal result = getMoneyExact(name).divide(amount, MATH_CONTEXT);
setMoney(name, result);
Trade.log("API", "Divide", "API", name, new Trade(amount, ess), null, null, null, ess);
/**
* Divides the balance of a user by a value
*
* @param name Name of the user
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)}
*/
@Deprecated
public static void divide(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
divide(user, amount);
}
/**
* Divides the balance of a user by a value
*
* @param uuid Name of the user
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void divide(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
divide(user, amount);
}
/**
* Divides the balance of a user by a value
*
* @param user Name of the user
* @param amount The balance is divided by this value
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void divide(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
final BigDecimal result = getMoneyExact(user).divide(amount, MATH_CONTEXT);
setMoney(user, result);
Trade.log("API", "Divide", "API", user.getName(), new Trade(amount, ess), null, null, null, ess);
}
/**
* Multiplies the balance of a user by a value
*
* @param name Name of the user
* @param value The balance is multiplied by this value
*
* @param name Name of the user
* @param amount The balance is multiplied by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)}
*/
@Deprecated
public static void multiply(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void multiply(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
try {
multiply(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e);
}
}
public static void multiply(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
BigDecimal result = getMoneyExact(name).multiply(amount, MATH_CONTEXT);
setMoney(name, result);
Trade.log("API", "Multiply", "API", name, new Trade(amount, ess), null, null, null, ess);
/**
* Multiplies the balance of a user by a value
*
* @param name Name of the user
* @param amount The balance is multiplied by the this value
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)}
*/
@Deprecated
public static void multiply(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
multiply(user, amount);
}
/**
* Multiplies the balance of a user by a value
*
* @param uuid Name of the user
* @param amount The balance is multiplied by the this value
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void multiply(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
multiply(user, amount);
}
/**
* Multiplies the balance of a user by a value
*
* @param user Name of the user
* @param amount The balance is multiplied by the this value
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
*/
public static void multiply(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
final BigDecimal result = getMoneyExact(user).multiply(amount, MATH_CONTEXT);
setMoney(user, result);
Trade.log("API", "Multiply", "API", user.getName(), new Trade(amount, ess), null, null, null, ess);
}
/**
* Resets the balance of a user to the starting balance
*
* @param name Name of the user
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @deprecated Usernames can change, use {@link Economy#resetBalance(UUID)} or {@link Economy#resetBalance(User)}
*/
public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException {
@Deprecated
public static void resetBalance(final String name) throws UserDoesNotExistException, NoLoanPermittedException {
if (ess == null) {
throw new RuntimeException(noCallBeforeLoad);
}
@@ -239,102 +539,291 @@ public class Economy {
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* Resets the balance of a user to the starting balance
*
* @return true, if the user has more or an equal amount of money
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @param uuid UUID of the user
* @throws UserDoesNotExistException If a user by that UUID does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
@Deprecated
public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException {
try {
return hasEnough(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e);
return false;
public static void resetBalance(final UUID uuid) throws NoLoanPermittedException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
resetBalance(user);
}
public static boolean hasEnough(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
return amount.compareTo(getMoneyExact(name)) <= 0;
/**
* Resets the balance of a user to the starting balance
*
* @param user User
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void resetBalance(final User user) throws NoLoanPermittedException {
if (ess == null) {
throw new RuntimeException(noCallBeforeLoad);
}
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
setMoney(user, ess.getSettings().getStartingBalance());
Trade.log("API", "Reset", "API", user.getName(), new Trade(BigDecimal.ZERO, ess), null, null, null, ess);
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
*
* @return true, if the user has more money
*
* @return true, if the user has more or an equal amount of money
* @throws UserDoesNotExistException If a user by that name does not exists
* @deprecated Use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)}
*/
@Deprecated
public static boolean hasMore(String name, double amount) throws UserDoesNotExistException {
public static boolean hasEnough(final String name, final double amount) throws UserDoesNotExistException {
try {
return hasMore(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
return hasEnough(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e);
return false;
}
}
public static boolean hasMore(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
return amount.compareTo(getMoneyExact(name)) < 0;
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more or an equal amount of money
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)}
*/
public static boolean hasEnough(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return hasEnough(user, amount);
}
/**
* @param uuid UUID of the user
* @param amount The amount of money the user should have
* @return true, if the user has more or an equal amount of money
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws ArithmeticException
*/
public static boolean hasEnough(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
return hasEnough(user, amount);
}
/**
* @param user User
* @param amount The amount of money the user should have
* @return true, if the user has more or an equal amount of money
* @throws ArithmeticException
*/
public static boolean hasEnough(final User user, final BigDecimal amount) throws ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
return amount.compareTo(getMoneyExact(user)) <= 0;
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws UserDoesNotExistException If a user by that name does not exists
* @deprecated Use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)}
*/
@Deprecated
public static boolean hasMore(final String name, final double amount) throws UserDoesNotExistException {
try {
return hasMore(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e);
return false;
}
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)}
*/
@Deprecated
public static boolean hasMore(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return hasMore(user, amount);
}
/**
* @param uuid UUID of the user
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws UserDoesNotExistException If a user by that UUID does not exists
* @throws ArithmeticException
*/
public static boolean hasMore(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
return hasMore(user, amount);
}
/**
* @param user User
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws ArithmeticException
*/
public static boolean hasMore(final User user, final BigDecimal amount) throws ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
return amount.compareTo(getMoneyExact(user)) < 0;
}
/**
* @param name Name of the user
* @param amount The amount of money the user should not have
*
* @return true, if the user has less money
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @deprecated Use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)}
*/
@Deprecated
public static boolean hasLess(String name, double amount) throws UserDoesNotExistException {
public static boolean hasLess(final String name, final double amount) throws UserDoesNotExistException {
try {
return hasLess(name, BigDecimal.valueOf(amount));
} catch (ArithmeticException e) {
} catch (final ArithmeticException e) {
logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e);
return false;
}
}
public static boolean hasLess(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
return amount.compareTo(getMoneyExact(name)) > 0;
/**
* @param name Name of the user
* @param amount The amount of money the user should not have
* @return true, if the user has less money
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)}
*/
@Deprecated
public static boolean hasLess(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return hasLess(user, amount);
}
/**
* @param uuid UUID of the user
* @param amount The amount of money the user should not have
* @return true, if the user has less money
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws ArithmeticException
*/
public static boolean hasLess(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
return hasLess(user, amount);
}
/**
* @param user User
* @param amount The amount of money the user should not have
* @return true, if the user has less money
* @throws ArithmeticException
*/
public static boolean hasLess(final User user, final BigDecimal amount) throws ArithmeticException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
return amount.compareTo(getMoneyExact(user)) > 0;
}
/**
* Test if the user has a negative balance
*
* @param name Name of the user
*
* @return true, if the user has a negative balance
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @deprecated Usernames can change, use {@link Economy#isNegative(UUID)} or {@link Economy#isNegative(User)}
*/
public static boolean isNegative(String name) throws UserDoesNotExistException {
return getMoneyExact(name).signum() < 0;
@Deprecated
public static boolean isNegative(final String name) throws UserDoesNotExistException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return isNegative(user);
}
/**
* Test if the user has a negative balance
*
* @param uuid UUID of the user
* @return true, if the user has a negative balance
* @throws UserDoesNotExistException If a user by that UUID does not exists
*/
public static boolean isNegative(final UUID uuid) throws UserDoesNotExistException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
}
return isNegative(user);
}
/**
* Test if the user has a negative balance
*
* @param user User
* @return true, if the user has a negative balance
*/
public static boolean isNegative(final User user) {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
return getMoneyExact(user).signum() < 0;
}
/**
* Formats the amount of money like all other Essentials functions. Example: $100000 or $12345.67
*
* @param amount The amount of money
*
* @return Formatted money
* @deprecated Use {@link #format(BigDecimal)} if your input is already a {@link BigDecimal}.
*/
@Deprecated
public static String format(double amount) {
public static String format(final double amount) {
try {
return format(BigDecimal.valueOf(amount));
} catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
logger.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e);
return "NaN";
}
}
public static String format(BigDecimal amount) {
/**
* Formats the amount of money like all other Essentials functions. Example: $100000 or $12345.67
*
* @param amount The amount of money
* @return Formatted money
*/
public static String format(final BigDecimal amount) {
if (ess == null) {
throw new RuntimeException(noCallBeforeLoad);
}
@@ -345,24 +834,33 @@ public class Economy {
* Test if a player exists to avoid the UserDoesNotExistException
*
* @param name Name of the user
* @return true, if the user exists
* @deprecated Essentials is moving away from username based economy methods. This may be removed in the future.
*/
@Deprecated
public static boolean playerExists(final String name) {
return getUserByName(name) != null;
}
/**
* Test if a player exists to avoid the UserDoesNotExistException
*
* @param uuid UUID of the user
* @return true, if the user exists
*/
public static boolean playerExists(String name) {
return getUserByName(name) != null;
public static boolean playerExists(final UUID uuid) {
return getUserByUUID(uuid) != null;
}
/**
* Test if a player is a npc
*
* @param name Name of the player
*
* @return true, if it's a npc
*
* @throws UserDoesNotExistException
*/
public static boolean isNPC(String name) throws UserDoesNotExistException {
User user = getUserByName(name);
public static boolean isNPC(final String name) throws UserDoesNotExistException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
@@ -373,11 +871,10 @@ public class Economy {
* Creates dummy files for a npc, if there is no player yet with that name.
*
* @param name Name of the player
*
* @return true, if a new npc was created
*/
public static boolean createNPC(String name) {
User user = getUserByName(name);
public static boolean createNPC(final String name) {
final User user = getUserByName(name);
if (user == null) {
createNPCFile(name);
return true;
@@ -389,11 +886,10 @@ public class Economy {
* Deletes a user, if it is marked as npc.
*
* @param name Name of the player
*
* @throws UserDoesNotExistException
*/
public static void removeNPC(String name) throws UserDoesNotExistException {
User user = getUserByName(name);
public static void removeNPC(final String name) throws UserDoesNotExistException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
@@ -0,0 +1,126 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Trade;
import net.ess3.api.IUser;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.concurrent.CompletableFuture;
/**
* Manages EssentialsX's teleport functionality for a player.
* Use this if you want to access EssentialsX's async/safe teleport functionality and teleport warmups and cooldowns.
*/
public interface IAsyncTeleport {
/**
* Used to skip teleportPlayer delay when teleporting someone to a location or player.
*
* @param loc - Where should the player end up
* @param cooldown - If cooldown should be enforced
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Used to skip teleportPlayer delay when teleporting someone to a location or player.
*
* @param entity - Where should the player end up
* @param cooldown - If cooldown should be enforced
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport a player to a specific location
*
* @param loc - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause.
* @param future - Future which is completed with the success status of the execution
*/
void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport a player to a specific player
*
* @param entity - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport a player to a specific location
*
* @param otherUser - Which user will be teleported
* @param loc - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport a player to a specific player
*
* @param otherUser - Which user will be teleported
* @param entity - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport wrapper used to handle tp fallback on /jail and /home
*
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport wrapper used to handle /warp teleports
*
* @param otherUser - Which user will be teleported
* @param warp - The name of the warp the user will be teleported too.
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
* @param future - Future which is completed with the success status of the execution
*/
void warp(IUser otherUser, String warp, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture<Boolean> future);
/**
* Teleport wrapper used to handle /back teleports
*
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param future - Future which is completed with the success status of the execution
*/
void back(Trade chargeFor, CompletableFuture<Boolean> future);
/**
* Teleport wrapper used to handle /back teleports that
* are executed by a different player with this
* instance of teleport as a target.
*
* @param teleporter - The user performing the /back command.
* This value may be {@code null} to indicate console.
* @param chargeFor - What the {@code teleporter} will be charged if teleportPlayer is successful
* @param future - Future which is completed with the success status of the execution
*/
void back(IUser teleporter, Trade chargeFor, CompletableFuture<Boolean> future);
/**
* Teleport wrapper used to handle throwing user home after a jail sentence
*
* @param future - Future which is completed with the success status of the execution
*/
void back(CompletableFuture<Boolean> future);
}
@@ -1,8 +1,16 @@
package com.earth2me.essentials.api;
import org.bukkit.entity.Player;
import java.util.Locale;
/**
* Provides access to the current locale in use.
*
* @deprecated External plugins should prefer to use either the player's client language ({@link Player#getLocale()} or
* {@link net.ess3.api.II18n} in case of future additions.
*/
@Deprecated
public interface II18n {
/**
* Gets the current locale setting
@@ -1,24 +1,171 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
/**
* Provides access to the current item alias registry.
*
* @deprecated External plugins should use {@link net.ess3.api.IItemDb} instead, which includes access to {@link net.ess3.api.IItemDb.ItemResolver}
* APIs.
*/
@Deprecated
public interface IItemDb {
ItemStack get(final String name, final int quantity) throws Exception;
/**
* Create a stack from the given name with the given quantity.
*
* @param name Item name to look up in the database
* @param quantity Quantity of the item stack
* @return The requested item stack
* @throws Exception if the item stack cannot be created
*/
default ItemStack get(final String name, final int quantity) throws Exception {
final ItemStack stack = get(name.toLowerCase(Locale.ENGLISH));
stack.setAmount(quantity);
return stack;
}
/**
* Create a stack from the given name with the maximum stack size for that material.
* <p>
* Note that this will always check against resolver functions from other plugins as well.
* To avoid this behaviour, use net.ess3.api.IItemDb#get(String name, boolean useResolvers).
*
* @param name Item name to look up in the database
* @return The requested item stack with the maximum stack size
* @throws Exception if the item stack cannot be created
*/
ItemStack get(final String name) throws Exception;
String names(ItemStack item);
/**
* Get a comma-separated string list of up to 15 aliases for the given stack.
*
* @param item Item stack whose names to find
* @return Comma-separated list of up to 15 item names
*/
default String names(final ItemStack item) {
List<String> nameList = nameList(item);
if (nameList.size() > 15) {
nameList = nameList.subList(0, 14);
}
return StringUtil.joinList(", ", nameList);
}
/**
* Get a List of all aliases for the given item stack.
*
* @param item Item stack whose names to find
* @return List of all names
*/
List<String> nameList(ItemStack item);
/**
* Get the primary name for the given item stack.
*
* @param item Item stack whose name to find
* @return Primary name of the item
*/
String name(ItemStack item);
/**
* Get all stacks in a given User's inventory that matches the given arguments.
*
* @param user The user with the player inventory to search
* @param args Either an item name, or one of the following:
* hand (default), inventory/invent/all, blocks
* @return A List of all matching ItemStacks
* @throws Exception if the given args are invalid or no blocks are found
*/
List<ItemStack> getMatching(User user, String[] args) throws Exception;
/**
* Converts the given {@link ItemStack} to a string representation that can be saved.
* This is typically used for /createkit but can be used by other plugins for various purposes too.
* Note that this will try registered resolvers first - to avoid this, use {@link net.ess3.api.IItemDb#serialize(ItemStack, boolean)} instead.
*
* @param is The stack to serialize
* @return A string representing the given stack
*/
String serialize(ItemStack is);
/**
* Return names recognised by the database, intended for tab-completion.
*
* @return Collection of all item names
*/
Collection<String> listNames();
/**
* Get the material matching the given legacy ID. Used for conversion from item IDs to
* modern names.
*
* @param id Legacy ID of material to find
* @return Updated material
*/
@Deprecated
default Material getFromLegacyId(final int id) {
return getFromLegacy(id, (byte) 0);
}
/**
* Get the legacy ID for the given material.
*
* @param material Material to look up
* @return Legacy ID of given material
* @throws Exception if the ID cannot be looked up
* @deprecated Item IDs are no longer supported.
*/
@Deprecated
int getLegacyId(Material material) throws Exception;
/**
* Convert colon syntax (eg. "13", "1:5") legacy IDs to Material. Used for conversion from
* item IDs to modern names.
*
* @param item Legacy ID in colon syntax.
* @return Material if an appropriate material exists, else null.
*/
default Material getFromLegacy(final String item) {
final String[] split = item.split(":");
if (!NumberUtil.isInt(split[0])) return null;
final int id = Integer.parseInt(split[0]);
byte damage = 0;
if (split.length > 1 && NumberUtil.isInt(split[1])) {
damage = Byte.parseByte(split[1]);
}
return getFromLegacy(id, damage);
}
/**
* Convert legacy ID and damage value to Material. Used for conversion from item IDs to
* modern names.
*
* @param id Legacy ID
* @param damage Damage value
* @return Material
*/
default Material getFromLegacy(final int id, final byte damage) {
return MaterialUtil.convertFromLegacy(id, damage);
}
/**
* Check whether the item database is loaded and ready for use.
*
* @return Whether items have finished loading
*/
boolean isReady();
}
@@ -4,16 +4,20 @@ import net.ess3.api.IUser;
import org.bukkit.Location;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
/**
* Provides access to the storage of jail locations. Maintainers should add methods to <i>this interface</i>.
*
* @deprecated External plugins should use {@link net.ess3.api.IJails} instead of this interface in case future APIs are added.
*/
@Deprecated
public interface IJails extends IReload {
/**
* Gets the location of the jail with the given name
*
* @param jailName The name of the jail
*
* @return the location of the jail
*
* @throws Exception if the jail does not exist
*/
Location getJail(String jailName) throws Exception;
@@ -22,7 +26,6 @@ public interface IJails extends IReload {
* Gets a list of jails by names
*
* @return a list of jails, if there are none the list will be empty
*
* @throws Exception
*/
Collection<String> getList() throws Exception;
@@ -38,7 +41,6 @@ public interface IJails extends IReload {
* Remove the jail with the given name
*
* @param jail the jail to remove
*
* @throws Exception if the jail does not exist
*/
void removeJail(String jail) throws Exception;
@@ -48,17 +50,27 @@ public interface IJails extends IReload {
*
* @param user the user to send to jail
* @param jail the jail to send the user to
* @throws Exception if the user is offline or jail does not exist
* @deprecated Use {@link IJails#sendToJail(IUser, String, CompletableFuture)}
*/
@Deprecated
void sendToJail(IUser user, String jail) throws Exception;
/**
* Attempts to send the given user to the given jail
*
* @param user the user to send to jail
* @param jail the jail to send the user to
* @param future Future which is completed with the success status of the execution
* @throws Exception if the user is offline or jail does not exist
*/
void sendToJail(IUser user, String jail) throws Exception;
void sendToJail(IUser user, String jail, CompletableFuture<Boolean> future) throws Exception;
/**
* Set a new jail with the given name and location
*
* @param jailName the name of the jail being set
* @param loc the location of the jail being set
*
* @throws Exception
*/
void setJail(String jailName, Location loc) throws Exception;
@@ -1,6 +1,15 @@
package com.earth2me.essentials.api;
/**
* Represents a storage object that is reloadable.
*
* @deprecated This is a remnant of the abandoned 3.x storage system. Neither future 2.x code nor external plugins
* should use this interface.
*/
@Deprecated
public interface IReload {
/**
* Reloads the given storage object.
*/
void onReload();
}
@@ -6,7 +6,9 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
/**
* @deprecated This API is not asynchronous and is no longer maintained. Use {@link com.earth2me.essentials.api.IAsyncTeleport IAsyncTeleport}.
*/
public interface ITeleport {
/**
* Used to skip teleportPlayer delay when teleporting someone to a location or player.
@@ -14,9 +16,9 @@ public interface ITeleport {
* @param loc - Where should the player end up
* @param cooldown - If cooldown should be enforced
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -25,11 +27,18 @@ public interface ITeleport {
* @param entity - Where should the player end up
* @param cooldown - If cooldown should be enforced
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
* Teleport a player to a specific location
*
* @param loc - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @throws Exception
*/
@Deprecated
void teleport(Location loc, Trade chargeFor) throws Exception;
@@ -39,9 +48,9 @@ public interface ITeleport {
* @param loc - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -50,9 +59,9 @@ public interface ITeleport {
* @param entity - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -62,9 +71,9 @@ public interface ITeleport {
* @param loc - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -74,9 +83,9 @@ public interface ITeleport {
* @param entity - Where should the player end up
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -84,9 +93,9 @@ public interface ITeleport {
*
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
@@ -96,25 +105,39 @@ public interface ITeleport {
* @param warp - The name of the warp the user will be teleported too.
* @param chargeFor - What the user will be charged if teleportPlayer is successful
* @param cause - The reported teleportPlayer cause
*
* @throws Exception
*/
@Deprecated
void warp(IUser otherUser, String warp, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
/**
* Teleport wrapper used to handle /back teleports
*
* @param chargeFor - What the user will be charged if teleportPlayer is successful
*
* @throws Exception
*/
@Deprecated
void back(Trade chargeFor) throws Exception;
/**
* Teleport wrapper used to handle /back teleports that
* are executed by a different player with this
* instance of teleport as a target.
*
* @param teleporter - The user performing the /back command.
* This value may be {@code null} to indicate console.
* @param chargeFor - What the {@code teleporter} will be charged if teleportPlayer is successful
* @throws Exception
*/
@Deprecated
void back(IUser teleporter, Trade chargeFor) throws Exception;
/**
* Teleport wrapper used to handle throwing user home after a jail sentence
*
* @throws Exception
*/
@Deprecated
void back() throws Exception;
}
@@ -1,23 +1,28 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.commands.WarpNotFoundException;
import org.bukkit.Location;
import java.io.File;
import java.util.Collection;
import java.util.UUID;
/**
* Provides access to the storage of warp locations. Maintainers should add methods to <i>this interface</i>.
*
* @deprecated External plugins should use {@link net.ess3.api.IWarps} instead of this interface, in case future APIs are added.
*/
@Deprecated
public interface IWarps extends IConf {
/**
* Get a warp by name
*
* @param warp - Warp name
*
* @return - Location the warp is set to
*
* @throws WarpNotFoundException When the warp is not found
* @throws InvalidWorldException When the world the warp is in is not found
* @throws net.ess3.api.InvalidWorldException When the world the warp is in is not found
*/
Location getWarp(String warp) throws WarpNotFoundException, net.ess3.api.InvalidWorldException;
@@ -39,7 +44,6 @@ public interface IWarps extends IConf {
* Delete a warp from the warp DB
*
* @param name - Name of warp
*
* @throws Exception
*/
void removeWarp(String name) throws Exception;
@@ -49,11 +53,28 @@ public interface IWarps extends IConf {
*
* @param name - Name of warp
* @param loc - Location of warp
*
* @throws Exception
*/
void setWarp(String name, Location loc) throws Exception;
/**
* Set a warp
*
* @param user - User of warp
* @param name - Name of warp
* @param loc - Location of warp
* @throws Exception
*/
void setWarp(IUser user, String name, Location loc) throws Exception;
/**
* Gets Lastowner UUID
*
* @param warp - Name of warp
* @throws WarpNotFoundException
*/
UUID getLastOwner(String warp) throws WarpNotFoundException;
/**
* Check to see if the file is empty
*
@@ -62,13 +83,8 @@ public interface IWarps extends IConf {
boolean isEmpty();
/**
* Get a warp file note: this is not yet implemented, as 3.x uses different storage methods
*
* @param name - name of file
*
* @return - an instance of the file
*
* @throws InvalidNameException - When the file is not found
* @deprecated This method relates to the abandoned 3.x storage refactor and is not implemented.
*/
@Deprecated
File getWarpFile(String name) throws net.ess3.api.InvalidNameException;
}
@@ -1,6 +1,9 @@
package com.earth2me.essentials.api;
/**
* @deprecated This exception relates to the abandoned 3.x storage refactor and is not implemented.
*/
@Deprecated
public class InvalidNameException extends Exception {
/**
* NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the
@@ -8,7 +11,7 @@ public class InvalidNameException extends Exception {
*/
private static final long serialVersionUID = 1485321420293663139L;
public InvalidNameException(Throwable thrwbl) {
public InvalidNameException(final Throwable thrwbl) {
super(thrwbl);
}
}
@@ -2,7 +2,10 @@ package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n.tl;
/**
* @deprecated This exception is unused. Use {@link net.ess3.api.InvalidWorldException} instead.
*/
@Deprecated
public class InvalidWorldException extends Exception {
private final String world;
@@ -1,6 +1,8 @@
package com.earth2me.essentials.api;
/**
* Thrown when a user does not have the balance for a transaction and cannot take a loan.
*/
public class NoLoanPermittedException extends net.ess3.api.NoLoanPermittedException {
}
@@ -1,10 +1,18 @@
package com.earth2me.essentials.api;
import java.util.UUID;
import static com.earth2me.essentials.I18n.tl;
/**
* Thrown when the requested user does not exist.
*/
public class UserDoesNotExistException extends Exception {
public UserDoesNotExistException(String name) {
public UserDoesNotExistException(final String name) {
super(tl("userDoesNotExist", name));
}
public UserDoesNotExistException(final UUID uuid) {
super(tl("uuidDoesNotExist", uuid.toString()));
}
}
@@ -2,6 +2,8 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DateUtil;
import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.Server;
import java.util.Collections;
@@ -9,49 +11,48 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandafk extends EssentialsCommand {
public Commandafk() {
super("afk");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length > 0 && user.isAuthorized("essentials.afk.others")) {
User afkUser = user; // if no player found, but message specified, set command executor to target user
String message;
try {
afkUser = getPlayer(server, user, args, 0);
message = args.length > 1 ? getFinalArg(args, 1) : null;
} catch (PlayerNotFoundException e) {
// If only one arg is passed, assume the command executor is targeting another player.
if (args.length == 1) {
throw e;
}
} catch (final PlayerNotFoundException e) {
message = getFinalArg(args, 0);
}
toggleAfk(user, afkUser, message);
} else {
String message = args.length > 0 ? getFinalArg(args, 0) : null;
final String message = args.length > 0 ? getFinalArg(args, 0) : null;
toggleAfk(user, user, message);
}
}
@Override
public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length > 0) {
User afkUser = getPlayer(server, args, 0, true, false);
String message = args.length > 1 ? getFinalArg(args, 1) : null;
final User afkUser = getPlayer(server, args, 0, true, false);
final String message = args.length > 1 ? getFinalArg(args, 1) : null;
toggleAfk(null, afkUser, message);
} else {
throw new NotEnoughArgumentsException();
}
}
private void toggleAfk(User sender, User user, String message) throws Exception {
private void toggleAfk(final User sender, final User user, final String message) throws Exception {
if (message != null && sender != null) {
if (sender.isMuted()) {
throw new Exception(tl("voiceSilenced"));
final String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : null;
if (dateDiff == null) {
throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReason", sender.getMuteReason()) : tl("voiceSilenced"));
}
throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, sender.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
}
if (!sender.isAuthorized("essentials.afk.message")) {
throw new Exception(tl("noPermToAFKMessage"));
@@ -59,40 +60,38 @@ public class Commandafk extends EssentialsCommand {
}
user.setDisplayNick();
String msg = "";
if (!user.toggleAfk()) {
//user.sendMessage(_("markedAsNotAway"));
String selfmsg = "";
if (!user.toggleAfk(AfkStatusChangeEvent.Cause.COMMAND)) {
if (!user.isHidden()) {
msg = tl("userIsNotAway", user.getDisplayName());
selfmsg = tl("userIsNotAwaySelf", user.getDisplayName());
}
user.updateActivity(false);
user.updateActivity(false, AfkStatusChangeEvent.Cause.COMMAND);
} else {
//user.sendMessage(_("markedAsAway"));
if (!user.isHidden()) {
if (message != null) {
msg = tl("userIsAwayWithMessage", user.getDisplayName(), message);
selfmsg = tl("userIsAwaySelfWithMessage", user.getDisplayName(), message);
} else {
msg = tl("userIsAway", user.getDisplayName());
selfmsg = tl("userIsAwaySelf", user.getDisplayName());
}
}
user.setAfkMessage(message);
}
if (!msg.isEmpty()) {
ess.broadcastMessage(user, msg);
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(user, msg, u -> u == user);
}
if (!selfmsg.isEmpty()) {
user.sendMessage(selfmsg);
}
user.setDisplayNick(); // Set this again after toggling
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.afk.others")) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.afk.others", ess)) {
return getPlayers(server, sender);
} else {
return Collections.emptyList();
@@ -0,0 +1,23 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandanvil extends EssentialsCommand {
public Commandanvil() {
super("anvil");
}
@Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand"));
return;
}
ess.getContainerProvider().openAnvil(user.getBase());
}
}
@@ -1,11 +1,14 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandback extends EssentialsCommand {
public Commandback() {
@@ -14,15 +17,70 @@ public class Commandback extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final CommandSource sender = user.getSource();
if (args.length > 0 && user.isAuthorized("essentials.back.others")) {
parseOthers(server, sender, args, commandLabel);
return;
}
teleportBack(sender, user, commandLabel);
}
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
parseOthers(server, sender, args, commandLabel);
}
private void parseOthers(final Server server, final CommandSource sender, final String[] args, final String commandLabel) throws Exception {
final User player = getPlayer(server, args, 0, true, false);
sender.sendMessage(tl("backOther", player.getName()));
teleportBack(sender, player, commandLabel);
}
private void teleportBack(final CommandSource sender, final User user, final String commandLabel) throws Exception {
if (user.getLastLocation() == null) {
throw new Exception(tl("noLocationFound"));
}
if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getLastLocation().getWorld().getName())) {
throw new Exception(tl("noPerm", "essentials.worlds." + user.getLastLocation().getWorld().getName()));
final String lastWorldName = user.getLastLocation().getWorld().getName();
User requester = null;
if (sender.isPlayer()) {
requester = ess.getUser(sender.getPlayer());
if (user.getWorld() != user.getLastLocation().getWorld() && this.ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.worlds." + lastWorldName));
}
if (!requester.isAuthorized("essentials.back.into." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.back.into." + lastWorldName));
}
}
if (requester == null) {
user.getAsyncTeleport().back(null, null, getNewExceptionFuture(sender, commandLabel));
} else if (!requester.equals(user)) {
final Trade charge = new Trade(this.getName(), this.ess);
charge.isAffordableFor(requester);
user.getAsyncTeleport().back(requester, charge, getNewExceptionFuture(sender, commandLabel));
} else {
final Trade charge = new Trade(this.getName(), this.ess);
charge.isAffordableFor(user);
user.getAsyncTeleport().back(charge, getNewExceptionFuture(sender, commandLabel));
}
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getTeleport().back(charge);
throw new NoChargeException();
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (user.isAuthorized("essentials.back.others") && args.length == 1) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
}
}
@@ -6,7 +6,6 @@ import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbackup extends EssentialsCommand {
public Commandbackup() {
super("backup");
@@ -5,13 +5,11 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbalance extends EssentialsCommand {
public Commandbalance() {
super("balance");
@@ -19,11 +17,11 @@ public class Commandbalance extends EssentialsCommand {
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
User target = getPlayer(server, args, 0, true, true);
final User target = getPlayer(server, args, 0, false, true);
sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
}
@@ -31,28 +29,17 @@ public class Commandbalance extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 1 && user.isAuthorized("essentials.balance.others")) {
final User target = getPlayer(server, args, 0, true, true);
final BigDecimal bal = target.getMoney();
user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(bal, ess)));
user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
} else if (args.length < 2) {
final BigDecimal bal = user.getMoney();
user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess)));
user.sendMessage(tl("balance", NumberUtil.displayCurrency(user.getMoney(), ess)));
} else {
throw new NotEnoughArgumentsException();
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.balance.others")) {
return getPlayers(server, user);
} else {
return Collections.emptyList();
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.balance.others", ess)) {
return getPlayers(server, sender);
} else {
return Collections.emptyList();
@@ -10,23 +10,35 @@ import org.bukkit.Server;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.earth2me.essentials.I18n.tl;
public class Commandbalancetop extends EssentialsCommand {
public static final int MINUSERS = 50;
private static final int CACHETIME = 2 * 60 * 1000;
private static final SimpleTextInput cache = new SimpleTextInput();
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static long cacheage = 0;
public Commandbalancetop() {
super("balancetop");
}
private static final int CACHETIME = 2 * 60 * 1000;
public static final int MINUSERS = 50;
private static final SimpleTextInput cache = new SimpleTextInput();
private static long cacheage = 0;
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static void outputCache(final CommandSource sender, final int page) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
sender.sendMessage(tl("balanceTop", format.format(cal.getTime())));
new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender);
}
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
@@ -35,7 +47,7 @@ public class Commandbalancetop extends EssentialsCommand {
if (args.length > 0) {
try {
page = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
} catch (final NumberFormatException ex) {
if (args[0].equalsIgnoreCase("force") && (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force"))) {
force = true;
}
@@ -45,7 +57,7 @@ public class Commandbalancetop extends EssentialsCommand {
if (!force && lock.readLock().tryLock()) {
try {
if (cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page);
outputCache(sender, page);
return;
}
if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
@@ -54,30 +66,33 @@ public class Commandbalancetop extends EssentialsCommand {
} finally {
lock.readLock().unlock();
}
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
} else {
if (ess.getUserMap().getUniqueUsers() > MINUSERS) {
sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers()));
}
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
}
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
}
private static void outputCache(final CommandSource sender, String command, int page) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
sender.sendMessage(tl("balanceTop", format.format(cal.getTime())));
new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender);
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
final List<String> options = Lists.newArrayList("1");
if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force")) {
options.add("force");
}
return options;
} else {
return Collections.emptyList();
}
}
private class Calculator implements Runnable {
private final transient Viewer viewer;
private final boolean force;
public Calculator(final Viewer viewer, final boolean force) {
Calculator(final Viewer viewer, final boolean force) {
this.viewer = viewer;
this.force = force;
}
@@ -88,41 +103,38 @@ public class Commandbalancetop extends EssentialsCommand {
try {
if (force || cacheage <= System.currentTimeMillis() - CACHETIME) {
cache.getLines().clear();
final Map<String, BigDecimal> balances = new HashMap<String, BigDecimal>();
final Map<String, BigDecimal> balances = new HashMap<>();
BigDecimal totalMoney = BigDecimal.ZERO;
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Internal economy functions disabled, aborting baltop.");
}
} else {
for (UUID u : ess.getUserMap().getAllUniqueUsers()) {
for (final UUID u : ess.getUserMap().getAllUniqueUsers()) {
final User user = ess.getUserMap().getUser(u);
if (user != null) {
if (!ess.getSettings().isNpcsInBalanceRanking() && user.isNPC()) {
// Don't list NPCs in output
continue;
}
final BigDecimal userMoney = user.getMoney();
user.updateMoneyCache(userMoney);
totalMoney = totalMoney.add(userMoney);
final String name = user.isHidden() ? user.getName() : user.getDisplayName();
balances.put(name, userMoney);
if (!user.isAuthorized("essentials.balancetop.exclude")) {
final BigDecimal userMoney = user.getMoney();
user.updateMoneyCache(userMoney);
totalMoney = totalMoney.add(userMoney);
final String name = user.isHidden() ? user.getName() : user.getDisplayName();
balances.put(name, userMoney);
}
}
}
}
final List<Map.Entry<String, BigDecimal>> sortedEntries = new ArrayList<Map.Entry<String, BigDecimal>>(balances.entrySet());
Collections.sort(sortedEntries, new Comparator<Map.Entry<String, BigDecimal>>() {
@Override
public int compare(final Entry<String, BigDecimal> entry1, final Entry<String, BigDecimal> entry2) {
return entry2.getValue().compareTo(entry1.getValue());
}
});
final List<Map.Entry<String, BigDecimal>> sortedEntries = new ArrayList<>(balances.entrySet());
sortedEntries.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess)));
int pos = 1;
for (Map.Entry<String, BigDecimal> entry : sortedEntries) {
cache.getLines().add(pos + ". " + entry.getKey() + ", " + NumberUtil.displayCurrency(entry.getValue(), ess));
for (final Map.Entry<String, BigDecimal> entry : sortedEntries) {
cache.getLines().add(tl("balanceTopLine", pos, entry.getKey(), NumberUtil.displayCurrency(entry.getValue(), ess)));
pos++;
}
cacheage = System.currentTimeMillis();
@@ -134,14 +146,13 @@ public class Commandbalancetop extends EssentialsCommand {
}
}
private class Viewer implements Runnable {
private final transient CommandSource sender;
private final transient int page;
private final transient boolean force;
private final transient String commandLabel;
public Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) {
Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) {
this.sender = sender;
this.page = page;
this.force = force;
@@ -153,7 +164,7 @@ public class Commandbalancetop extends EssentialsCommand {
lock.readLock().lock();
try {
if (!force && cacheage > System.currentTimeMillis() - CACHETIME) {
outputCache(sender, commandLabel, page);
outputCache(sender, page);
return;
}
} finally {
@@ -162,17 +173,4 @@ public class Commandbalancetop extends EssentialsCommand {
ess.runTaskAsynchronously(new Calculator(new Viewer(sender, commandLabel, page, false), force));
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) {
List<String> options = Lists.newArrayList("1");
if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force")) {
options.add("force");
}
return options;
} else {
return Collections.emptyList();
}
}
}
@@ -14,7 +14,6 @@ import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Commandban extends EssentialsCommand {
public Commandban() {
super("ban");
@@ -29,7 +28,7 @@ public class Commandban extends EssentialsCommand {
User user;
try {
user = getPlayer(server, args, 0, true, true);
} catch (PlayerNotFoundException e) {
} catch (final PlayerNotFoundException e) {
nomatch = true;
user = ess.getUser(new OfflinePlayer(args[0], ess.getServer()));
}
@@ -37,14 +36,12 @@ public class Commandban extends EssentialsCommand {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline")) {
throw new Exception(tl("banExemptOffline"));
}
} else {
if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) {
throw new Exception(tl("banExempt"));
}
} else if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) {
throw new Exception(tl("banExempt"));
}
final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME;
String banReason;
final String banReason;
if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else {
@@ -53,7 +50,7 @@ public class Commandban extends EssentialsCommand {
ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName);
String banDisplay = tl("banFormat", banReason, senderName);
final String banDisplay = tl("banFormat", banReason, senderName);
user.getBase().kickPlayer(banDisplay);
server.getLogger().log(Level.INFO, tl("playerBanned", senderName, user.getName(), banDisplay));
@@ -66,7 +63,7 @@ public class Commandban extends EssentialsCommand {
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return getPlayers(server, sender);
} else {
@@ -6,6 +6,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.BanList;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@@ -13,8 +14,6 @@ import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
//TODO: Add kick to online players matching ip ban.
public class Commandbanip extends EssentialsCommand {
public Commandbanip() {
super("banip");
@@ -33,9 +32,9 @@ public class Commandbanip extends EssentialsCommand {
ipAddress = args[0];
} else {
try {
User player = getPlayer(server, args, 0, true, true);
final User player = getPlayer(server, args, 0, true, true);
ipAddress = player.getLastLoginAddress();
} catch (PlayerNotFoundException ex) {
} catch (final PlayerNotFoundException ex) {
ipAddress = args[0];
}
}
@@ -44,21 +43,29 @@ public class Commandbanip extends EssentialsCommand {
throw new PlayerNotFoundException();
}
String banReason;
final String banReason;
if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else {
banReason = tl("defaultBanReason");
}
final String banDisplay = tl("banFormat", banReason, senderName);
ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName);
server.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderName, ipAddress, banReason));
for (final Player player : ess.getServer().getOnlinePlayers()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
player.kickPlayer(banDisplay);
}
}
ess.broadcastMessage("essentials.banip.notify", tl("playerBanIpAddress", senderName, ipAddress, banReason));
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
// TODO: Also list IP addresses?
return getPlayers(server, sender);
@@ -0,0 +1,35 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Mob;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.entity.Entity;
import static com.earth2me.essentials.I18n.tl;
public class Commandbeezooka extends EssentialsCommand {
public Commandbeezooka() {
super("beezooka");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) {
user.sendMessage(tl("unsupportedFeature"));
return;
}
final Entity bee = Mob.BEE.spawn(user.getWorld(), server, user.getBase().getEyeLocation());
bee.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
ess.scheduleSyncDelayedTask(() -> {
final Location loc = bee.getLocation();
bee.remove();
loc.getWorld().createExplosion(loc, 0F);
}, 20);
}
}
@@ -12,7 +12,6 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbigtree extends EssentialsCommand {
public Commandbigtree() {
super("bigtree");
@@ -20,20 +19,24 @@ public class Commandbigtree extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
TreeType tree;
final TreeType tree;
if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) {
tree = TreeType.TALL_REDWOOD;
} else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) {
tree = TreeType.BIG_TREE;
} else if (args.length > 0 && args[0].equalsIgnoreCase("jungle")) {
tree = TreeType.JUNGLE;
} else if (args.length > 0 && args[0].equalsIgnoreCase("darkoak")) {
tree = TreeType.DARK_OAK;
} else {
throw new NotEnoughArgumentsException();
}
final Location loc = LocationUtil.getTarget(user.getBase());
final Location safeLocation = LocationUtil.getSafeDestination(loc);
final boolean success = user.getWorld().generateTree(safeLocation, tree);
final Location loc = LocationUtil.getTarget(user.getBase()).add(0, 1, 0);
if (loc.getBlock().getType().isSolid()) {
throw new Exception(tl("bigTreeFailure"));
}
final boolean success = user.getWorld().generateTree(loc, tree);
if (success) {
user.sendMessage(tl("bigTreeSuccess"));
} else {
@@ -42,9 +45,9 @@ public class Commandbigtree extends EssentialsCommand {
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
return Lists.newArrayList("redwood", "tree", "jungle");
return Lists.newArrayList("redwood", "tree", "jungle", "darkoak");
} else {
return Collections.emptyList();
}
@@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.Server;
@@ -13,19 +14,20 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbook extends EssentialsCommand {
private static final Material WRITABLE_BOOK = EnumUtil.getMaterial("WRITABLE_BOOK", "BOOK_AND_QUILL");
public Commandbook() {
super("book");
}
//TODO: Translate this
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack item = user.getItemInHand();
final String player = user.getName();
if (item.getType() == Material.WRITTEN_BOOK) {
BookMeta bmeta = (BookMeta) item.getItemMeta();
final BookMeta bmeta = (BookMeta) item.getItemMeta();
if (args.length > 1 && args[0].equalsIgnoreCase("author")) {
if (user.isAuthorized("essentials.book.author") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) {
@@ -45,7 +47,7 @@ public class Commandbook extends EssentialsCommand {
}
} else {
if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) {
ItemStack newItem = new ItemStack(Material.BOOK_AND_QUILL, item.getAmount());
final ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount());
newItem.setItemMeta(bmeta);
InventoryWorkaround.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("editBookContents"));
@@ -53,12 +55,12 @@ public class Commandbook extends EssentialsCommand {
throw new Exception(tl("denyBookEdit"));
}
}
} else if (item.getType() == Material.BOOK_AND_QUILL) {
BookMeta bmeta = (BookMeta) item.getItemMeta();
} else if (item.getType() == WRITABLE_BOOK) {
final BookMeta bmeta = (BookMeta) item.getItemMeta();
if (!user.isAuthorized("essentials.book.author")) {
bmeta.setAuthor(player);
}
ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount());
final ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount());
newItem.setItemMeta(bmeta);
InventoryWorkaround.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("bookLocked"));
@@ -67,16 +69,16 @@ public class Commandbook extends EssentialsCommand {
}
}
private boolean isAuthor(BookMeta bmeta, String player) {
String author = bmeta.getAuthor();
private boolean isAuthor(final BookMeta bmeta, final String player) {
final String author = bmeta.getAuthor();
return author != null && author.equalsIgnoreCase(player);
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
// Right now, we aren't testing what's held in the player's hand - we could, but it's not necessarily worth it
if (args.length == 1) {
List<String> options = Lists.newArrayList("sign", "unsign"); // sign and unsign aren't real, but work
final List<String> options = Lists.newArrayList("sign", "unsign"); // sign and unsign aren't real, but work
if (user.isAuthorized("essentials.book.author")) {
options.add("author");
}
@@ -85,7 +87,7 @@ public class Commandbook extends EssentialsCommand {
}
return options;
} else if (args.length == 2 && args[0].equalsIgnoreCase("author") && user.isAuthorized("essentials.book.author")) {
List<String> options = getPlayers(server, user);
final List<String> options = getPlayers(server, user);
options.add("Herobrine"); // #EasterEgg
return options;
} else {
@@ -6,11 +6,8 @@ import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandbreak extends EssentialsCommand {
public Commandbreak() {
super("break");
@@ -19,10 +16,8 @@ public class Commandbreak extends EssentialsCommand {
//TODO: Switch to use util class
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final Block block = user.getBase().getTargetBlock((Set<Material>) null, 20);
if (block == null) {
throw new NoChargeException();
}
final Block block = user.getTargetBlock(20);
if (block.getType() == Material.AIR) {
throw new NoChargeException();
}
@@ -1,33 +1,22 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcast extends EssentialsCommand {
public Commandbroadcast() {
super("broadcast");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
sendBroadcast(user.getDisplayName(), args);
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
sendBroadcast(sender.getSender().getName(), args);
}
private void sendBroadcast(final String name, final String[] args) throws NotEnoughArgumentsException {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), name));
ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), sender.getDisplayName()));
}
}
@@ -1,7 +1,5 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.textreader.IText;
@@ -9,7 +7,6 @@ import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
@@ -18,6 +15,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcastworld extends EssentialsCommand {
@@ -27,7 +25,21 @@ public class Commandbroadcastworld extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
sendBroadcast(user.getWorld().getName(), user.getDisplayName(), getFinalArg(args, 0));
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
World world = user.getWorld();
String message = getFinalArg(args, 0);
if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
final World argWorld = ess.getWorld(args[0]);
if (argWorld != null) {
world = argWorld;
message = getFinalArg(args, 1);
}
}
sendBroadcast(world, user.getDisplayName(), message);
}
@Override
@@ -35,26 +47,30 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (args.length < 2) {
throw new NotEnoughArgumentsException("world");
}
sendBroadcast(args[0], sender.getSender().getName(), getFinalArg(args, 1));
}
private void sendBroadcast(final String worldName, final String name, final String message) throws Exception {
World world = ess.getWorld(worldName);
final World world = ess.getWorld(args[0]);
if (world == null) {
throw new Exception(tl("invalidWorld"));
}
sendBroadcast(world, sender.getSender().getName(), getFinalArg(args, 1));
}
private void sendBroadcast(final World world, final String name, final String message) throws Exception {
if (message.isEmpty()) {
throw new NotEnoughArgumentsException();
}
sendToWorld(world, tl("broadcast", FormatUtil.replaceFormat(message).replace("\\n", "\n"), name));
}
private void sendToWorld(World world, String message) {
private void sendToWorld(final World world, final String message) {
IText broadcast = new SimpleTextInput(message);
final Collection<Player> players = ess.getOnlinePlayers();
for (Player player : players) {
for (final Player player : players) {
if (player.getWorld().equals(world)) {
final User user = ess.getUser(player);
broadcast = new KeywordReplacer(broadcast, new CommandSource(player), ess, false);
for (String messageText : broadcast.getLines()) {
for (final String messageText : broadcast.getLines()) {
user.sendMessage(messageText);
}
}
@@ -62,15 +78,10 @@ public class Commandbroadcastworld extends EssentialsCommand {
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
return Collections.emptyList(); // The argument is only for non-players
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) {
List<String> worlds = Lists.newArrayList();
for (World world : server.getWorlds()) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && (!sender.isPlayer() || ess.getSettings().isAllowWorldInBroadcastworld())) {
final List<String> worlds = Lists.newArrayList();
for (final World world : server.getWorlds()) {
worlds.add(world.getName());
}
return worlds;
@@ -9,7 +9,6 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandburn extends EssentialsCommand {
public Commandburn() {
super("burn");
@@ -21,17 +20,13 @@ public class Commandburn extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
if (args[0].trim().length() < 2) {
throw new NotEnoughArgumentsException();
}
User user = getPlayer(server, sender, args, 0);
final User user = getPlayer(server, sender, args, 0);
user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1])));
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return getPlayers(server, sender);
} else if (args.length == 2) {
@@ -0,0 +1,23 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandcartographytable extends EssentialsCommand {
public Commandcartographytable() {
super("cartographytable");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand"));
return;
}
ess.getContainerProvider().openCartographyTable(user.getBase());
}
}
@@ -1,13 +1,12 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -15,36 +14,39 @@ import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand {
private static final int BASE_AMOUNT = 100000;
private static final int EXTENDED_CAP = 8;
public Commandclearinventory() {
super("clearinventory");
}
private static final int BASE_AMOUNT = 100000;
private static final int EXTENDED_CAP = 8;
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
public void run(final Server server, final User user, final String commandLabel, final 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"));
}
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
parseCommand(server, sender, commandLabel, args, true, true);
}
private void parseCommand(Server server, CommandSource sender, String commandLabel, String[] args, boolean allowOthers, boolean allowAll)
private void parseCommand(final Server server, final CommandSource sender, final String commandLabel, final String[] args, final boolean allowOthers, final boolean allowAll)
throws Exception {
Collection<Player> players = new ArrayList<Player>();
User senderUser = ess.getUser(sender.getPlayer());
Collection<Player> players = new ArrayList<>();
final User senderUser = ess.getUser(sender.getPlayer());
String previousClearCommand = "";
int offset = 0;
if (sender.isPlayer()) {
@@ -67,9 +69,8 @@ public class Commandclearinventory extends EssentialsCommand {
throw new PlayerNotFoundException();
}
// Confirm
String formattedCommand = formatCommand(commandLabel, args);
final String formattedCommand = formatCommand(commandLabel, args);
if (senderUser != null && senderUser.isPromptingClearConfirm()) {
if (!formattedCommand.equals(previousClearCommand)) {
senderUser.setConfirmingClearCommand(formattedCommand);
@@ -78,44 +79,48 @@ public class Commandclearinventory extends EssentialsCommand {
}
}
for (Player player : players) {
for (final Player player : players) {
clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP);
}
}
protected void clearHandler(CommandSource sender, Player player, String[] args, int offset, boolean showExtended) throws Exception {
short data = -1;
int type = -1;
protected void clearHandler(final CommandSource sender, final Player player, final String[] args, final int offset, final boolean showExtended) {
ClearHandlerType type = ClearHandlerType.ALL_EXCEPT_ARMOR;
final Set<Item> items = new HashSet<>();
int amount = -1;
if (args.length > (offset + 1) && NumberUtil.isInt(args[(offset + 1)])) {
amount = Integer.parseInt(args[(offset + 1)]);
if (args.length > (offset + 1) && NumberUtil.isInt(args[offset + 1])) {
amount = Integer.parseInt(args[offset + 1]);
}
if (args.length > offset) {
if (args[offset].equalsIgnoreCase("**")) {
type = -2;
type = ClearHandlerType.ALL_INCLUDING_ARMOR;
} else if (!args[offset].equalsIgnoreCase("*")) {
final String[] split = args[offset].split(":");
final ItemStack item = ess.getItemDb().get(split[0]);
type = item.getTypeId();
if (split.length > 1 && NumberUtil.isInt(split[1])) {
data = Short.parseShort(split[1]);
} else {
data = item.getDurability();
final String[] split = args[offset].split(",");
for (final String item : split) {
final String[] itemParts = item.split(":");
short data;
try {
data = Short.parseShort(itemParts[1]);
} catch (final Exception e) {
data = 0;
}
try {
items.add(new Item(ess.getItemDb().get(itemParts[0]).getType(), data));
} catch (final Exception ignored) {
}
}
type = ClearHandlerType.SPECIFIC_ITEM;
}
}
if (type == -1) // type -1 represents wildcard or all items
{
if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) {
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
}
InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null);
} else if (type == -2) // type -2 represents double wildcard or all items and armor
{
} else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) {
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
}
@@ -123,32 +128,28 @@ public class Commandclearinventory extends EssentialsCommand {
InventoryWorkaround.setItemInOffHand(player, null);
player.getInventory().setArmorContents(null);
} else {
if (data == -1) // data -1 means that all subtypes will be cleared
{
ItemStack stack = new ItemStack(type);
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
for (final Item item : items) {
final ItemStack stack = new ItemStack(item.getMaterial());
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
stack.setDurability(item.getData());
}
player.getInventory().clear(type, data);
} else if (amount == -1) // amount -1 means all items will be cleared
{
ItemStack stack = new ItemStack(type, BASE_AMOUNT, data);
ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
final int removedAmount = (BASE_AMOUNT - removedStack.getAmount());
if (removedAmount > 0 || showExtended) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
} else {
if (amount < 0) {
amount = 1;
}
ItemStack stack = new ItemStack(type, amount, data);
if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
// amount -1 means all items will be cleared
if (amount == -1) {
stack.setAmount(BASE_AMOUNT);
final ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
final int removedAmount = BASE_AMOUNT - removedStack.getAmount() + InventoryWorkaround.clearItemInOffHand(player, stack);
if (removedAmount > 0 || showExtended) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
stack.setAmount(amount < 0 ? 1 : amount);
if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
}
}
}
}
@@ -156,17 +157,17 @@ public class Commandclearinventory extends EssentialsCommand {
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (user.isAuthorized("essentials.clearinventory.others")) {
if (args.length == 1) {
List<String> options = getPlayers(server, user);
final List<String> options = getPlayers(server, user);
if (user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")) {
// Assume that nobody will have the 'all' permission without the 'others' permission
options.add("*");
}
return options;
} else if (args.length == 2) {
List<String> items = new ArrayList<>(getItems());
final List<String> items = new ArrayList<>(getItems());
items.add("*");
items.add("**");
return items;
@@ -175,7 +176,7 @@ public class Commandclearinventory extends EssentialsCommand {
}
} else {
if (args.length == 1) {
List<String> items = new ArrayList<>(getItems());
final List<String> items = new ArrayList<>(getItems());
items.add("*");
items.add("**");
return items;
@@ -186,13 +187,13 @@ public class Commandclearinventory extends EssentialsCommand {
}
@Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
List<String> options = getPlayers(server, sender);
final List<String> options = getPlayers(server, sender);
options.add("*");
return options;
} else if (args.length == 2) {
List<String> items = new ArrayList<>(getItems());
final List<String> items = new ArrayList<>(getItems());
items.add("*");
items.add("**");
return items;
@@ -201,7 +202,29 @@ public class Commandclearinventory extends EssentialsCommand {
}
}
private String formatCommand(String commandLabel, String[] args) {
return "/" + commandLabel + " " + StringUtil.joinList(" ", (Object[]) args);
private String formatCommand(final String commandLabel, final String[] args) {
return "/" + commandLabel + " " + StringUtil.joinList(" ", args);
}
private enum ClearHandlerType {
ALL_EXCEPT_ARMOR, ALL_INCLUDING_ARMOR, SPECIFIC_ITEM
}
private static class Item {
private final Material material;
private final short data;
Item(final Material material, final short data) {
this.material = material;
this.data = data;
}
public Material getMaterial() {
return material;
}
public short getData() {
return data;
}
}
}
@@ -1,11 +1,10 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
public Commandclearinventoryconfirmtoggle() {
@@ -13,7 +12,7 @@ public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
boolean confirmingClear = !user.isPromptingClearConfirm();
if (commandLabel.toLowerCase().endsWith("on")) {
confirmingClear = true;
Loaded 100 of 544 files, more files were not shown because too many files have changed in this diff. Show more