mirror of
https://github.com/EssentialsX/Essentials.git
synced 2026-11-05 01:00:13 -05:00
Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d06fc84e41 | ||
|
|
1cbb6f1617 | ||
|
|
0039f73fb3 | ||
|
|
a865c9ad01 | ||
|
|
8c5d4d83f1 | ||
|
|
53c9265800 | ||
|
|
9b25a25e91 | ||
|
|
a2fdf66de4 | ||
|
|
224e5f129e | ||
|
|
146599ae4b | ||
|
|
4203119e9a | ||
|
|
aefe79bbe7 | ||
|
|
5da1e9a220 | ||
|
|
a0df79cc06 | ||
|
|
32840e68f3 | ||
|
|
4da3f52164 | ||
|
|
cae3c5a03e | ||
|
|
13206b3418 | ||
|
|
c713be8c82 | ||
|
|
a3c67e23c8 | ||
|
|
ffcdd99ad0 | ||
|
|
539700cb21 | ||
|
|
1078b7b5f2 | ||
|
|
f908eee76c | ||
|
|
b95c662ed5 | ||
|
|
a60f280a1c | ||
|
|
8ab5bad988 | ||
|
|
8080abacd6 | ||
|
|
e960078e1a | ||
|
|
f4413633b8 | ||
|
|
5c44877c4c | ||
|
|
36d7907987 | ||
|
|
047f373631 | ||
|
|
72ed86e0dd | ||
|
|
c689b55c4d | ||
|
|
cbee61093e | ||
|
|
df061749dd | ||
|
|
38a9327284 | ||
|
|
307c6c7bf0 | ||
|
|
bdc695c85b | ||
|
|
8c54f37092 | ||
|
|
cc0e9aa84b | ||
|
|
6af054631f | ||
|
|
01a37df700 | ||
|
|
f0dd81ee00 | ||
|
|
27b0cc86de | ||
|
|
ee88abafcf | ||
|
|
a1cf08d6ab | ||
|
|
42e9e105cb | ||
|
|
ec0d6651b0 | ||
|
|
348bb6d0a3 | ||
|
|
64904cdcfd | ||
|
|
69d57b04d9 | ||
|
|
ef659d5f26 | ||
|
|
703c5741bd | ||
|
|
d64c73fc51 | ||
|
|
92abba0f25 | ||
|
|
cc3cd5e89c | ||
|
|
3513d72a7b | ||
|
|
8432e1fc7d | ||
|
|
a46f6fd73d | ||
|
|
897571db7d | ||
|
|
de0a419476 | ||
|
|
6dd73f5247 | ||
|
|
a50cfb3efb | ||
|
|
bbcf2ecce3 | ||
|
|
86ea654a5d | ||
|
|
d2bbbd14fc | ||
|
|
a5398e938c | ||
|
|
7b01bc894d | ||
|
|
2678be90e3 | ||
|
|
781f42fba1 | ||
|
|
481749b119 | ||
|
|
a552b88172 | ||
|
|
801562ac2c | ||
|
|
869d79ae73 | ||
|
|
7153676137 | ||
|
|
d2c1b24e4b | ||
|
|
b3de4276bc | ||
|
|
cb31939a7a | ||
|
|
41e0e64a5f | ||
|
|
a20e96af4e | ||
|
|
cedf363557 | ||
|
|
9bb6d77bdb | ||
|
|
03171616fa | ||
|
|
087a594449 | ||
|
|
c0b78cc3d5 | ||
|
|
b05e4079d9 | ||
|
|
556c990eff | ||
|
|
618f58c3f3 | ||
|
|
a7e71488c6 | ||
|
|
0155bcedb7 | ||
|
|
9ab2fe54fc | ||
|
|
0f1eb9b4f9 | ||
|
|
503e837cfd | ||
|
|
0a98b8f662 | ||
|
|
6e79302908 | ||
|
|
ecf72e27bb | ||
|
|
d1aea7dd35 | ||
|
|
b2a307ec23 | ||
|
|
f0dabdd4b1 |
No files matched your search
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
|
||||
<classpathentry kind="lib" path="lib/bukkit-0.0.1-SNAPSHOT.jar"/>
|
||||
<classpathentry kind="lib" path="lib/craftbukkit-0.0.1-SNAPSHOT.jar"/>
|
||||
<classpathentry kind="lib" path="lib/Permissions3.jar"/>
|
||||
</classpath>
|
||||
@@ -1,13 +0,0 @@
|
||||
# Currently used
|
||||
patreon: 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
|
||||
#ko_fi: # Replace with a single Ko-fi 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
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
name: Help!
|
||||
about: Encountered a problem with EssentialsX? Not sure how to fix it?
|
||||
|
||||
---
|
||||
|
||||
<!-- EssentialsX help guide
|
||||
|
||||
Don't write inside the arrows as they will be hidden when you post your issue.
|
||||
|
||||
Want faster support? Come join our Discord server to get help sooner:
|
||||
https://discord.gg/F7gexAQ
|
||||
|
||||
If you're happy to wait (or you were sent here from Discord), read on:
|
||||
|
||||
1. Fill out the template.
|
||||
This will help us understand what problem you've encountered and help us
|
||||
find a solution.
|
||||
|
||||
2. Check the Common Issues page.
|
||||
Read through the wiki page to see if you've encountered a regular issue:
|
||||
https://essentialsx.github.io/#/Common-Issues
|
||||
|
||||
3. Delete this line and all above lines before posting your issue! -->
|
||||
|
||||
### Information
|
||||
|
||||
Full output of `/ess version`:
|
||||
|
||||
<!-- Replace this with the command output -->
|
||||
|
||||
**Server log:** <!-- Upload `logs/latest.log` to https://gist.github.com/ -->
|
||||
|
||||
**EssentialsX config** <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/ -->
|
||||
|
||||
### Help request
|
||||
|
||||
**Problem**
|
||||
<!-- What problem did you encounter? -->
|
||||
|
||||
**What I have tried**
|
||||
<!-- What have you tried so far? -->
|
||||
|
||||
**Screenshots**
|
||||
<!-- If relevant, include any screenshots here. -->
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
name: Report a bug
|
||||
about: Report an EssentialsX bug. Only use this if you're 100% sure there's something wrong with EssentialsX - otherwise, try "Help!".
|
||||
|
||||
---
|
||||
|
||||
<!-- EssentialsX bug reporting guide
|
||||
|
||||
Don't put anything inside this block, as it won't be included in the issue.
|
||||
|
||||
If you are reporting a bug, please follow the following steps:
|
||||
|
||||
1. Fill out the template in full.
|
||||
Run the commands in the console. Don't just put "latest" as a version,
|
||||
or we will ignore it.
|
||||
|
||||
2. When linking files, do not attach them to the post!
|
||||
Copy and paste any logs into https://gist.github.com/, then paste a
|
||||
link to them in the relevant parts of the template. Avoid using
|
||||
Hastebin or Pastebin, as this makes providing support more difficult.
|
||||
**DO NOT drag files into this box!**
|
||||
|
||||
3. If you are reporting a performance issue, please include a link to a
|
||||
Timings and/or profiler report.
|
||||
|
||||
4. If you are reporting a bug with commands or something else in-game,
|
||||
please include screenshots to help us diagnose the problem.
|
||||
|
||||
5. Make sure not to write between the arrows, as anything there will be
|
||||
hidden.
|
||||
|
||||
6. Delete this line and all above lines before posting your issue! -->
|
||||
|
||||
### Information
|
||||
|
||||
**Full output of `/ess version`**:
|
||||
|
||||
```
|
||||
<!-- Run the command in your console, and copy and paste the whole output here -->
|
||||
```
|
||||
|
||||
**Server log**: <!-- Upload `logs/latest.log` to https://gist.github.com/, replace this with link -->
|
||||
|
||||
**EssentialsX config**: <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/, replace this with link -->
|
||||
|
||||
### Details
|
||||
|
||||
**Description**
|
||||
<!-- Replace this with a brief summary of the bug. -->
|
||||
|
||||
**Steps to reproduce**
|
||||
<!-- Replace this with exactly what you did to cause the bug. -->
|
||||
|
||||
**Expected behavior**
|
||||
<!-- Replace this with what you expected to happen. -->
|
||||
|
||||
**Screenshots**
|
||||
<!-- Replace this with screenshots, if necessary. -->
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
name: Request a feature
|
||||
about: Suggest a feature you want to see in EssentialsX!
|
||||
|
||||
---
|
||||
|
||||
<!-- EssentialsX feature request guide
|
||||
|
||||
Fill out the template. Don't write inside the arrows as they will be hidden
|
||||
when you post your issue.
|
||||
|
||||
Not sure if your feature fits in EssentialsX? Feel free to ask on our Discord
|
||||
server: https://discord.gg/F7gexAQ
|
||||
|
||||
If you have a feature suggestion for EssentialsX, read the following tips:
|
||||
|
||||
1. Fill out the template.
|
||||
This will help us understand what you're requesting and why you want us
|
||||
to add it.
|
||||
|
||||
2. Keep it simple.
|
||||
Make sure it's easy to understand what you're requesting. A good way is
|
||||
to keep it to one request per GitHub issue, as we can then easily track
|
||||
feature requests.
|
||||
|
||||
3. Check whether it has already been asked or added.
|
||||
You can search the issue tracker to see if your feature has already been
|
||||
requested at https://github.com/EssentialsX/Essentials/issues. You can
|
||||
also check the wiki at https://essentialsx.github.io/ to see if the
|
||||
feature was recently added.
|
||||
|
||||
4. Ask yourself: "Does this belong in EssentialsX?"
|
||||
There are lots of features that we reject because most servers won't
|
||||
need or use them. If your feature is very specific or already exists in
|
||||
another plugin, it might not be a good fit for EssentialsX.
|
||||
|
||||
5. Delete this line and all above lines before posting your issue! -->
|
||||
|
||||
### Feature request
|
||||
|
||||
**Feature description**
|
||||
<!-- What feature are you suggesting? -->
|
||||
|
||||
**How the feature is useful**
|
||||
<!-- How is the feature useful to players, server owners and/or developers? -->
|
||||
+46
-17
@@ -1,18 +1,47 @@
|
||||
# IDE files
|
||||
*.classpath
|
||||
*.project
|
||||
*.settings/
|
||||
.idea/
|
||||
*.iml
|
||||
.DS_Store
|
||||
|
||||
# Essentials files
|
||||
/Essentials/userdata
|
||||
/Essentials/config.yml
|
||||
/Essentials/kits.yml
|
||||
/Essentials/userdata/testplayer1.yml
|
||||
/Essentials/usermap.csv
|
||||
|
||||
# Build files
|
||||
target/
|
||||
jars/
|
||||
/BuildAll/nbproject/private/
|
||||
/EssentialsProtect/nbproject/private/
|
||||
/EssentialsChat/nbproject/private/
|
||||
/EssentialsGroupBridge/nbproject/private/
|
||||
/EssentialsGeoIP/nbproject/private/
|
||||
/EssentialsSpawn/nbproject/private/
|
||||
/EssentialsXMPP/nbproject/private/
|
||||
/EssentialsGroupManager/nbproject/private/
|
||||
/BuildAll/build/
|
||||
/EssentialsGroupBridge/dist/
|
||||
/EssentialsGroupBridge/build/
|
||||
/EssentialsGeoIP/dist/
|
||||
/EssentialsGeoIP/build/
|
||||
/EssentialsGroupManager/build/
|
||||
/EssentialsGroupManager/dist/
|
||||
/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
|
||||
/.idea
|
||||
*.iml
|
||||
/EssentialsSigns/nbproject/private/
|
||||
/Essentials2Compat/nbproject/private/
|
||||
/Essentials2Compat/dist/
|
||||
/Essentials2Compat/build/
|
||||
/EssentialsGroupManager/bin
|
||||
/EssentialsGroupManager/.externalToolBuilders
|
||||
/EssentialsGeoIP/build
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>Essentials</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
language: java
|
||||
|
||||
jdk:
|
||||
- openjdk8
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- .buildtools
|
||||
- $HOME/.m2
|
||||
|
||||
before_install:
|
||||
- chmod +x scripts/buildtools.sh
|
||||
- scripts/buildtools.sh
|
||||
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- You may freely edit this file. See commented blocks below for -->
|
||||
<!-- some examples of how to customize the build. -->
|
||||
<!-- (If you delete it and reopen the project it will be recreated.) -->
|
||||
<!-- By default, only the Clean and Build commands use this build script. -->
|
||||
<!-- Commands such as Run, Debug, and Test only use this build script if -->
|
||||
<!-- the Compile on Save feature is turned off for the project. -->
|
||||
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
|
||||
<!-- in the project's Project Properties dialog box.-->
|
||||
<project name="BuildAll" default="default" basedir=".">
|
||||
<description>Builds, tests, and runs the project BuildAll.</description>
|
||||
<import file="nbproject/build-impl.xml"/>
|
||||
<!--
|
||||
|
||||
There exist several targets which are by default empty and which can be
|
||||
used for execution of your tasks. These targets are usually executed
|
||||
before and after some main targets. They are:
|
||||
|
||||
-pre-init: called before initialization of project properties
|
||||
-post-init: called after initialization of project properties
|
||||
-pre-compile: called before javac compilation
|
||||
-post-compile: called after javac compilation
|
||||
-pre-compile-single: called before javac compilation of single file
|
||||
-post-compile-single: called after javac compilation of single file
|
||||
-pre-compile-test: called before javac compilation of JUnit tests
|
||||
-post-compile-test: called after javac compilation of JUnit tests
|
||||
-pre-compile-test-single: called before javac compilation of single JUnit test
|
||||
-post-compile-test-single: called after javac compilation of single JUunit test
|
||||
-pre-jar: called before JAR building
|
||||
-post-jar: called after JAR building
|
||||
-post-clean: called after cleaning build products
|
||||
|
||||
(Targets beginning with '-' are not intended to be called on their own.)
|
||||
|
||||
Example of inserting an obfuscator after compilation could look like this:
|
||||
|
||||
<target name="-post-compile">
|
||||
<obfuscate>
|
||||
<fileset dir="${build.classes.dir}"/>
|
||||
</obfuscate>
|
||||
</target>
|
||||
|
||||
For list of available properties check the imported
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
|
||||
Another way to customize the build is by overriding existing main targets.
|
||||
The targets of interest are:
|
||||
|
||||
-init-macrodef-javac: defines macro for javac compilation
|
||||
-init-macrodef-junit: defines macro for junit execution
|
||||
-init-macrodef-debug: defines macro for class debugging
|
||||
-init-macrodef-java: defines macro for class execution
|
||||
-do-jar-with-manifest: JAR building (if you are using a manifest)
|
||||
-do-jar-without-manifest: JAR building (if you are not using a manifest)
|
||||
run: execution of project
|
||||
-javadoc-build: Javadoc generation
|
||||
test-report: JUnit report generation
|
||||
|
||||
An example of overriding the target for project execution could look like this:
|
||||
|
||||
<target name="run" depends="BuildAll-impl.jar">
|
||||
<exec dir="bin" executable="launcher.exe">
|
||||
<arg file="${dist.jar}"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
Notice that the overridden target depends on the jar target and not only on
|
||||
the compile target as the regular run target does. Again, for a list of available
|
||||
properties which you can use, check the target you are overriding in the
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
-->
|
||||
</project>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
build.xml.data.CRC32=51b33957
|
||||
build.xml.script.CRC32=7a797370
|
||||
build.xml.stylesheet.CRC32=28e38971@1.44.1.45
|
||||
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
|
||||
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
|
||||
nbproject/build-impl.xml.data.CRC32=51b33957
|
||||
nbproject/build-impl.xml.script.CRC32=c5170bed
|
||||
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46
|
||||
@@ -0,0 +1,129 @@
|
||||
annotation.processing.enabled=true
|
||||
annotation.processing.enabled.in.editor=false
|
||||
annotation.processing.run.all.processors=true
|
||||
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
|
||||
application.title=BuildAll
|
||||
application.vendor=
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
|
||||
build.classes.dir=${build.dir}/classes
|
||||
build.classes.excludes=**/*.java,**/*.form
|
||||
# This directory is removed when the project is cleaned:
|
||||
build.dir=build
|
||||
build.generated.dir=${build.dir}/generated
|
||||
build.generated.sources.dir=${build.dir}/generated-sources
|
||||
# Only compile against the classpath explicitly listed here:
|
||||
build.sysclasspath=ignore
|
||||
build.test.classes.dir=${build.dir}/test/classes
|
||||
build.test.results.dir=${build.dir}/test/results
|
||||
# Uncomment to specify the preferred debugger connection transport:
|
||||
#debug.transport=dt_socket
|
||||
debug.classpath=\
|
||||
${run.classpath}
|
||||
debug.test.classpath=\
|
||||
${run.test.classpath}
|
||||
# This directory is removed when the project is cleaned:
|
||||
dist.dir=dist
|
||||
dist.jar=${dist.dir}/BuildAll.jar
|
||||
dist.javadoc.dir=${dist.dir}/javadoc
|
||||
endorsed.classpath=
|
||||
excludes=
|
||||
includes=**
|
||||
jar.compress=true
|
||||
javac.classpath=\
|
||||
${reference.Essentials.jar}:\
|
||||
${reference.EssentialsChat.jar}:\
|
||||
${reference.EssentialsProtect.jar}:\
|
||||
${reference.EssentialsSpawn.jar}:\
|
||||
${reference.EssentialsGeoIP.jar}:\
|
||||
${reference.EssentialsGroupBridge.jar}:\
|
||||
${reference.EssentialsXMPP.jar}:\
|
||||
${reference.EssentialsGroupManager.jar}
|
||||
# Space-separated list of extra javac options
|
||||
javac.compilerargs=
|
||||
javac.deprecation=false
|
||||
javac.processorpath=\
|
||||
${javac.classpath}
|
||||
javac.source=1.6
|
||||
javac.target=1.6
|
||||
javac.test.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}
|
||||
javac.test.processorpath=\
|
||||
${javac.test.classpath}
|
||||
javadoc.additionalparam=
|
||||
javadoc.author=false
|
||||
javadoc.encoding=${source.encoding}
|
||||
javadoc.noindex=false
|
||||
javadoc.nonavbar=false
|
||||
javadoc.notree=false
|
||||
javadoc.private=false
|
||||
javadoc.splitindex=true
|
||||
javadoc.use=true
|
||||
javadoc.version=false
|
||||
javadoc.windowtitle=
|
||||
meta.inf.dir=${src.dir}/META-INF
|
||||
mkdist.disabled=false
|
||||
platform.active=default_platform
|
||||
project.Essentials=../Essentials
|
||||
project.EssentialsChat=../EssentialsChat
|
||||
project.EssentialsGeoIP=../EssentialsGeoIP
|
||||
project.EssentialsGroupBridge=../EssentialsGroupBridge
|
||||
project.EssentialsGroupManager=../EssentialsGroupManager
|
||||
project.EssentialsProtect=../EssentialsProtect
|
||||
project.EssentialsSpawn=../EssentialsSpawn
|
||||
project.EssentialsXMPP=../EssentialsXMPP
|
||||
reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar
|
||||
reference.EssentialsChat.jar=${project.EssentialsChat}/dist/EssentialsChat.jar
|
||||
reference.EssentialsGeoIP.jar=${project.EssentialsGeoIP}/dist/EssentialsGeoIP.jar
|
||||
reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/EssentialsGroupBridge.jar
|
||||
reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar
|
||||
reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/EssentialsProtect.jar
|
||||
reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar
|
||||
reference.EssentialsXMPP.jar=${project.EssentialsXMPP}/dist/EssentialsXMPP.jar
|
||||
run.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}
|
||||
# Space-separated list of JVM arguments used when running the project
|
||||
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
|
||||
# or test-sys-prop.name=value to set system properties for unit tests):
|
||||
run.jvmargs=
|
||||
run.test.classpath=\
|
||||
${javac.test.classpath}:\
|
||||
${build.test.classes.dir}
|
||||
source.encoding=UTF-8
|
||||
src.dir=src
|
||||
test.src.dir=test
|
||||
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
||||
<type>org.netbeans.modules.java.j2seproject</type>
|
||||
<configuration>
|
||||
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
|
||||
<name>BuildAll</name>
|
||||
<source-roots>
|
||||
<root id="src.dir"/>
|
||||
</source-roots>
|
||||
<test-roots>
|
||||
<root id="test.src.dir"/>
|
||||
</test-roots>
|
||||
</data>
|
||||
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
|
||||
<definitions>..\lib\nblibraries.properties</definitions>
|
||||
</libraries>
|
||||
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
|
||||
<reference>
|
||||
<foreign-project>Essentials</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsChat</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsGeoIP</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsGroupBridge</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsGroupManager</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsProtect</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsSpawn</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
<reference>
|
||||
<foreign-project>EssentialsXMPP</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
</references>
|
||||
</configuration>
|
||||
</project>
|
||||
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- You may freely edit this file. See commented blocks below for -->
|
||||
<!-- some examples of how to customize the build. -->
|
||||
<!-- (If you delete it and reopen the project it will be recreated.) -->
|
||||
<!-- By default, only the Clean and Build commands use this build script. -->
|
||||
<!-- Commands such as Run, Debug, and Test only use this build script if -->
|
||||
<!-- the Compile on Save feature is turned off for the project. -->
|
||||
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
|
||||
<!-- in the project's Project Properties dialog box.-->
|
||||
<project name="Essentials" default="default" basedir=".">
|
||||
|
||||
<description>Builds, tests, and runs the project Essentials.</description>
|
||||
<import file="nbproject/build-impl.xml"/>
|
||||
<!--
|
||||
|
||||
There exist several targets which are by default empty and which can be
|
||||
used for execution of your tasks. These targets are usually executed
|
||||
before and after some main targets. They are:
|
||||
|
||||
-pre-init: called before initialization of project properties
|
||||
-post-init: called after initialization of project properties
|
||||
-pre-compile: called before javac compilation
|
||||
-post-compile: called after javac compilation
|
||||
-pre-compile-single: called before javac compilation of single file
|
||||
-post-compile-single: called after javac compilation of single file
|
||||
-pre-compile-test: called before javac compilation of JUnit tests
|
||||
-post-compile-test: called after javac compilation of JUnit tests
|
||||
-pre-compile-test-single: called before javac compilation of single JUnit test
|
||||
-post-compile-test-single: called after javac compilation of single JUunit test
|
||||
-pre-jar: called before JAR building
|
||||
-post-jar: called after JAR building
|
||||
-post-clean: called after cleaning build products
|
||||
|
||||
(Targets beginning with '-' are not intended to be called on their own.)
|
||||
|
||||
Example of inserting an obfuscator after compilation could look like this:
|
||||
|
||||
<target name="-post-compile">
|
||||
<obfuscate>
|
||||
<fileset dir="${build.classes.dir}"/>
|
||||
</obfuscate>
|
||||
</target>
|
||||
|
||||
For list of available properties check the imported
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
|
||||
Another way to customize the build is by overriding existing main targets.
|
||||
The targets of interest are:
|
||||
|
||||
-init-macrodef-javac: defines macro for javac compilation
|
||||
-init-macrodef-junit: defines macro for junit execution
|
||||
-init-macrodef-debug: defines macro for class debugging
|
||||
-init-macrodef-java: defines macro for class execution
|
||||
-do-jar-with-manifest: JAR building (if you are using a manifest)
|
||||
-do-jar-without-manifest: JAR building (if you are not using a manifest)
|
||||
run: execution of project
|
||||
-javadoc-build: Javadoc generation
|
||||
test-report: JUnit report generation
|
||||
|
||||
An example of overriding the target for project execution could look like this:
|
||||
|
||||
<target name="run" depends="Essentials-impl.jar">
|
||||
<exec dir="bin" executable="launcher.exe">
|
||||
<arg file="${dist.jar}"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
Notice that the overridden target depends on the jar target and not only on
|
||||
the compile target as the regular run target does. Again, for a list of available
|
||||
properties which you can use, check the target you are overriding in the
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
-->
|
||||
<!--target name="-post-jar">
|
||||
<jar jarfile="${dist.dir}/Essentials.jar">
|
||||
<zipfileset src="${dist.jar}" excludes="META-INF/*" />
|
||||
<zipfileset src="${dist.dir}/lib/Register.jar" excludes="META-INF/*" />
|
||||
<manifest>
|
||||
<attribute name="Classpath" value="Essentials.jar"/>
|
||||
</manifest>
|
||||
</jar>
|
||||
</target-->
|
||||
</project>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
build.xml.data.CRC32=7d758acf
|
||||
build.xml.script.CRC32=3233ee78
|
||||
build.xml.stylesheet.CRC32=28e38971@1.38.2.45
|
||||
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
|
||||
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
|
||||
nbproject/build-impl.xml.data.CRC32=a830bc14
|
||||
nbproject/build-impl.xml.script.CRC32=a9f8842a
|
||||
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46
|
||||
nbproject/profiler-build-impl.xml.data.CRC32=ab78ce15
|
||||
nbproject/profiler-build-impl.xml.script.CRC32=abda56ed
|
||||
nbproject/profiler-build-impl.xml.stylesheet.CRC32=f10cf54c@1.11.1
|
||||
@@ -0,0 +1,3 @@
|
||||
DoNotUseThreads
|
||||
LongVariable
|
||||
SignatureDeclareThrowsException
|
||||
@@ -0,0 +1,154 @@
|
||||
annotation.processing.enabled=true
|
||||
annotation.processing.enabled.in.editor=false
|
||||
annotation.processing.processors.list=lombok.core.AnnotationProcessor
|
||||
annotation.processing.run.all.processors=false
|
||||
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
|
||||
application.title=Essentials
|
||||
application.vendor=
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
|
||||
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=*
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateImportGroups=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
|
||||
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
|
||||
build.classes.dir=${build.dir}/classes
|
||||
build.classes.excludes=**/*.java,**/*.form
|
||||
# This directory is removed when the project is cleaned:
|
||||
build.dir=build
|
||||
build.generated.dir=${build.dir}/generated
|
||||
build.generated.sources.dir=${build.dir}/generated-sources
|
||||
# Only compile against the classpath explicitly listed here:
|
||||
build.sysclasspath=ignore
|
||||
build.test.classes.dir=${build.dir}/test/classes
|
||||
build.test.results.dir=${build.dir}/test/results
|
||||
# Uncomment to specify the preferred debugger connection transport:
|
||||
#debug.transport=dt_socket
|
||||
debug.classpath=\
|
||||
${run.classpath}
|
||||
debug.test.classpath=\
|
||||
${run.test.classpath}
|
||||
# This directory is removed when the project is cleaned:
|
||||
dist.dir=dist
|
||||
dist.jar=${dist.dir}/Essentials.jar
|
||||
dist.javadoc.dir=${dist.dir}/javadoc
|
||||
endorsed.classpath=
|
||||
excludes=
|
||||
file.reference.BOSEconomy7.jar=../lib/BOSEconomy7.jar
|
||||
file.reference.bPermissions.jar=../lib/bPermissions.jar
|
||||
file.reference.bpermissions2.jar=../lib/bpermissions2.jar
|
||||
file.reference.bukkit.jar=../lib/bukkit.jar
|
||||
file.reference.craftbukkit.jar=../lib/craftbukkit.jar
|
||||
file.reference.iCo4.jar=../lib/iCo4.jar
|
||||
file.reference.iCo5.jar=../lib/iCo5.jar
|
||||
file.reference.iCo6.jar=../lib/iCo6.jar
|
||||
file.reference.lombok.jar=../lib/lombok-0.10.8.jar
|
||||
file.reference.MultiCurrency.jar=../lib/MultiCurrency.jar
|
||||
file.reference.Permissions3.jar=../lib/Permissions3.jar
|
||||
file.reference.PermissionsBukkit-1.2.jar=../lib/PermissionsBukkit-1.2.jar
|
||||
file.reference.PermissionsEx.jar=../lib/PermissionsEx.jar
|
||||
file.reference.Privileges.jar=..\\lib\\Privileges.jar
|
||||
file.reference.Vault.jar=../lib/Vault.jar
|
||||
includes=**
|
||||
jar.archive.disabled=${jnlp.enabled}
|
||||
jar.compress=true
|
||||
jar.index=${jnlp.enabled}
|
||||
javac.classpath=\
|
||||
${file.reference.Permissions3.jar}:\
|
||||
${file.reference.iCo4.jar}:\
|
||||
${file.reference.iCo5.jar}:\
|
||||
${file.reference.iCo6.jar}:\
|
||||
${file.reference.MultiCurrency.jar}:\
|
||||
${file.reference.BOSEconomy7.jar}:\
|
||||
${file.reference.PermissionsEx.jar}:\
|
||||
${file.reference.bPermissions.jar}:\
|
||||
${file.reference.PermissionsBukkit-1.2.jar}:\
|
||||
${file.reference.lombok.jar}:\
|
||||
${reference.EssentialsGroupManager.jar}:\
|
||||
${file.reference.bukkit.jar}:\
|
||||
${file.reference.craftbukkit.jar}:\
|
||||
${file.reference.Vault.jar}:\
|
||||
${file.reference.Privileges.jar}:\
|
||||
${file.reference.bpermissions2.jar}
|
||||
# Space-separated list of extra javac options
|
||||
javac.compilerargs=
|
||||
javac.deprecation=false
|
||||
javac.processorpath=\
|
||||
${javac.classpath}
|
||||
javac.source=1.6
|
||||
javac.target=1.6
|
||||
javac.test.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}:\
|
||||
${libs.junit_4.10.classpath}
|
||||
javac.test.processorpath=\
|
||||
${javac.test.classpath}
|
||||
javadoc.additionalparam=
|
||||
javadoc.author=false
|
||||
javadoc.encoding=${source.encoding}
|
||||
javadoc.noindex=false
|
||||
javadoc.nonavbar=false
|
||||
javadoc.notree=false
|
||||
javadoc.private=false
|
||||
javadoc.reference.PermissionsEx.jar=../lib/PermissionsEx-javadoc.jar
|
||||
javadoc.splitindex=true
|
||||
javadoc.use=true
|
||||
javadoc.version=false
|
||||
javadoc.windowtitle=Essentials Docs.
|
||||
jnlp.codebase.type=no.codebase
|
||||
jnlp.descriptor=application
|
||||
jnlp.enabled=false
|
||||
jnlp.mixed.code=default
|
||||
jnlp.offline-allowed=false
|
||||
jnlp.signed=false
|
||||
jnlp.signing=
|
||||
jnlp.signing.alias=
|
||||
jnlp.signing.keystore=
|
||||
meta.inf.dir=${src.dir}/META-INF
|
||||
mkdist.disabled=true
|
||||
platform.active=default_platform
|
||||
project.EssentialsGroupManager=../EssentialsGroupManager
|
||||
reference.EssentialsGroupManager.jar=../EssentialsGroupManager/dist/EssentialsGroupManager.jar
|
||||
run.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}
|
||||
# Space-separated list of JVM arguments used when running the project
|
||||
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
|
||||
# or test-sys-prop.name=value to set system properties for unit tests):
|
||||
run.jvmargs=-Djline.terminal=jline.UnsupportedTerminal
|
||||
run.test.classpath=\
|
||||
${javac.test.classpath}:\
|
||||
${build.test.classes.dir}
|
||||
source.encoding=UTF-8
|
||||
src.dir=src
|
||||
test.src.dir=test
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
||||
<type>org.netbeans.modules.java.j2seproject</type>
|
||||
<configuration>
|
||||
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
|
||||
<name>Essentials</name>
|
||||
<source-roots>
|
||||
<root id="src.dir"/>
|
||||
</source-roots>
|
||||
<test-roots>
|
||||
<root id="test.src.dir"/>
|
||||
</test-roots>
|
||||
</data>
|
||||
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
|
||||
<definitions>../lib/nblibraries.properties</definitions>
|
||||
</libraries>
|
||||
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
|
||||
<reference>
|
||||
<foreign-project>EssentialsGroupManager</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
</references>
|
||||
</configuration>
|
||||
</project>
|
||||
@@ -1,118 +0,0 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>EssentialsXParent</artifactId>
|
||||
<version>2.17.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>EssentialsX</artifactId>
|
||||
|
||||
<build>
|
||||
<finalName>EssentialsX-${full.version}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<showDeprecation>false</showDeprecation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>io.papermc.lib</pattern>
|
||||
<shadedPattern>com.earth2me.essentials.paperlib</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>net.milkbowl.vault</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.papermc</groupId>
|
||||
<artifactId>paperlib</artifactId>
|
||||
<version>1.0.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>NMSProvider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>UpdatedMetaProvider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>1_8_R1Provider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bukkit</groupId>
|
||||
<artifactId>craftbukkit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>1_8_R2Provider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bukkit</groupId>
|
||||
<artifactId>craftbukkit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>LegacyProvider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>ReflectionProvider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.ess3</groupId>
|
||||
<artifactId>FlattenedProvider</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -1,18 +0,0 @@
|
||||
This is the book file.
|
||||
|
||||
This file format works similar to the info.txt, motd.txt and rules.txt
|
||||
|
||||
Place content in here that you would like to be used by books ingame.
|
||||
|
||||
You can use this content by using the book:<section> meta option in kits or item spawning.
|
||||
|
||||
#Colors
|
||||
Minecraft colors:
|
||||
&0 &&0 &1 &&1 &2 &&2 &3 &&3
|
||||
&4 &&4 &5 &&5 &6 &&6 &7 &&7
|
||||
&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
|
||||
@@ -1,113 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.PluginCommandYamlParser;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.*;
|
||||
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<>();
|
||||
private final transient Map<String, String> disabledList = new HashMap<>();
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public AlternativeCommandsHandler(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) {
|
||||
if (plugin.isEnabled()) {
|
||||
addPlugin(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final void addPlugin(final Plugin plugin) {
|
||||
if (plugin.getDescription().getMain().contains("com.earth2me.essentials")) {
|
||||
return;
|
||||
}
|
||||
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
|
||||
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
|
||||
|
||||
for (Command command : commands) {
|
||||
final PluginCommand pc = (PluginCommand) command;
|
||||
final List<String> labels = new ArrayList<>(pc.getAliases());
|
||||
labels.add(pc.getName());
|
||||
|
||||
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
|
||||
if (reg == null) {
|
||||
reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
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);
|
||||
}
|
||||
boolean found = false;
|
||||
for (PluginCommand pc2 : plugincommands) {
|
||||
if (pc2.getPlugin().equals(plugin)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
plugincommands.add(reg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlugin(final Plugin plugin) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
if (entry.getValue().isEmpty()) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public PluginCommand getAlternative(final String label) {
|
||||
final List<PluginCommand> commands = altcommands.get(label);
|
||||
if (commands == null || commands.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (commands.size() == 1) {
|
||||
return commands.get(0);
|
||||
}
|
||||
// return the first command that is not an alias
|
||||
for (PluginCommand command : commands) {
|
||||
if (command.getName().equalsIgnoreCase(label)) {
|
||||
return command;
|
||||
}
|
||||
}
|
||||
// return the first alias
|
||||
return commands.get(0);
|
||||
}
|
||||
|
||||
public void executed(final String label, final PluginCommand pc) {
|
||||
final String altString = pc.getPlugin().getName() + ":" + pc.getLabel();
|
||||
if (ess.getSettings().isDebug()) {
|
||||
LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + altString);
|
||||
}
|
||||
disabledList.put(label, altString);
|
||||
}
|
||||
|
||||
public Map<String, String> disabledCommands() {
|
||||
return disabledList;
|
||||
}
|
||||
}
|
||||
@@ -1,132 +1,153 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IBackup;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.ISettings;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
import lombok.Cleanup;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
|
||||
public class Backup implements Runnable {
|
||||
private static final Logger LOGGER = Logger.getLogger("Essentials");
|
||||
private transient final Server server;
|
||||
private transient final IEssentials ess;
|
||||
private transient boolean running = false;
|
||||
private transient int taskId = -1;
|
||||
private transient boolean active = false;
|
||||
public class Backup implements Runnable, IBackup
|
||||
{
|
||||
private static final Logger LOGGER = Bukkit.getLogger();
|
||||
private transient final Server server;
|
||||
private transient final IEssentials ess;
|
||||
private transient final AtomicBoolean running = new AtomicBoolean(false);
|
||||
private transient int taskId = -1;
|
||||
private transient final AtomicBoolean active = new AtomicBoolean(false);
|
||||
|
||||
public Backup(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
server = ess.getServer();
|
||||
if (!ess.getOnlinePlayers().isEmpty()) {
|
||||
ess.runTaskAsynchronously(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
startTask();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
public Backup(final IEssentials ess)
|
||||
{
|
||||
this.ess = ess;
|
||||
server = ess.getServer();
|
||||
if (server.getOnlinePlayers().length > 0)
|
||||
{
|
||||
startTask();
|
||||
}
|
||||
}
|
||||
|
||||
public void onPlayerJoin() {
|
||||
startTask();
|
||||
}
|
||||
@Override
|
||||
public final void startTask()
|
||||
{
|
||||
if (running.compareAndSet(false, true))
|
||||
{
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks
|
||||
if (interval < 1200)
|
||||
{
|
||||
running.set(false);
|
||||
return;
|
||||
}
|
||||
taskId = ess.scheduleSyncRepeatingTask(this, interval, interval);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void stopTask() {
|
||||
running = false;
|
||||
if (taskId != -1) {
|
||||
server.getScheduler().cancelTask(taskId);
|
||||
}
|
||||
taskId = -1;
|
||||
}
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
if (!active.compareAndSet(false, true))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
final String command = settings.getData().getGeneral().getBackup().getCommand();
|
||||
if (command == null || command.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
LOGGER.log(Level.INFO, _("backupStarted"));
|
||||
final CommandSender consoleSender = server.getConsoleSender();
|
||||
server.dispatchCommand(consoleSender, "save-all");
|
||||
server.dispatchCommand(consoleSender, "save-off");
|
||||
|
||||
private synchronized void startTask() {
|
||||
if (!running) {
|
||||
final long interval = ess.getSettings().getBackupInterval() * 1200; // minutes -> ticks
|
||||
if (interval < 1200) {
|
||||
return;
|
||||
}
|
||||
taskId = ess.scheduleSyncRepeatingTask(this, interval, interval);
|
||||
running = true;
|
||||
}
|
||||
}
|
||||
ess.scheduleAsyncDelayedTask(new BackupRunner(command));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (active) {
|
||||
return;
|
||||
}
|
||||
active = true;
|
||||
final String command = ess.getSettings().getBackupCommand();
|
||||
if (command == null || "".equals(command)) {
|
||||
return;
|
||||
}
|
||||
if ("save-all".equalsIgnoreCase(command)) {
|
||||
final CommandSender cs = server.getConsoleSender();
|
||||
server.dispatchCommand(cs, "save-all");
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
LOGGER.log(Level.INFO, tl("backupStarted"));
|
||||
final CommandSender cs = server.getConsoleSender();
|
||||
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();
|
||||
}
|
||||
} 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"));
|
||||
}
|
||||
}
|
||||
ess.scheduleSyncDelayedTask(new BackupEnableSaveTask());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
private class BackupRunner implements Runnable
|
||||
{
|
||||
private final transient String command;
|
||||
|
||||
public BackupRunner(final String command)
|
||||
{
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
@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();
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()));
|
||||
try
|
||||
{
|
||||
child.waitFor();
|
||||
String line;
|
||||
do
|
||||
{
|
||||
line = reader.readLine();
|
||||
if (line != null)
|
||||
{
|
||||
LOGGER.log(Level.INFO, line);
|
||||
}
|
||||
}
|
||||
while (line != null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
catch (InterruptedException ex)
|
||||
{
|
||||
LOGGER.log(Level.SEVERE, null, ex);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
LOGGER.log(Level.SEVERE, null, ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ess.scheduleSyncDelayedTask(new EnableSavingRunner());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class EnableSavingRunner implements Runnable
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
server.dispatchCommand(server.getConsoleSender(), "save-on");
|
||||
if (server.getOnlinePlayers().length == 0)
|
||||
{
|
||||
running.set(false);
|
||||
if (taskId != -1)
|
||||
{
|
||||
server.getScheduler().cancelTask(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
active.set(false);
|
||||
LOGGER.log(Level.INFO, _("backupFinished"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
|
||||
public class ChargeException extends Exception {
|
||||
public ChargeException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ChargeException(final String message, final Throwable throwable) {
|
||||
super(message, throwable);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
||||
public class CommandSource {
|
||||
protected CommandSender sender;
|
||||
|
||||
public CommandSource(final CommandSender base) {
|
||||
this.sender = base;
|
||||
}
|
||||
|
||||
public final CommandSender getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public final Player getPlayer() {
|
||||
if (sender instanceof Player) {
|
||||
return (Player) sender;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public final boolean isPlayer() {
|
||||
return (sender instanceof Player);
|
||||
}
|
||||
|
||||
public final CommandSender setSender(final CommandSender base) {
|
||||
return this.sender = base;
|
||||
}
|
||||
|
||||
|
||||
public void sendMessage(String message) {
|
||||
if (!message.isEmpty()) {
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +1,33 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.messaging.IMessageRecipient;
|
||||
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
|
||||
|
||||
import org.bukkit.Server;
|
||||
import com.earth2me.essentials.api.IReplyTo;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
|
||||
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;
|
||||
public final class Console implements IReplyTo
|
||||
{
|
||||
private static Console instance = new Console();
|
||||
private CommandSender replyTo;
|
||||
public final static String NAME = "Console";
|
||||
|
||||
public static Console getInstance() {
|
||||
return instance;
|
||||
}
|
||||
private Console()
|
||||
{
|
||||
}
|
||||
|
||||
static void setInstance(IEssentials ess) { // Called in Essentials#onEnable()
|
||||
instance = new Console(ess);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link Console#getCommandSender()}
|
||||
*/
|
||||
@Deprecated
|
||||
public static CommandSender getCommandSender(Server server) throws Exception {
|
||||
return server.getConsoleSender();
|
||||
}
|
||||
@Override
|
||||
public void setReplyTo(final CommandSender user)
|
||||
{
|
||||
replyTo = user;
|
||||
}
|
||||
|
||||
private Console(IEssentials ess) {
|
||||
this.ess = ess;
|
||||
this.messageRecipient = new SimpleMessageRecipient(ess, this);
|
||||
}
|
||||
@Override
|
||||
public CommandSender getReplyTo()
|
||||
{
|
||||
return replyTo;
|
||||
}
|
||||
|
||||
public CommandSender getCommandSender() {
|
||||
return ess.getServer().getConsoleSender();
|
||||
}
|
||||
|
||||
@Override public String getName() {
|
||||
return Console.NAME;
|
||||
}
|
||||
|
||||
@Override public String getDisplayName() {
|
||||
return Console.NAME;
|
||||
}
|
||||
|
||||
@Override public void sendMessage(String message) {
|
||||
getCommandSender().sendMessage(message);
|
||||
}
|
||||
|
||||
@Override public boolean isReachable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ================================
|
||||
* >> DELEGATE METHODS
|
||||
* ================================ */
|
||||
|
||||
@Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) {
|
||||
return this.messageRecipient.sendMessage(recipient, message);
|
||||
}
|
||||
|
||||
@Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) {
|
||||
return this.messageRecipient.onReceiveMessage(sender, message);
|
||||
}
|
||||
|
||||
@Override public IMessageRecipient getReplyRecipient() {
|
||||
return this.messageRecipient.getReplyRecipient();
|
||||
}
|
||||
|
||||
@Override public void setReplyRecipient(IMessageRecipient recipient) {
|
||||
this.messageRecipient.setReplyRecipient(recipient);
|
||||
}
|
||||
public static Console getConsoleReplyTo()
|
||||
{
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* This utility class is used for converting between the ingame
|
||||
* time in ticks to ingame time as a friendly string.
|
||||
* Note that the time is INGAME.
|
||||
*
|
||||
* http://www.minecraftwiki.net/wiki/Day/night_cycle
|
||||
*
|
||||
* @author Olof Larsson
|
||||
*/
|
||||
public final class DescParseTickFormat
|
||||
{
|
||||
public static final Map<String, Integer> nameToTicks = new LinkedHashMap<String, Integer>();
|
||||
public static final Set<String> resetAliases = new HashSet<String>();
|
||||
public static final int ticksAtMidnight = 18000;
|
||||
public static final int ticksPerDay = 24000;
|
||||
public static final int ticksPerHour = 1000;
|
||||
public static final double ticksPerMinute = 1000d / 60d;
|
||||
public static final double ticksPerSecond = 1000d / 60d / 60d;
|
||||
private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
|
||||
private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mmaa", Locale.ENGLISH);
|
||||
|
||||
static
|
||||
{
|
||||
SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
|
||||
nameToTicks.put("sunrise", 23000);
|
||||
nameToTicks.put("dawn", 23000);
|
||||
|
||||
nameToTicks.put("daystart", 0);
|
||||
nameToTicks.put("day", 0);
|
||||
|
||||
nameToTicks.put("morning", 1000);
|
||||
|
||||
nameToTicks.put("midday", 6000);
|
||||
nameToTicks.put("noon", 6000);
|
||||
|
||||
nameToTicks.put("afternoon", 9000);
|
||||
|
||||
nameToTicks.put("sunset", 12000);
|
||||
nameToTicks.put("dusk", 12000);
|
||||
nameToTicks.put("sundown", 12000);
|
||||
nameToTicks.put("nightfall", 12000);
|
||||
|
||||
nameToTicks.put("nightstart", 14000);
|
||||
nameToTicks.put("night", 14000);
|
||||
|
||||
nameToTicks.put("midnight", 18000);
|
||||
|
||||
resetAliases.add("reset");
|
||||
resetAliases.add("normal");
|
||||
resetAliases.add("default");
|
||||
}
|
||||
|
||||
private DescParseTickFormat()
|
||||
{
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PARSE. From describing String to int
|
||||
// --------------------------------------------
|
||||
public static long parse(String desc) throws NumberFormatException
|
||||
{
|
||||
// Only look at alphanumeric and lowercase and : for 24:00
|
||||
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^A-Za-z0-9:]", "");
|
||||
|
||||
// Detect ticks format
|
||||
try
|
||||
{
|
||||
return parseTicks(desc);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
}
|
||||
|
||||
// Detect 24-hour format
|
||||
try
|
||||
{
|
||||
return parse24(desc);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
}
|
||||
|
||||
// Detect 12-hour format
|
||||
try
|
||||
{
|
||||
return parse12(desc);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
}
|
||||
|
||||
// Detect aliases
|
||||
try
|
||||
{
|
||||
return parseAlias(desc);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
}
|
||||
|
||||
// Well we failed to understand...
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
public static long parseTicks(String desc) throws NumberFormatException
|
||||
{
|
||||
if (!desc.matches("^[0-9]+ti?c?k?s?$"))
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
desc = desc.replaceAll("[^0-9]", "");
|
||||
|
||||
return Long.parseLong(desc) % 24000;
|
||||
}
|
||||
|
||||
public static long parse24(String desc) throws NumberFormatException
|
||||
{
|
||||
if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$"))
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", "");
|
||||
|
||||
if (desc.length() != 4)
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
final int hours = Integer.parseInt(desc.substring(0, 2));
|
||||
final int minutes = Integer.parseInt(desc.substring(2, 4));
|
||||
|
||||
return hoursMinutesToTicks(hours, minutes);
|
||||
}
|
||||
|
||||
public static long parse12(String desc) throws NumberFormatException
|
||||
{
|
||||
if (!desc.matches("^[0-9]{1,2}([^0-9]?[0-9]{2})?(pm|am)$"))
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
int hours = 0;
|
||||
int minutes = 0;
|
||||
|
||||
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", "");
|
||||
|
||||
if (desc.length() > 4)
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
if (desc.length() == 4)
|
||||
{
|
||||
hours += Integer.parseInt(desc.substring(0, 2));
|
||||
minutes += Integer.parseInt(desc.substring(2, 4));
|
||||
}
|
||||
else if (desc.length() == 3)
|
||||
{
|
||||
hours += Integer.parseInt(desc.substring(0, 1));
|
||||
minutes += Integer.parseInt(desc.substring(1, 3));
|
||||
}
|
||||
else if (desc.length() == 2)
|
||||
{
|
||||
hours += Integer.parseInt(desc.substring(0, 2));
|
||||
}
|
||||
else if (desc.length() == 1)
|
||||
{
|
||||
hours += Integer.parseInt(desc.substring(0, 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
if (desc.endsWith("pm") && hours != 12)
|
||||
{
|
||||
hours += 12;
|
||||
}
|
||||
|
||||
if (desc.endsWith("am") && hours == 12)
|
||||
{
|
||||
hours -= 12;
|
||||
}
|
||||
|
||||
return hoursMinutesToTicks(hours, minutes);
|
||||
}
|
||||
|
||||
public static long hoursMinutesToTicks(final int hours, final int minutes)
|
||||
{
|
||||
long ret = ticksAtMidnight;
|
||||
ret += (hours) * ticksPerHour;
|
||||
|
||||
ret += (minutes / 60.0) * ticksPerHour;
|
||||
|
||||
ret %= ticksPerDay;
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static long parseAlias(final String desc) throws NumberFormatException
|
||||
{
|
||||
final Integer ret = nameToTicks.get(desc);
|
||||
if (ret == null)
|
||||
{
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static boolean meansReset(final String desc)
|
||||
{
|
||||
return resetAliases.contains(desc);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// FORMAT. From int to describing String
|
||||
// --------------------------------------------
|
||||
public static String format(final long ticks)
|
||||
{
|
||||
return _("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks));
|
||||
}
|
||||
|
||||
public static String formatTicks(final long ticks)
|
||||
{
|
||||
return (ticks % ticksPerDay) + "ticks";
|
||||
}
|
||||
|
||||
public static String format24(final long ticks)
|
||||
{
|
||||
synchronized (SDFTwentyFour)
|
||||
{
|
||||
return formatDateFormat(ticks, SDFTwentyFour);
|
||||
}
|
||||
}
|
||||
|
||||
public static String format12(final long ticks)
|
||||
{
|
||||
synchronized (SDFTwelve)
|
||||
{
|
||||
return formatDateFormat(ticks, SDFTwelve);
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatDateFormat(final long ticks, final SimpleDateFormat format)
|
||||
{
|
||||
final Date date = ticksToDate(ticks);
|
||||
return format.format(date);
|
||||
}
|
||||
|
||||
public static Date ticksToDate(long ticks)
|
||||
{
|
||||
// Assume the server time starts at 0. It would start on a day.
|
||||
// But we will simulate that the server started with 0 at midnight.
|
||||
ticks = ticks - ticksAtMidnight + ticksPerDay;
|
||||
|
||||
// How many ingame days have passed since the server start?
|
||||
final long days = ticks / ticksPerDay;
|
||||
ticks = ticks - days * ticksPerDay;
|
||||
|
||||
// How many hours on the last day?
|
||||
final long hours = ticks / ticksPerHour;
|
||||
ticks = ticks - hours * ticksPerHour;
|
||||
|
||||
// How many minutes on the last day?
|
||||
final long minutes = (long)Math.floor(ticks / ticksPerMinute);
|
||||
final double dticks = ticks - minutes * ticksPerMinute;
|
||||
|
||||
// How many seconds on the last day?
|
||||
final long seconds = (long)Math.floor(dticks / ticksPerSecond);
|
||||
|
||||
// Now we create an english GMT calendar (We wan't no daylight savings)
|
||||
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
|
||||
cal.setLenient(true);
|
||||
|
||||
// And we set the time to 0! And append the time that passed!
|
||||
cal.set(0, Calendar.JANUARY, 1, 0, 0, 0);
|
||||
cal.add(Calendar.DAY_OF_YEAR, (int)days);
|
||||
cal.add(Calendar.HOUR_OF_DAY, (int)hours);
|
||||
cal.add(Calendar.MINUTE, (int)minutes);
|
||||
cal.add(Calendar.SECOND, (int)seconds + 1); // To solve rounding errors.
|
||||
|
||||
return cal.getTime();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.api.*;
|
||||
import com.earth2me.essentials.perm.Permissions;
|
||||
import com.earth2me.essentials.settings.MoneyHolder;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class Economy implements IEconomy
|
||||
{
|
||||
private final IEssentials ess;
|
||||
private final MoneyHolder npcs;
|
||||
|
||||
public Economy(IEssentials ess)
|
||||
{
|
||||
this.ess = ess;
|
||||
this.npcs = new MoneyHolder(ess);
|
||||
}
|
||||
|
||||
private double getNPCBalance(String name) throws UserDoesNotExistException
|
||||
{
|
||||
npcs.acquireReadLock();
|
||||
try
|
||||
{
|
||||
Map<String, Double> balances = npcs.getData().getBalances();
|
||||
if (balances == null)
|
||||
{
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
Double balance = npcs.getData().getBalances().get(name.toLowerCase(Locale.ENGLISH));
|
||||
if (balance == null)
|
||||
{
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
return balance;
|
||||
}
|
||||
finally
|
||||
{
|
||||
npcs.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void setNPCBalance(String name, double balance, boolean checkExistance) throws UserDoesNotExistException
|
||||
{
|
||||
npcs.acquireWriteLock();
|
||||
try
|
||||
{
|
||||
Map<String, Double> balances = npcs.getData().getBalances();
|
||||
if (balances == null)
|
||||
{
|
||||
balances = new HashMap<String, Double>();
|
||||
npcs.getData().setBalances(balances);
|
||||
}
|
||||
if (checkExistance && !balances.containsKey(name.toLowerCase(Locale.ENGLISH)))
|
||||
{
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
balances.put(name.toLowerCase(Locale.ENGLISH), balance);
|
||||
}
|
||||
finally
|
||||
{
|
||||
npcs.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private double getStartingBalance()
|
||||
{
|
||||
double startingBalance = 0;
|
||||
ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
try
|
||||
{
|
||||
startingBalance = settings.getData().getEconomy().getStartingBalance();
|
||||
}
|
||||
finally
|
||||
{
|
||||
settings.unlock();
|
||||
}
|
||||
return startingBalance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload()
|
||||
{
|
||||
this.npcs.onReload(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getMoney(String name) throws UserDoesNotExistException
|
||||
{
|
||||
IUser user = ess.getUser(name);
|
||||
if (user == null)
|
||||
{
|
||||
return getNPCBalance(name);
|
||||
}
|
||||
return user.getMoney();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMoney(String name, double balance) throws NoLoanPermittedException, UserDoesNotExistException
|
||||
{
|
||||
IUser user = ess.getUser(name);
|
||||
if (user == null)
|
||||
{
|
||||
setNPCBalance(name, balance, true);
|
||||
return;
|
||||
}
|
||||
if (balance < 0.0 && !Permissions.ECO_LOAN.isAuthorized(user))
|
||||
{
|
||||
throw new NoLoanPermittedException();
|
||||
}
|
||||
user.setMoney(balance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetBalance(String name) throws NoLoanPermittedException, UserDoesNotExistException
|
||||
{
|
||||
setMoney(name, getStartingBalance());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format(double amount)
|
||||
{
|
||||
return Util.formatCurrency(amount, ess);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean playerExists(String name)
|
||||
{
|
||||
try
|
||||
{
|
||||
getMoney(name);
|
||||
return true;
|
||||
}
|
||||
catch (UserDoesNotExistException ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNPC(String name) throws UserDoesNotExistException
|
||||
{
|
||||
boolean result = ess.getUser(name) == null;
|
||||
if (result)
|
||||
{
|
||||
getNPCBalance(name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createNPC(String name)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (isNPC(name))
|
||||
{
|
||||
|
||||
setNPCBalance(name, getStartingBalance(), false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (UserDoesNotExistException ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
setNPCBalance(name, getStartingBalance(), false);
|
||||
return true;
|
||||
}
|
||||
catch (UserDoesNotExistException ex1)
|
||||
{
|
||||
//This should never happen!
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeNPC(String name) throws UserDoesNotExistException
|
||||
{
|
||||
npcs.acquireWriteLock();
|
||||
try
|
||||
{
|
||||
Map<String, Double> balances = npcs.getData().getBalances();
|
||||
if (balances == null)
|
||||
{
|
||||
balances = new HashMap<String, Double>();
|
||||
npcs.getData().setBalances(balances);
|
||||
}
|
||||
if (balances.containsKey(name.toLowerCase(Locale.ENGLISH)))
|
||||
{
|
||||
balances.remove(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
npcs.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,289 +1,88 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
|
||||
|
||||
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>();
|
||||
private static boolean isFlat;
|
||||
public final class Enchantments
|
||||
{
|
||||
|
||||
static {
|
||||
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
|
||||
ALIASENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
|
||||
ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL);
|
||||
ALIASENCHANTMENTS.put("sharp", Enchantment.DAMAGE_ALL);
|
||||
ALIASENCHANTMENTS.put("dal", Enchantment.DAMAGE_ALL);
|
||||
private Enchantments()
|
||||
{
|
||||
}
|
||||
|
||||
private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
|
||||
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
|
||||
|
||||
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ALIASENCHANTMENTS.put("baneofarthropod", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ALIASENCHANTMENTS.put("arthropod", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ALIASENCHANTMENTS.put("dar", Enchantment.DAMAGE_ARTHROPODS);
|
||||
static
|
||||
{
|
||||
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
|
||||
ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
|
||||
ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL);
|
||||
ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS);
|
||||
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
|
||||
ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD);
|
||||
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
|
||||
ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED);
|
||||
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
|
||||
ENCHANTMENTS.put("dura", Enchantment.DURABILITY);
|
||||
ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY);
|
||||
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
|
||||
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
|
||||
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
|
||||
ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
|
||||
ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS);
|
||||
ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS);
|
||||
ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
|
||||
ENCHANTMENTS.put("respiration", Enchantment.OXYGEN);
|
||||
ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
|
||||
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
|
||||
ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL);
|
||||
ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
|
||||
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
|
||||
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
|
||||
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
|
||||
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
|
||||
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
|
||||
ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER);
|
||||
ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE);
|
||||
ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE);
|
||||
ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK);
|
||||
ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK);
|
||||
ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE);
|
||||
ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE);
|
||||
}
|
||||
|
||||
public static Enchantment getByName(final String name) {
|
||||
Enchantment enchantment;
|
||||
if (NUMPATTERN.matcher(name).matches()) {
|
||||
enchantment = Enchantment.getById(Integer.parseInt(name));
|
||||
} else {
|
||||
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
|
||||
}
|
||||
if (enchantment == null)
|
||||
{
|
||||
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
return enchantment;
|
||||
}
|
||||
|
||||
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
|
||||
ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD);
|
||||
ALIASENCHANTMENTS.put("du", Enchantment.DAMAGE_UNDEAD);
|
||||
|
||||
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
|
||||
ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED);
|
||||
ALIASENCHANTMENTS.put("minespeed", Enchantment.DIG_SPEED);
|
||||
ALIASENCHANTMENTS.put("cutspeed", Enchantment.DIG_SPEED);
|
||||
ALIASENCHANTMENTS.put("ds", Enchantment.DIG_SPEED);
|
||||
ALIASENCHANTMENTS.put("eff", Enchantment.DIG_SPEED);
|
||||
|
||||
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
|
||||
ALIASENCHANTMENTS.put("dura", Enchantment.DURABILITY);
|
||||
ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY);
|
||||
ALIASENCHANTMENTS.put("d", Enchantment.DURABILITY);
|
||||
|
||||
ENCHANTMENTS.put("thorns", Enchantment.THORNS);
|
||||
ENCHANTMENTS.put("highcrit", Enchantment.THORNS);
|
||||
ALIASENCHANTMENTS.put("thorn", Enchantment.THORNS);
|
||||
ALIASENCHANTMENTS.put("highercrit", Enchantment.THORNS);
|
||||
ALIASENCHANTMENTS.put("t", Enchantment.THORNS);
|
||||
|
||||
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
|
||||
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
|
||||
ALIASENCHANTMENTS.put("meleefire", Enchantment.FIRE_ASPECT);
|
||||
ALIASENCHANTMENTS.put("meleeflame", Enchantment.FIRE_ASPECT);
|
||||
ALIASENCHANTMENTS.put("fa", Enchantment.FIRE_ASPECT);
|
||||
|
||||
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("kback", Enchantment.KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("kb", Enchantment.KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("k", Enchantment.KNOCKBACK);
|
||||
|
||||
ALIASENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
ALIASENCHANTMENTS.put("fort", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
ALIASENCHANTMENTS.put("lbb", Enchantment.LOOT_BONUS_BLOCKS);
|
||||
|
||||
ALIASENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
|
||||
ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS);
|
||||
ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS);
|
||||
ALIASENCHANTMENTS.put("lbm", Enchantment.LOOT_BONUS_MOBS);
|
||||
|
||||
ALIASENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
|
||||
ENCHANTMENTS.put("respiration", Enchantment.OXYGEN);
|
||||
ALIASENCHANTMENTS.put("breathing", Enchantment.OXYGEN);
|
||||
ENCHANTMENTS.put("breath", Enchantment.OXYGEN);
|
||||
ALIASENCHANTMENTS.put("o", Enchantment.OXYGEN);
|
||||
|
||||
ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
ALIASENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
ENCHANTMENTS.put("protect", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
ALIASENCHANTMENTS.put("p", Enchantment.PROTECTION_ENVIRONMENTAL);
|
||||
|
||||
ALIASENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("explosionprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("bprotection", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("bprotect", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ENCHANTMENTS.put("blastprotect", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
ALIASENCHANTMENTS.put("pe", Enchantment.PROTECTION_EXPLOSIONS);
|
||||
|
||||
ALIASENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
|
||||
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
|
||||
ENCHANTMENTS.put("featherfall", Enchantment.PROTECTION_FALL);
|
||||
ALIASENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL);
|
||||
ALIASENCHANTMENTS.put("pfa", Enchantment.PROTECTION_FALL);
|
||||
|
||||
ALIASENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
|
||||
ALIASENCHANTMENTS.put("flameprotection", Enchantment.PROTECTION_FIRE);
|
||||
ENCHANTMENTS.put("fireprotect", Enchantment.PROTECTION_FIRE);
|
||||
ALIASENCHANTMENTS.put("flameprotect", Enchantment.PROTECTION_FIRE);
|
||||
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
|
||||
ALIASENCHANTMENTS.put("flameprot", Enchantment.PROTECTION_FIRE);
|
||||
ALIASENCHANTMENTS.put("pf", Enchantment.PROTECTION_FIRE);
|
||||
|
||||
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
|
||||
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
|
||||
ALIASENCHANTMENTS.put("pp", Enchantment.PROTECTION_PROJECTILE);
|
||||
|
||||
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
|
||||
ALIASENCHANTMENTS.put("softtouch", Enchantment.SILK_TOUCH);
|
||||
ALIASENCHANTMENTS.put("st", Enchantment.SILK_TOUCH);
|
||||
|
||||
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
|
||||
ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER);
|
||||
ALIASENCHANTMENTS.put("watermine", Enchantment.WATER_WORKER);
|
||||
ALIASENCHANTMENTS.put("ww", Enchantment.WATER_WORKER);
|
||||
|
||||
ALIASENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE);
|
||||
ENCHANTMENTS.put("flame", Enchantment.ARROW_FIRE);
|
||||
ENCHANTMENTS.put("flamearrow", Enchantment.ARROW_FIRE);
|
||||
ALIASENCHANTMENTS.put("af", Enchantment.ARROW_FIRE);
|
||||
|
||||
ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE);
|
||||
ENCHANTMENTS.put("power", Enchantment.ARROW_DAMAGE);
|
||||
ALIASENCHANTMENTS.put("arrowpower", Enchantment.ARROW_DAMAGE);
|
||||
ALIASENCHANTMENTS.put("ad", Enchantment.ARROW_DAMAGE);
|
||||
|
||||
ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK);
|
||||
ENCHANTMENTS.put("punch", Enchantment.ARROW_KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("arrowpunch", Enchantment.ARROW_KNOCKBACK);
|
||||
ALIASENCHANTMENTS.put("ak", Enchantment.ARROW_KNOCKBACK);
|
||||
|
||||
ALIASENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE);
|
||||
ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE);
|
||||
ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE);
|
||||
ALIASENCHANTMENTS.put("infinite", Enchantment.ARROW_INFINITE);
|
||||
ALIASENCHANTMENTS.put("unlimited", Enchantment.ARROW_INFINITE);
|
||||
ALIASENCHANTMENTS.put("unlimitedarrows", Enchantment.ARROW_INFINITE);
|
||||
ALIASENCHANTMENTS.put("ai", Enchantment.ARROW_INFINITE);
|
||||
|
||||
ENCHANTMENTS.put("luck", Enchantment.LUCK);
|
||||
ALIASENCHANTMENTS.put("luckofsea", Enchantment.LUCK);
|
||||
ALIASENCHANTMENTS.put("luckofseas", Enchantment.LUCK);
|
||||
ALIASENCHANTMENTS.put("rodluck", Enchantment.LUCK);
|
||||
|
||||
ENCHANTMENTS.put("lure", Enchantment.LURE);
|
||||
ALIASENCHANTMENTS.put("rodlure", Enchantment.LURE);
|
||||
|
||||
// 1.8
|
||||
try {
|
||||
Enchantment depthStrider = Enchantment.getByName("DEPTH_STRIDER");
|
||||
if (depthStrider != null) {
|
||||
ENCHANTMENTS.put("depthstrider", depthStrider);
|
||||
ALIASENCHANTMENTS.put("depth", depthStrider);
|
||||
ALIASENCHANTMENTS.put("strider", depthStrider);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
|
||||
// 1.9
|
||||
try {
|
||||
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");
|
||||
if (mending != null) {
|
||||
ENCHANTMENTS.put("mending", mending);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
|
||||
// 1.11
|
||||
try {
|
||||
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");
|
||||
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");
|
||||
if (sweeping != null) {
|
||||
ENCHANTMENTS.put("sweepingedge", sweeping);
|
||||
ALIASENCHANTMENTS.put("sweepedge", sweeping);
|
||||
ALIASENCHANTMENTS.put("sweeping", sweeping);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
|
||||
|
||||
try { // 1.13
|
||||
Enchantment loyalty = Enchantment.getByName("LOYALTY");
|
||||
if (loyalty != null) {
|
||||
ENCHANTMENTS.put("loyalty", loyalty);
|
||||
ALIASENCHANTMENTS.put("loyal", loyalty);
|
||||
ALIASENCHANTMENTS.put("return", loyalty);
|
||||
}
|
||||
Enchantment impaling = Enchantment.getByName("IMPALING");
|
||||
if (impaling != null) {
|
||||
ENCHANTMENTS.put("impaling", impaling);
|
||||
ALIASENCHANTMENTS.put("impale", impaling);
|
||||
ALIASENCHANTMENTS.put("oceandamage", impaling);
|
||||
ALIASENCHANTMENTS.put("oceandmg", impaling);
|
||||
}
|
||||
Enchantment riptide = Enchantment.getByName("RIPTIDE");
|
||||
if (riptide != null) {
|
||||
ENCHANTMENTS.put("riptide", riptide);
|
||||
ALIASENCHANTMENTS.put("rip", riptide);
|
||||
ALIASENCHANTMENTS.put("tide", riptide);
|
||||
ALIASENCHANTMENTS.put("launch", riptide);
|
||||
}
|
||||
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 (IllegalArgumentException ignored) {}
|
||||
|
||||
|
||||
try { // 1.14
|
||||
Enchantment multishot = Enchantment.getByName("MULTISHOT");
|
||||
if (multishot != null) {
|
||||
ENCHANTMENTS.put("multishot", multishot);
|
||||
ALIASENCHANTMENTS.put("tripleshot", multishot);
|
||||
}
|
||||
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);
|
||||
}
|
||||
Enchantment piercing = Enchantment.getByName("PIERCING");
|
||||
if (piercing != null) {
|
||||
ENCHANTMENTS.put("piercing", piercing);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
|
||||
try {
|
||||
Class<?> namespacedKeyClass = Class.forName("org.bukkit.NamespacedKey");
|
||||
Class<?> enchantmentClass = Class.forName("org.bukkit.enchantments.Enchantment");
|
||||
enchantmentClass.getDeclaredMethod("getByKey", namespacedKeyClass);
|
||||
isFlat = true;
|
||||
} catch (ClassNotFoundException | NoSuchMethodException e) {
|
||||
isFlat = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Enchantment getByName(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));
|
||||
}
|
||||
if (enchantment == null) {
|
||||
enchantment = ALIASENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
return enchantment;
|
||||
}
|
||||
|
||||
public static Set<Entry<String, Enchantment>> entrySet() {
|
||||
return ENCHANTMENTS.entrySet();
|
||||
}
|
||||
|
||||
public static Set<String> keySet() {
|
||||
return ENCHANTMENTS.keySet();
|
||||
}
|
||||
public static Set<Entry<String, Enchantment>> entrySet()
|
||||
{
|
||||
return ENCHANTMENTS.entrySet();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,64 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.EnumUtil;
|
||||
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;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
|
||||
public class EssentialsBlockListener implements Listener {
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public EssentialsBlockListener(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onBlockPlace(final BlockPlaceEvent event) {
|
||||
// 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() == 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());
|
||||
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);
|
||||
spawner.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL) {
|
||||
class UnlimitedItemSpawnTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
user.getBase().getInventory().addItem(is);
|
||||
user.getBase().updateInventory();
|
||||
}
|
||||
}
|
||||
ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.*;
|
||||
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 java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.PluginCommandYamlParser;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
|
||||
public class EssentialsCommandHandler implements ICommandHandler
|
||||
{
|
||||
private final transient ClassLoader classLoader;
|
||||
private final transient String commandPath;
|
||||
private final transient String permissionPrefix;
|
||||
private final transient IEssentialsModule module;
|
||||
private static final transient Logger LOGGER = Bukkit.getLogger();
|
||||
private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<String, List<PluginCommand>>();
|
||||
private final transient Map<String, String> disabledList = new HashMap<String, String>();
|
||||
private final transient Map<String, IEssentialsCommand> commands = new HashMap<String, IEssentialsCommand>();
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentials ess)
|
||||
{
|
||||
this(classLoader, commandPath, permissionPrefix, null, ess);
|
||||
}
|
||||
|
||||
public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module, IEssentials ess)
|
||||
{
|
||||
this.classLoader = classLoader;
|
||||
this.commandPath = commandPath;
|
||||
this.permissionPrefix = permissionPrefix;
|
||||
this.module = module;
|
||||
this.ess = ess;
|
||||
for (Plugin plugin : ess.getServer().getPluginManager().getPlugins())
|
||||
{
|
||||
if (plugin.isEnabled())
|
||||
{
|
||||
addPlugin(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args)
|
||||
{
|
||||
boolean disabled = false;
|
||||
boolean overridden = false;
|
||||
ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
try
|
||||
{
|
||||
disabled = settings.getData().getCommands().isDisabled(command.getName());
|
||||
overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName());
|
||||
}
|
||||
finally
|
||||
{
|
||||
settings.unlock();
|
||||
}
|
||||
// Allow plugins to override the command via onCommand
|
||||
if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName())))
|
||||
{
|
||||
final PluginCommand pc = getAlternative(commandLabel);
|
||||
if (pc != null)
|
||||
{
|
||||
|
||||
executed(commandLabel, pc.getLabel());
|
||||
try
|
||||
{
|
||||
return pc.execute(sender, commandLabel, args);
|
||||
}
|
||||
catch (final Exception ex)
|
||||
{
|
||||
final ArrayList<StackTraceElement> elements = new ArrayList<StackTraceElement>(Arrays.asList(ex.getStackTrace()));
|
||||
elements.remove(0);
|
||||
final ArrayList<StackTraceElement> toRemove = new ArrayList<StackTraceElement>();
|
||||
for (final StackTraceElement e : elements)
|
||||
{
|
||||
if (e.getClassName().equals("com.earth2me.essentials.Essentials"))
|
||||
{
|
||||
toRemove.add(e);
|
||||
}
|
||||
}
|
||||
elements.removeAll(toRemove);
|
||||
final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]);
|
||||
ex.setStackTrace(trace);
|
||||
ex.printStackTrace();
|
||||
sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
IUser user = null;
|
||||
if (sender instanceof Player)
|
||||
{
|
||||
user = ess.getUser((Player)sender);
|
||||
LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)));
|
||||
}
|
||||
|
||||
// Check for disabled commands
|
||||
if (disabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
final String commandName = command.getName().toLowerCase(Locale.ENGLISH);
|
||||
IEssentialsCommand cmd = commands.get(commandName);
|
||||
if (cmd == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance();
|
||||
cmd.init(ess, commandName);
|
||||
cmd.setEssentialsModule(module);
|
||||
commands.put(commandName, cmd);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sender.sendMessage(_("commandNotLoaded", commandName));
|
||||
LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check authorization
|
||||
if (sender != null && cmd.isAuthorized(sender))
|
||||
{
|
||||
LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName()));
|
||||
user.sendMessage(_("noAccessCommand"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Run the command
|
||||
try
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
cmd.run(sender, command, commandLabel, args);
|
||||
}
|
||||
else
|
||||
{
|
||||
user.acquireReadLock();
|
||||
try
|
||||
{
|
||||
cmd.run(user, command, commandLabel, args);
|
||||
}
|
||||
finally
|
||||
{
|
||||
user.unlock();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (NoChargeException ex)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
catch (NotEnoughArgumentsException ex)
|
||||
{
|
||||
sender.sendMessage(command.getDescription());
|
||||
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
|
||||
if (!ex.getMessage().isEmpty())
|
||||
{
|
||||
sender.sendMessage(ex.getMessage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Throwable ex)
|
||||
{
|
||||
showCommandError(sender, commandLabel, ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Throwable ex)
|
||||
{
|
||||
LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception)
|
||||
{
|
||||
sender.sendMessage(_("errorWithMessage", exception.getMessage()));
|
||||
if (ess.getSettings().isDebug())
|
||||
{
|
||||
LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload()
|
||||
{
|
||||
}
|
||||
|
||||
public final void addPlugin(final Plugin plugin)
|
||||
{
|
||||
if (plugin.getDescription().getMain().contains("com.earth2me.essentials"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
|
||||
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
|
||||
|
||||
for (Command command : commands)
|
||||
{
|
||||
final PluginCommand pc = (PluginCommand)command;
|
||||
final List<String> labels = new ArrayList<String>(pc.getAliases());
|
||||
labels.add(pc.getName());
|
||||
|
||||
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
|
||||
if (reg == null)
|
||||
{
|
||||
reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
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<PluginCommand>();
|
||||
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
|
||||
}
|
||||
boolean found = false;
|
||||
for (PluginCommand pc2 : plugincommands)
|
||||
{
|
||||
if (pc2.getPlugin().equals(plugin))
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
{
|
||||
plugincommands.add(reg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlugin(final Plugin plugin)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
if (entry.getValue().isEmpty())
|
||||
{
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public PluginCommand getAlternative(final String label)
|
||||
{
|
||||
final List<PluginCommand> commands = altcommands.get(label);
|
||||
if (commands == null || commands.isEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (commands.size() == 1)
|
||||
{
|
||||
return commands.get(0);
|
||||
}
|
||||
// return the first command that is not an alias
|
||||
for (PluginCommand command : commands)
|
||||
{
|
||||
if (command.getName().equalsIgnoreCase(label))
|
||||
{
|
||||
return command;
|
||||
}
|
||||
}
|
||||
// return the first alias
|
||||
return commands.get(0);
|
||||
}
|
||||
|
||||
public void executed(final String label, final String otherLabel)
|
||||
{
|
||||
if (ess.getSettings().isDebug())
|
||||
{
|
||||
LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel);
|
||||
}
|
||||
disabledList.put(label, otherLabel);
|
||||
}
|
||||
|
||||
public Map<String, String> disabledCommands()
|
||||
{
|
||||
return disabledList;
|
||||
}
|
||||
}
|
||||
@@ -1,661 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.google.common.io.Files;
|
||||
import net.ess3.api.InvalidWorldException;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.MathContext;
|
||||
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.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.logging.Level;
|
||||
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;
|
||||
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
|
||||
private final AtomicInteger pendingDiskWrites = new AtomicInteger(0);
|
||||
private final AtomicBoolean transaction = new AtomicBoolean(false);
|
||||
|
||||
public EssentialsConf(final File configFile) {
|
||||
super();
|
||||
this.configFile = configFile.getAbsoluteFile();
|
||||
}
|
||||
|
||||
private final byte[] bytebuffer = new byte[1024];
|
||||
|
||||
public synchronized void load() {
|
||||
if (pendingDiskWrites.get() != 0) {
|
||||
LOGGER.log(Level.INFO, "File {0} not read, because it''s not yet written to disk.", configFile);
|
||||
return;
|
||||
}
|
||||
if (!configFile.getParentFile().exists()) {
|
||||
if (!configFile.getParentFile().mkdirs()) {
|
||||
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
|
||||
}
|
||||
}
|
||||
// This will delete files where the first character is 0. In most cases they are broken.
|
||||
if (configFile.exists() && configFile.length() != 0) {
|
||||
try {
|
||||
final InputStream input = new FileInputStream(configFile);
|
||||
try {
|
||||
if (input.read() == 0) {
|
||||
input.close();
|
||||
configFile.delete();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
LOGGER.log(Level.SEVERE, null, ex);
|
||||
} finally {
|
||||
try {
|
||||
input.close();
|
||||
} catch (IOException ex) {
|
||||
LOGGER.log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
} catch (FileNotFoundException ex) {
|
||||
LOGGER.log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (!configFile.exists()) {
|
||||
if (legacyFileExists()) {
|
||||
convertLegacyFile();
|
||||
} else if (altFileExists()) {
|
||||
convertAltFile();
|
||||
} else if (templateName != null) {
|
||||
LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString()));
|
||||
createFromTemplate();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
try (FileInputStream inputStream = new FileInputStream(configFile)) {
|
||||
long startSize = configFile.length();
|
||||
if (startSize > Integer.MAX_VALUE) {
|
||||
throw new InvalidConfigurationException("File too big");
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.allocate((int) startSize);
|
||||
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();
|
||||
resize.put(buffer);
|
||||
resize.position(resizePosition);
|
||||
buffer = resize;
|
||||
}
|
||||
buffer.put(bytebuffer, 0, length);
|
||||
}
|
||||
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();
|
||||
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);
|
||||
if (result.isError()) {
|
||||
throw new InvalidConfigurationException("Invalid Characters in file " + configFile.getAbsolutePath());
|
||||
} else {
|
||||
decoder.flush(data);
|
||||
}
|
||||
} else {
|
||||
decoder.flush(data);
|
||||
}
|
||||
final int end = data.position();
|
||||
data.rewind();
|
||||
super.loadFromString(data.subSequence(0, end).toString());
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
|
||||
} catch (InvalidConfigurationException ex) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean legacyFileExists() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void convertLegacyFile() {
|
||||
LOGGER.log(Level.SEVERE, "Unable to import legacy config file.");
|
||||
}
|
||||
|
||||
public boolean altFileExists() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void convertAltFile() {
|
||||
LOGGER.log(Level.SEVERE, "Unable to import alt config file.");
|
||||
}
|
||||
|
||||
private void createFromTemplate() {
|
||||
InputStream istr = null;
|
||||
OutputStream ostr = null;
|
||||
try {
|
||||
istr = resourceClass.getResourceAsStream(templateName);
|
||||
if (istr == null) {
|
||||
LOGGER.log(Level.SEVERE, tl("couldNotFindTemplate", templateName));
|
||||
return;
|
||||
}
|
||||
ostr = new FileOutputStream(configFile);
|
||||
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) {
|
||||
LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex);
|
||||
} finally {
|
||||
try {
|
||||
if (istr != null) {
|
||||
istr.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
try {
|
||||
if (ostr != null) {
|
||||
ostr.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setTemplateName(final String templateName) {
|
||||
this.templateName = templateName;
|
||||
}
|
||||
|
||||
public File getFile() {
|
||||
return configFile;
|
||||
}
|
||||
|
||||
public void setTemplateName(final String templateName, final Class<?> resClass) {
|
||||
this.templateName = templateName;
|
||||
this.resourceClass = resClass;
|
||||
}
|
||||
|
||||
public void startTransaction() {
|
||||
transaction.set(true);
|
||||
}
|
||||
|
||||
public void stopTransaction() {
|
||||
transaction.set(false);
|
||||
save();
|
||||
}
|
||||
|
||||
public void save() {
|
||||
try {
|
||||
save(configFile);
|
||||
} catch (IOException ex) {
|
||||
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void saveWithError() throws IOException {
|
||||
save(configFile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void save(final File file) throws IOException {
|
||||
if (!transaction.get()) {
|
||||
delayedSave(file);
|
||||
}
|
||||
}
|
||||
|
||||
//This may be aborted if there are stagnant requests sitting in queue.
|
||||
//This needs fixed to discard outstanding save requests.
|
||||
public synchronized void forceSave() {
|
||||
try {
|
||||
Future<?> future = delayedSave(configFile);
|
||||
if (future != null) {
|
||||
future.get();
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException ex) {
|
||||
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void cleanup() {
|
||||
forceSave();
|
||||
}
|
||||
|
||||
private Future<?> delayedSave(final File file) {
|
||||
if (file == null) {
|
||||
throw new IllegalArgumentException("File cannot be null");
|
||||
}
|
||||
|
||||
final String data = saveToString();
|
||||
|
||||
if (data.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
pendingDiskWrites.incrementAndGet();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public Location getLocation(final String path, final Server server) throws InvalidWorldException {
|
||||
final String worldString = (path == null ? "" : path + ".") + "world";
|
||||
final String worldName = getString(worldString);
|
||||
if (worldName == null || worldName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
final World world = server.getWorld(worldName);
|
||||
if (world == null) {
|
||||
throw new InvalidWorldException(worldName);
|
||||
}
|
||||
return new Location(world, getDouble((path == null ? "" : path + ".") + "x", 0), getDouble((path == null ? "" : path + ".") + "y", 0), getDouble((path == null ? "" : path + ".") + "z", 0), (float) getDouble((path == null ? "" : path + ".") + "yaw", 0), (float) getDouble((path == null ? "" : path + ".") + "pitch", 0));
|
||||
}
|
||||
|
||||
public void setProperty(final String path, final Location loc) {
|
||||
set((path == null ? "" : path + ".") + "world", loc.getWorld().getName());
|
||||
set((path == null ? "" : path + ".") + "x", loc.getX());
|
||||
set((path == null ? "" : path + ".") + "y", loc.getY());
|
||||
set((path == null ? "" : path + ".") + "z", loc.getZ());
|
||||
set((path == null ? "" : path + ".") + "yaw", loc.getYaw());
|
||||
set((path == null ? "" : path + ".") + "pitch", loc.getPitch());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemStack(final String path) {
|
||||
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)) {
|
||||
final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH));
|
||||
if (enchantment == null) {
|
||||
continue;
|
||||
}
|
||||
final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel());
|
||||
stack.addUnsafeEnchantment(enchantment, level);
|
||||
}
|
||||
}
|
||||
return stack;
|
||||
/*
|
||||
* ,
|
||||
* (byte)getInt(path + ".data", 0)
|
||||
*/
|
||||
}
|
||||
|
||||
public void setProperty(final String path, final ItemStack stack) {
|
||||
final Map<String, Object> map = new HashMap<>();
|
||||
map.put("type", stack.getType().toString());
|
||||
map.put("amount", stack.getAmount());
|
||||
map.put("damage", stack.getDurability());
|
||||
Map<Enchantment, Integer> enchantments = stack.getEnchantments();
|
||||
if (!enchantments.isEmpty()) {
|
||||
Map<String, Integer> enchant = new HashMap<>();
|
||||
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
|
||||
enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue());
|
||||
}
|
||||
map.put("enchant", enchant);
|
||||
}
|
||||
// getData().getData() is broken
|
||||
//map.put("data", stack.getDurability());
|
||||
set(path, map);
|
||||
}
|
||||
|
||||
public void setProperty(String path, List object) {
|
||||
set(path, new ArrayList(object));
|
||||
}
|
||||
|
||||
public void setProperty(String path, Map object) {
|
||||
set(path, new LinkedHashMap(object));
|
||||
}
|
||||
|
||||
public Object getProperty(String path) {
|
||||
return get(path);
|
||||
}
|
||||
|
||||
public void setProperty(final String path, final BigDecimal bigDecimal) {
|
||||
set(path, bigDecimal.toString());
|
||||
}
|
||||
|
||||
public void setProperty(String path, Object object) {
|
||||
set(path, object);
|
||||
}
|
||||
|
||||
public void removeProperty(String path) {
|
||||
set(path, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Object get(String path) {
|
||||
return super.get(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Object get(String path, Object def) {
|
||||
return super.get(path, def);
|
||||
}
|
||||
|
||||
public synchronized BigDecimal getBigDecimal(final String path, final BigDecimal def) {
|
||||
final String input = super.getString(path);
|
||||
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) {
|
||||
return super.getBoolean(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean getBoolean(String path, boolean def) {
|
||||
return super.getBoolean(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Boolean> getBooleanList(String path) {
|
||||
return super.getBooleanList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Byte> getByteList(String path) {
|
||||
return super.getByteList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Character> getCharacterList(String path) {
|
||||
return super.getCharacterList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized ConfigurationSection getConfigurationSection(String path) {
|
||||
return super.getConfigurationSection(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized double getDouble(String path) {
|
||||
return super.getDouble(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized double getDouble(final String path, final double def) {
|
||||
return super.getDouble(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Double> getDoubleList(String path) {
|
||||
return super.getDoubleList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Float> getFloatList(String path) {
|
||||
return super.getFloatList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getInt(String path) {
|
||||
return super.getInt(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getInt(String path, int def) {
|
||||
return super.getInt(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Integer> getIntegerList(String path) {
|
||||
return super.getIntegerList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized ItemStack getItemStack(String path, ItemStack def) {
|
||||
return super.getItemStack(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Set<String> getKeys(boolean deep) {
|
||||
return super.getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<?> getList(String path) {
|
||||
return super.getList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<?> getList(String path, List<?> def) {
|
||||
return super.getList(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized long getLong(String path) {
|
||||
return super.getLong(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized long getLong(final String path, final long def) {
|
||||
return super.getLong(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Long> getLongList(String path) {
|
||||
return super.getLongList(path);
|
||||
}
|
||||
|
||||
public synchronized Map<String, Object> getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Map<?, ?>> getMapList(String path) {
|
||||
return super.getMapList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized OfflinePlayer getOfflinePlayer(String path) {
|
||||
return super.getOfflinePlayer(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) {
|
||||
return super.getOfflinePlayer(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<Short> getShortList(String path) {
|
||||
return super.getShortList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String getString(String path) {
|
||||
return super.getString(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String getString(String path, String def) {
|
||||
return super.getString(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<String> getStringList(String path) {
|
||||
return super.getStringList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Map<String, Object> getValues(boolean deep) {
|
||||
return super.getValues(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Vector getVector(String path) {
|
||||
return super.getVector(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Vector getVector(String path, Vector def) {
|
||||
return super.getVector(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isBoolean(String path) {
|
||||
return super.isBoolean(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isConfigurationSection(String path) {
|
||||
return super.isConfigurationSection(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isDouble(String path) {
|
||||
return super.isDouble(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isInt(String path) {
|
||||
return super.isInt(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isItemStack(String path) {
|
||||
return super.isItemStack(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isList(String path) {
|
||||
return super.isList(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isLong(String path) {
|
||||
return super.isLong(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isOfflinePlayer(String path) {
|
||||
return super.isOfflinePlayer(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isSet(String path) {
|
||||
return super.isSet(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isString(String path) {
|
||||
return super.isString(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isVector(String path) {
|
||||
return super.isVector(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void set(String path, Object value) {
|
||||
super.set(path, value);
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.*;
|
||||
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.EntityRegainHealthEvent.RegainReason;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
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) {
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
// This method does something undocumented reguarding certain bucket types #EasterEgg
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onEntityDamage(final EntityDamageByEntityEvent event) {
|
||||
final Entity eAttack = event.getDamager();
|
||||
final Entity eDefend = event.getEntity();
|
||||
if (eAttack instanceof Player) {
|
||||
final User attacker = ess.getUser((Player) eAttack);
|
||||
if (eDefend instanceof Player) {
|
||||
onPlayerVsPlayerDamage(event, (Player) eDefend, attacker);
|
||||
} else if (eDefend instanceof Ageable) {
|
||||
final ItemStack hand = attacker.getBase().getItemInHand();
|
||||
if (ess.getSettings().isMilkBucketEasterEggEnabled()
|
||||
&& hand != null && hand.getType() == Material.MILK_BUCKET) {
|
||||
((Ageable) eDefend).setBaby();
|
||||
hand.setType(Material.BUCKET);
|
||||
attacker.getBase().setItemInHand(hand);
|
||||
attacker.getBase().updateInventory();
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
attacker.updateActivityOnInteract(true);
|
||||
} else if (eAttack instanceof Projectile && eDefend instanceof Player) {
|
||||
final Projectile projectile = (Projectile) event.getDamager();
|
||||
//This should return a ProjectileSource on 1.7.3 beta +
|
||||
final Object shooter = projectile.getShooter();
|
||||
if (shooter instanceof Player) {
|
||||
final User attacker = ess.getUser((Player) shooter);
|
||||
onPlayerVsPlayerDamage(event, (Player) eDefend, attacker);
|
||||
attacker.updateActivityOnInteract(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onPlayerVsPlayerDamage(final EntityDamageByEntityEvent event, final Player defender, final User attacker) {
|
||||
if (ess.getSettings().getLoginAttackDelay() > 0 && (System.currentTimeMillis() < (attacker.getLastLogin() + ess.getSettings().getLoginAttackDelay())) && !attacker.isAuthorized("essentials.pvpdelay.exempt")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (!defender.equals(attacker.getBase()) && (attacker.hasInvulnerabilityAfterTeleport() || ess.getUser(defender).hasInvulnerabilityAfterTeleport())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (attacker.isGodModeEnabled() && !attacker.isAuthorized("essentials.god.pvp")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (attacker.isHidden() && !attacker.isAuthorized("essentials.vanish.pvp")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (attacker.arePowerToolsEnabled()) {
|
||||
onPlayerVsPlayerPowertool(event, defender, attacker);
|
||||
}
|
||||
}
|
||||
|
||||
private void onPlayerVsPlayerPowertool(final EntityDamageByEntityEvent event, final Player defender, final User attacker) {
|
||||
final List<String> commandList = attacker.getPowertool(attacker.getBase().getItemInHand());
|
||||
if (commandList != null && !commandList.isEmpty()) {
|
||||
for (final String tempCommand : commandList) {
|
||||
final String command = powertoolPlayer.matcher(tempCommand).replaceAll(defender.getName());
|
||||
if (command != null && !command.isEmpty() && !command.equals(tempCommand)) {
|
||||
|
||||
class PowerToolInteractTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
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);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onEntityDamage(final EntityDamageEvent event) {
|
||||
if (event.getEntity() instanceof Player && ess.getUser((Player) event.getEntity()).isGodModeEnabled()) {
|
||||
final Player player = (Player) event.getEntity();
|
||||
player.setFireTicks(0);
|
||||
player.setRemainingAir(player.getMaximumAir());
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onEntityCombust(final EntityCombustEvent event) {
|
||||
if (event.getEntity() instanceof Player && ess.getUser((Player) event.getEntity()).isGodModeEnabled()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onEntityCombustByEntity(final EntityCombustByEntityEvent event) {
|
||||
if (event.getCombuster() instanceof Arrow && event.getEntity() instanceof Player) {
|
||||
Arrow combuster = (Arrow) event.getCombuster();
|
||||
if (combuster.getShooter() instanceof Player) {
|
||||
final User srcCombuster = ess.getUser(((Player) combuster.getShooter()).getUniqueId());
|
||||
if (srcCombuster.isGodModeEnabled() && !srcCombuster.isAuthorized("essentials.god.pvp")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
if (srcCombuster.isHidden() && !srcCombuster.isAuthorized("essentials.vanish.pvp")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerDeathEvent(final PlayerDeathEvent event) {
|
||||
final User user = ess.getUser(event.getEntity());
|
||||
if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) {
|
||||
user.setLastLocation();
|
||||
user.sendMessage(tl("backAfterDeath"));
|
||||
}
|
||||
if (!ess.getSettings().areDeathMessagesEnabled()) {
|
||||
event.setDeathMessage("");
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onPlayerDeathExpEvent(final PlayerDeathEvent event) {
|
||||
final User user = ess.getUser(event.getEntity());
|
||||
if (user.isAuthorized("essentials.keepxp")) {
|
||||
event.setKeepLevel(true);
|
||||
event.setDroppedExp(0);
|
||||
}
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onFoodLevelChange(final FoodLevelChangeEvent event) {
|
||||
if (event.getEntity() instanceof Player) {
|
||||
final User user = ess.getUser((Player) event.getEntity());
|
||||
if (user.isGodModeEnabled()) {
|
||||
if (user.isGodModeEnabledRaw()) {
|
||||
user.getBase().setFoodLevel(20);
|
||||
user.getBase().setSaturation(10);
|
||||
}
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onEntityRegainHealth(final EntityRegainHealthEvent event) {
|
||||
if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player && ess.getUser((Player) event.getEntity()).isAfk() && ess.getSettings().getFreezeAfkPlayers()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onPotionSplashEvent(final PotionSplashEvent event) {
|
||||
for (LivingEntity entity : event.getAffectedEntities()) {
|
||||
if (entity instanceof Player && ess.getUser((Player) entity).isGodModeEnabled()) {
|
||||
event.setIntensity(entity, 0d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onEntityShootBow(EntityShootBowEvent event) {
|
||||
if (event.getEntity() instanceof Player) {
|
||||
final User user = ess.getUser((Player) event.getEntity());
|
||||
if (user.isAfk()) {
|
||||
user.updateActivityOnInteract(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onEntityTarget(EntityTargetEvent event) {
|
||||
if (event.getTarget() instanceof Player) {
|
||||
final User user = ess.getUser((Player) event.getTarget());
|
||||
if (user.isVanished()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,875 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
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 io.papermc.lib.PaperLib;
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.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.PlayerLoginEvent.Result;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
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;
|
||||
|
||||
public EssentialsPlayerListener(final IEssentials parent) {
|
||||
this.ess = parent;
|
||||
}
|
||||
|
||||
public void registerEvents() {
|
||||
ess.getServer().getPluginManager().registerEvents(this, ess);
|
||||
|
||||
if (isEntityPickupEvent()) {
|
||||
ess.getServer().getPluginManager().registerEvents(new PickupListener1_12(), ess);
|
||||
} else {
|
||||
ess.getServer().getPluginManager().registerEvents(new PickupListenerPre1_12(), ess);
|
||||
}
|
||||
|
||||
if (isCommandSendEvent()) {
|
||||
ess.getServer().getPluginManager().registerEvents(new CommandSendListener(), ess);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onPlayerRespawn(final PlayerRespawnEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
updateCompass(user);
|
||||
user.setDisplayNick();
|
||||
|
||||
if (ess.getSettings().isTeleportInvulnerability()) {
|
||||
user.enableInvulnerabilityAfterTeleport();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerChat(final AsyncPlayerChatEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isMuted()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced"));
|
||||
|
||||
LOGGER.info(tl("mutedUserSpeaks", user.getName(), event.getMessage()));
|
||||
}
|
||||
try {
|
||||
final Iterator<Player> it = event.getRecipients().iterator();
|
||||
while (it.hasNext()) {
|
||||
final User u = ess.getUser(it.next());
|
||||
if (u.isIgnoredPlayer(user)) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
} catch (UnsupportedOperationException ex) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "Ignore could not block chat due to custom chat plugin event.", ex);
|
||||
} else {
|
||||
ess.getLogger().info("Ignore could not block chat due to custom chat plugin event.");
|
||||
}
|
||||
}
|
||||
|
||||
user.updateActivityOnInteract(true);
|
||||
user.setDisplayNick();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
|
||||
public void onPlayerMove(final PlayerMoveEvent event) {
|
||||
if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ() && event.getFrom().getBlockY() == event.getTo().getBlockY()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ess.getSettings().cancelAfkOnMove() && !ess.getSettings().getFreezeAfkPlayers()) {
|
||||
event.getHandlers().unregister(this);
|
||||
|
||||
if (ess.getSettings().isDebug()) {
|
||||
LOGGER.log(Level.INFO, "Unregistering move listener");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) {
|
||||
final Location from = event.getFrom();
|
||||
final Location origTo = event.getTo();
|
||||
final Location to = origTo.clone();
|
||||
if (origTo.getY() >= from.getBlockY() + 1) {
|
||||
user.updateActivityOnMove(true);
|
||||
return;
|
||||
}
|
||||
to.setX(from.getX());
|
||||
to.setY(from.getY());
|
||||
to.setZ(from.getZ());
|
||||
try {
|
||||
event.setTo(LocationUtil.getSafeDestination(to));
|
||||
} catch (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);
|
||||
}
|
||||
}
|
||||
|
||||
@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")) {
|
||||
event.setQuitMessage(null);
|
||||
} else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) {
|
||||
final Player player = event.getPlayer();
|
||||
final String msg = ess.getSettings().getCustomQuitMessage()
|
||||
.replace("{PLAYER}", player.getDisplayName())
|
||||
.replace("{USERNAME}", player.getName())
|
||||
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()));
|
||||
|
||||
event.setQuitMessage(msg.isEmpty() ? null : msg);
|
||||
}
|
||||
|
||||
user.startTransaction();
|
||||
if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) {
|
||||
user.setGodModeEnabled(false);
|
||||
}
|
||||
if (user.isVanished()) {
|
||||
user.setVanished(false);
|
||||
}
|
||||
user.setLogoutLocation();
|
||||
if (user.isRecipeSee()) {
|
||||
user.getBase().getOpenInventory().getTopInventory().clear();
|
||||
}
|
||||
|
||||
for (HumanEntity viewer : user.getBase().getInventory().getViewers()) {
|
||||
if (viewer instanceof Player) {
|
||||
User uviewer = ess.getUser((Player) viewer);
|
||||
if (uviewer.isInvSee()) {
|
||||
uviewer.getBase().closeInventory();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user.updateActivity(false);
|
||||
if (!user.isHidden()) {
|
||||
user.setLastLogout(System.currentTimeMillis());
|
||||
}
|
||||
user.stopTransaction();
|
||||
|
||||
user.dispose();
|
||||
}
|
||||
|
||||
@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()) {
|
||||
event.setJoinMessage(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void delayedJoin(final Player player, final String message) {
|
||||
if (!player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ess.getBackup().onPlayerJoin();
|
||||
final User dUser = ess.getUser(player);
|
||||
|
||||
dUser.startTransaction();
|
||||
if (dUser.isNPC()) {
|
||||
dUser.setNPC(false);
|
||||
}
|
||||
|
||||
final long currentTime = System.currentTimeMillis();
|
||||
dUser.checkMuteTimeout(currentTime);
|
||||
dUser.updateActivity(false);
|
||||
dUser.stopTransaction();
|
||||
|
||||
class DelayJoinTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
final User user = ess.getUser(player);
|
||||
|
||||
if (!user.getBase().isOnline()) {
|
||||
return;
|
||||
}
|
||||
|
||||
user.startTransaction();
|
||||
|
||||
user.setLastAccountName(user.getBase().getName());
|
||||
user.setLastLogin(currentTime);
|
||||
user.setDisplayNick();
|
||||
updateCompass(user);
|
||||
|
||||
if (!ess.getVanishedPlayersNew().isEmpty() && !user.isAuthorized("essentials.vanish.see")) {
|
||||
for (String p : ess.getVanishedPlayersNew()) {
|
||||
Player toVanish = ess.getServer().getPlayerExact(p);
|
||||
if (toVanish != null && toVanish.isOnline()) {
|
||||
user.getBase().hidePlayer(toVanish);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().info("Hiding vanished player: " + p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (user.isAuthorized("essentials.sleepingignored")) {
|
||||
user.getBase().setSleepingIgnored(true);
|
||||
}
|
||||
|
||||
if (ess.getSettings().allowSilentJoinQuit() && (user.isAuthorized("essentials.silentjoin") || user.isAuthorized("essentials.silentjoin.vanish"))) {
|
||||
if (user.isAuthorized("essentials.silentjoin.vanish")) {
|
||||
user.setVanished(true);
|
||||
}
|
||||
} else if (message == null) {
|
||||
//NOOP
|
||||
} else if (ess.getSettings().isCustomJoinMessage()) {
|
||||
String msg = ess.getSettings().getCustomJoinMessage()
|
||||
.replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())
|
||||
.replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers()))
|
||||
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()));
|
||||
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);
|
||||
if (motdDelay > 0) {
|
||||
ess.scheduleSyncDelayedTask(motdTask, motdDelay);
|
||||
} else {
|
||||
motdTask.run();
|
||||
}
|
||||
|
||||
if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) {
|
||||
final List<String> mail = user.getMails();
|
||||
if (mail.isEmpty()) {
|
||||
if (ess.getSettings().isNotifyNoNewMail()) {
|
||||
user.sendMessage(tl("noNewMail")); // Only notify if they want us to.
|
||||
}
|
||||
} else {
|
||||
user.notifyOfMail();
|
||||
}
|
||||
}
|
||||
|
||||
if (user.isAuthorized("essentials.fly.safelogin")) {
|
||||
user.getBase().setFallDistance(0);
|
||||
if (LocationUtil.shouldFly(user.getLocation())) {
|
||||
user.getBase().setAllowFlight(true);
|
||||
user.getBase().setFlying(true);
|
||||
if (ess.getSettings().isSendFlyEnableOnJoin()) {
|
||||
user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!user.isAuthorized("essentials.speed")) {
|
||||
user.getBase().setFlySpeed(0.1f);
|
||||
user.getBase().setWalkSpeed(0.2f);
|
||||
}
|
||||
|
||||
if (user.isSocialSpyEnabled() && !user.isAuthorized("essentials.socialspy")) {
|
||||
user.setSocialSpyEnabled(false);
|
||||
ess.getLogger().log(Level.INFO, "Set socialspy to false for {0} because they had it enabled without permission.", user.getName());
|
||||
}
|
||||
|
||||
if (user.isGodModeEnabled() && !user.isAuthorized("essentials.god")) {
|
||||
user.setGodModeEnabled(false);
|
||||
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;
|
||||
|
||||
public DelayMotdTask(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
IText tempInput = null;
|
||||
|
||||
if (!ess.getSettings().isCommandDisabled("motd")) {
|
||||
try {
|
||||
tempInput = new TextInput(user.getSource(), "motd", true, ess);
|
||||
} catch (IOException ex) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
|
||||
} else {
|
||||
LOGGER.log(Level.WARNING, ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final IText input = tempInput;
|
||||
|
||||
if (input != null && !input.getLines().isEmpty() && user.isAuthorized("essentials.motd")) {
|
||||
final IText output = new KeywordReplacer(input, user.getSource(), ess);
|
||||
final TextPager pager = new TextPager(output, true);
|
||||
pager.showPage("1", null, "motd", user.getSource());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ess.scheduleSyncDelayedTask(new DelayJoinTask());
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (ess.getSettings().isCompassTowardsHomePerm() && !user.isAuthorized("essentials.home.compass")) return;
|
||||
|
||||
Location loc = user.getHome(user.getLocation());
|
||||
if (loc == null) {
|
||||
loc = user.getBase().getBedSpawnLocation();
|
||||
}
|
||||
if (loc != null) {
|
||||
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()));
|
||||
}
|
||||
} else {
|
||||
banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress());
|
||||
if (banEntry != null) {
|
||||
event.setKickMessage(tl("banIpJoin", banEntry.getReason()));
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
|
||||
public void onPlayerTeleport(final PlayerTeleportEvent event) {
|
||||
final boolean backListener = ess.getSettings().registerBackInListener();
|
||||
final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability();
|
||||
if (backListener || teleportInvulnerability) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
//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)) {
|
||||
user.setLastLocation();
|
||||
}
|
||||
if (teleportInvulnerability && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) {
|
||||
user.enableInvulnerabilityAfterTeleport();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
|
||||
public void onPlayerEggThrow(final PlayerEggThrowEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
final ItemStack stack = new ItemStack(Material.EGG, 1);
|
||||
if (user.hasUnlimited(stack)) {
|
||||
user.getBase().getInventory().addItem(stack);
|
||||
user.getBase().updateInventory();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
|
||||
public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) {
|
||||
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) {
|
||||
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);
|
||||
|
||||
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);
|
||||
if (!user.isAuthorized("essentials.chat.spy.exempt")) {
|
||||
for (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 {
|
||||
spyer.sendMessage(tl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) {
|
||||
event.setCancelled(true);
|
||||
player.sendMessage(tl("voiceSilenced"));
|
||||
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
|
||||
|
||||
if (pluginCommand != null) {
|
||||
// Switch case for commands that shouldn't broadcast afk activity.
|
||||
switch (pluginCommand.getName()) {
|
||||
case "afk":
|
||||
update = false;
|
||||
case "vanish":
|
||||
broadcast = false;
|
||||
}
|
||||
}
|
||||
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
|
||||
: " " + event.getMessage().substring(argStartIndex); // arguments start at argStartIndex; substring from there.
|
||||
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()) {
|
||||
// Remove any expired cooldowns
|
||||
if (entry.getValue() <= System.currentTimeMillis()) {
|
||||
user.clearCommandCooldown(entry.getKey());
|
||||
// Don't break in case there are other command cooldowns left to clear.
|
||||
} 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());
|
||||
user.sendMessage(tl("commandCooldown", commandCooldownTime));
|
||||
cooldownFound = true;
|
||||
event.setCancelled(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cooldownFound) {
|
||||
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());
|
||||
user.addCommandCooldown(cooldownEntry.getKey(), expiry, ess.getSettings().isCommandCooldownPersistent(fullCommand));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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());
|
||||
} else {
|
||||
user.getBase().setWalkSpeed(user.getBase().getWalkSpeed() * 0.99999f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
final String newWorld = event.getPlayer().getLocation().getWorld().getName();
|
||||
user.setDisplayNick();
|
||||
updateCompass(user);
|
||||
if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) {
|
||||
// Player god mode is never disabled in order to retain it when changing worlds once more.
|
||||
// With that said, players will still take damage as per the result of User#isGodModeEnabled()
|
||||
user.sendMessage(tl("noGodWorldWarning"));
|
||||
}
|
||||
|
||||
if (!user.getWorld().getName().equals(newWorld)) {
|
||||
user.sendMessage(tl("currentWorld", newWorld));
|
||||
}
|
||||
if (user.isVanished()) {
|
||||
user.setVanished(user.isAuthorized("essentials.vanish"));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onPlayerInteract(final PlayerInteractEvent event) {
|
||||
boolean updateActivity = true;
|
||||
|
||||
switch (event.getAction()) {
|
||||
case RIGHT_CLICK_BLOCK:
|
||||
if (!event.isCancelled() && MaterialUtil.isBed(event.getClickedBlock().getType()) && ess.getSettings().getUpdateBedAtDaytime()) {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case LEFT_CLICK_AIR:
|
||||
if (event.getPlayer().isFlying()) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isFlyClickJump()) {
|
||||
useFlyClickJump(user);
|
||||
break;
|
||||
}
|
||||
}
|
||||
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().getType())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case PHYSICAL:
|
||||
updateActivity = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (updateActivity) {
|
||||
ess.getUser(event.getPlayer()).updateActivityOnInteract(true);
|
||||
}
|
||||
}
|
||||
|
||||
// This method allows the /jump lock feature to work, allows teleporting while flying #EasterEgg
|
||||
private void useFlyClickJump(final User user) {
|
||||
try {
|
||||
final Location otarget = LocationUtil.getTarget(user.getBase());
|
||||
|
||||
class DelayedClickJumpTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
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);
|
||||
}
|
||||
PaperLib.teleportAsync(user.getBase(), loc, TeleportCause.PLUGIN);
|
||||
}
|
||||
}
|
||||
ess.scheduleSyncDelayedTask(new DelayedClickJumpTask());
|
||||
} catch (Exception ex) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean usePowertools(final User user, final Material material) {
|
||||
final List<String> commandList = user.getPowertool(material);
|
||||
if (commandList == null || commandList.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
boolean used = false;
|
||||
// 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));
|
||||
} else {
|
||||
used = true;
|
||||
|
||||
class PowerToolUseTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
user.getBase().chat("/" + command);
|
||||
LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command));
|
||||
}
|
||||
}
|
||||
ess.scheduleSyncDelayedTask(new PowerToolUseTask());
|
||||
|
||||
}
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
|
||||
public void onInventoryClickEvent(final InventoryClickEvent event) {
|
||||
Player refreshPlayer = null;
|
||||
final Inventory top = event.getView().getTopInventory();
|
||||
final InventoryType type = top.getType();
|
||||
|
||||
final Inventory clickedInventory;
|
||||
if (event.getRawSlot() < 0) {
|
||||
clickedInventory = null;
|
||||
} else {
|
||||
clickedInventory = event.getRawSlot() < top.getSize() ? top : event.getView().getBottomInventory();
|
||||
}
|
||||
|
||||
if (type == InventoryType.PLAYER) {
|
||||
final User user = ess.getUser((Player) event.getWhoClicked());
|
||||
final InventoryHolder invHolder = top.getHolder();
|
||||
if (invHolder != null && 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);
|
||||
refreshPlayer = user.getBase();
|
||||
}
|
||||
}
|
||||
} else if (type == InventoryType.ENDER_CHEST) {
|
||||
final User user = ess.getUser((Player) event.getWhoClicked());
|
||||
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());
|
||||
if (user.isRecipeSee()) {
|
||||
event.setCancelled(true);
|
||||
refreshPlayer = user.getBase();
|
||||
}
|
||||
} 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()) {
|
||||
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
|
||||
&& !MaterialUtil.isSkull(event.getCursor().getType())
|
||||
&& ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat")) {
|
||||
event.setCancelled(true);
|
||||
final PlayerInventory inv = (PlayerInventory) clickedInventory;
|
||||
final ItemStack head = inv.getHelmet();
|
||||
inv.setHelmet(event.getCursor());
|
||||
event.setCursor(head);
|
||||
}
|
||||
}
|
||||
|
||||
if (refreshPlayer != null) {
|
||||
final Player player = refreshPlayer;
|
||||
ess.scheduleSyncDelayedTask(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
player.updateInventory();
|
||||
}
|
||||
}, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onInventoryCloseEvent(final InventoryCloseEvent event) {
|
||||
Player refreshPlayer = null;
|
||||
final Inventory top = event.getView().getTopInventory();
|
||||
final InventoryType type = top.getType();
|
||||
if (type == InventoryType.PLAYER) {
|
||||
final User user = ess.getUser((Player) event.getPlayer());
|
||||
user.setInvSee(false);
|
||||
refreshPlayer = user.getBase();
|
||||
} else if (type == InventoryType.ENDER_CHEST) {
|
||||
final User user = ess.getUser((Player) event.getPlayer());
|
||||
user.setEnderSee(false);
|
||||
refreshPlayer = user.getBase();
|
||||
} else if (type == InventoryType.WORKBENCH) {
|
||||
final User user = ess.getUser((Player) event.getPlayer());
|
||||
if (user.isRecipeSee()) {
|
||||
user.setRecipeSee(false);
|
||||
event.getView().getTopInventory().clear();
|
||||
refreshPlayer = user.getBase();
|
||||
}
|
||||
} else if (type == InventoryType.CHEST && top.getSize() == 9) {
|
||||
final InventoryHolder invHolder = top.getHolder();
|
||||
if (invHolder != null && invHolder instanceof HumanEntity) {
|
||||
final User user = ess.getUser((Player) event.getPlayer());
|
||||
user.setInvSee(false);
|
||||
refreshPlayer = user.getBase();
|
||||
}
|
||||
}
|
||||
|
||||
if (refreshPlayer != null) {
|
||||
final Player player = refreshPlayer;
|
||||
ess.scheduleSyncDelayedTask(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
player.updateInventory();
|
||||
}
|
||||
}, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onPlayerFishEvent(final PlayerFishEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
user.updateActivityOnInteract(true);
|
||||
}
|
||||
|
||||
private static boolean isEntityPickupEvent() {
|
||||
try {
|
||||
Class.forName("org.bukkit.event.entity.EntityPickupItemEvent");
|
||||
return true;
|
||||
} catch (ClassNotFoundException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCommandSendEvent() {
|
||||
try {
|
||||
Class.forName("org.bukkit.event.player.PlayerCommandSendEvent");
|
||||
return true;
|
||||
} catch (ClassNotFoundException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
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 (ess.getUser(event.getPlayer()).isAfk()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if (ess.getUser((Player) event.getEntity()).isAfk()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class CommandSendListener implements Listener {
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onCommandSend(final PlayerCommandSendEvent event) {
|
||||
User user = ess.getUser(event.getPlayer());
|
||||
|
||||
ArrayList<String> removedCmds = new ArrayList<>(event.getCommands());
|
||||
|
||||
event.getCommands().removeIf(str -> shouldHideFromUser(str, user));
|
||||
|
||||
if (ess.getSettings().isDebug()) {
|
||||
removedCmds.removeAll(event.getCommands());
|
||||
ess.getLogger().info("Removed commands: " + removedCmds.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if all of the following are true:
|
||||
* - The command is a plugin command
|
||||
* - The plugin command is from Essentials
|
||||
* - There is no known alternative OR the alternative is overridden by Essentials
|
||||
* - The user is not allowed to perform the given Essentials command
|
||||
*/
|
||||
private boolean shouldHideFromUser(String commandLabel, User user) {
|
||||
PluginCommand command = ess.getServer().getPluginCommand(commandLabel);
|
||||
|
||||
return command != null
|
||||
&& command.getPlugin().getName().equals("Essentials")
|
||||
&& (ess.getSettings().isCommandOverridden(commandLabel) || (ess.getAlternativeCommandsHandler().getAlternative(commandLabel) == null))
|
||||
&& !user.isAuthorized(command.getName().equals("r") ? "essentials.msg" : "essentials." + command.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.register.payment.Methods;
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
import org.bukkit.event.server.PluginEnableEvent;
|
||||
|
||||
import java.util.logging.Level;
|
||||
|
||||
|
||||
public class EssentialsPluginListener implements Listener, IConf {
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public EssentialsPluginListener(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPluginEnable(final PluginEnableEvent event) {
|
||||
if (event.getPlugin().getName().equals("EssentialsChat")) {
|
||||
ess.getSettings().setEssentialsChatActive(true);
|
||||
}
|
||||
ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions());
|
||||
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() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPluginDisable(final PluginDisableEvent event) {
|
||||
if (event.getPlugin().getName().equals("EssentialsChat")) {
|
||||
ess.getSettings().setEssentialsChatActive(false);
|
||||
}
|
||||
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())) {
|
||||
Methods.reset();
|
||||
ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import net.ess3.nms.refl.ReflUtil;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
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 List<String> ignoredSLPECallers = Arrays.asList(
|
||||
".LegacyPingHandler.channelRead(", // CB responding to pings from pre-Netty clients
|
||||
"de.dytanic.cloudnet.bridge.BukkitBootstrap" // CloudNet v2 doing... something
|
||||
);
|
||||
|
||||
private final transient IEssentials ess;
|
||||
private boolean unsupportedLogged = false;
|
||||
private boolean npeWarned = false;
|
||||
private boolean isPaperSample;
|
||||
private Method setSampleText;
|
||||
private Method getSampleText;
|
||||
|
||||
public EssentialsServerListener(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
|
||||
if (ReflUtil.getClassCached("com.destroystokyo.paper.event.server.PaperServerListPingEvent") == null) {
|
||||
// This workaround is only necessary for older Paper builds
|
||||
setSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "setSampleText", List.class);
|
||||
getSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "getSampleText");
|
||||
if (setSampleText != null && getSampleText != null) {
|
||||
ess.getLogger().info("ServerListPingEvent: Paper 1.12.2 setSampleText API");
|
||||
isPaperSample = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ess.getLogger().info("ServerListPingEvent: Spigot iterator API");
|
||||
isPaperSample = false;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onServerListPing(final ServerListPingEvent event) throws Exception {
|
||||
if (isPaperSample) {
|
||||
try {
|
||||
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 && shouldWarnSLPECaller(e)) {
|
||||
ess.getLogger().log(Level.WARNING, "Unable to hide players from server list ping "
|
||||
+ "using Paper 1.12 method!", e);
|
||||
unsupportedLogged = true;
|
||||
}
|
||||
} catch (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.");
|
||||
ex.setStackTrace(e.getStackTrace());
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
Iterator<Player> iterator = event.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Player player = iterator.next();
|
||||
if (ess.getUser(player).isVanished()) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
} catch (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(Throwable throwable) {
|
||||
final int maxStackDepth = 20; // Limit the depth when searching through the stack trace
|
||||
int depth = 0;
|
||||
for (StackTraceElement element : throwable.getStackTrace()) {
|
||||
depth++;
|
||||
if (depth > maxStackDepth) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (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
|
||||
}
|
||||
}
|
||||
@@ -1,106 +1,82 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.ISettings;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.perm.Permissions;
|
||||
import com.earth2me.essentials.user.UserData.TimestampType;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class EssentialsTimer implements Runnable
|
||||
{
|
||||
private final transient IEssentials ess;
|
||||
private final transient Set<IUser> onlineUsers = new HashSet<IUser>();
|
||||
|
||||
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<>();
|
||||
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;
|
||||
}
|
||||
|
||||
EssentialsTimer(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
history.add(20d);
|
||||
}
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
final long currentTime = System.currentTimeMillis();
|
||||
for (Player player : ess.getServer().getOnlinePlayers())
|
||||
{
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final long startTime = System.nanoTime();
|
||||
final long currentTime = System.currentTimeMillis();
|
||||
long timeSpent = (startTime - lastPoll) / 1000;
|
||||
if (timeSpent == 0) {
|
||||
timeSpent = 1;
|
||||
}
|
||||
if (history.size() > 10) {
|
||||
history.remove();
|
||||
}
|
||||
double tps = tickInterval * 1000000.0 / timeSpent;
|
||||
if (tps <= 21) {
|
||||
history.add(tps);
|
||||
}
|
||||
lastPoll = startTime;
|
||||
int count = 0;
|
||||
for (Player player : ess.getOnlinePlayers()) {
|
||||
count++;
|
||||
if (skip1 > 0) {
|
||||
skip1--;
|
||||
continue;
|
||||
}
|
||||
if (count % 10 == 0) {
|
||||
if (System.nanoTime() - startTime > maxTime / 2) {
|
||||
skip1 = count - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
try {
|
||||
final User user = ess.getUser(player);
|
||||
onlineUsers.add(user.getBase().getUniqueId());
|
||||
user.setLastOnlineActivity(currentTime);
|
||||
user.checkActivity();
|
||||
} catch (Exception e) {
|
||||
ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
final IUser user = ess.getUser(player);
|
||||
onlineUsers.add(user);
|
||||
user.setLastOnlineActivity(currentTime);
|
||||
user.checkActivity();
|
||||
|
||||
count = 0;
|
||||
final Iterator<UUID> iterator = onlineUsers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
count++;
|
||||
if (skip2 > 0) {
|
||||
skip2--;
|
||||
continue;
|
||||
}
|
||||
if (count % 10 == 0) {
|
||||
if (System.nanoTime() - startTime > maxTime) {
|
||||
skip2 = count - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
final User user = ess.getUser(iterator.next());
|
||||
// Not sure why this would happen, but it does
|
||||
if (user == null) {
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) {
|
||||
if (!user.isHidden()) {
|
||||
user.setLastLogout(user.getLastOnlineActivity());
|
||||
}
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
user.checkMuteTimeout(currentTime);
|
||||
user.checkJailTimeout(currentTime);
|
||||
user.resetInvulnerabilityAfterTeleport();
|
||||
}
|
||||
}
|
||||
boolean mailDisabled = false;
|
||||
ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
try
|
||||
{
|
||||
mailDisabled = settings.getData().getCommands().isDisabled("mail");
|
||||
}
|
||||
finally
|
||||
{
|
||||
settings.unlock();
|
||||
}
|
||||
// New mail notification
|
||||
if (user != null && !mailDisabled && Permissions.MAIL.isAuthorized(user) && !user.gotMailInfo())
|
||||
{
|
||||
final List<String> mail = user.getMails();
|
||||
if (mail != null && !mail.isEmpty())
|
||||
{
|
||||
user.sendMessage(_("youHaveNewMail", mail.size()));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
public double getAverageTPS() {
|
||||
double avg = 0;
|
||||
for (Double f : history) {
|
||||
if (f != null) {
|
||||
avg += f;
|
||||
}
|
||||
}
|
||||
return avg / history.size();
|
||||
}
|
||||
final Iterator<IUser> iterator = onlineUsers.iterator();
|
||||
while (iterator.hasNext())
|
||||
{
|
||||
final IUser user = iterator.next();
|
||||
if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getTimestamp(TimestampType.LOGOUT))
|
||||
{
|
||||
user.setTimestamp(TimestampType.LOGOUT, user.getLastOnlineActivity());
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
user.checkMuteTimeout(currentTime);
|
||||
user.checkJailTimeout(currentTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,722 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.craftbukkit.BanLookup;
|
||||
import com.earth2me.essentials.craftbukkit.FakeWorld;
|
||||
import com.earth2me.essentials.settings.Spawns;
|
||||
import com.earth2me.essentials.storage.YamlStorageWriter;
|
||||
import com.earth2me.essentials.utils.StringUtil;
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.collect.Maps;
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.BanList;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.security.DigestInputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
public class EssentialsUpgrade {
|
||||
private final static Logger LOGGER = Logger.getLogger("Essentials");
|
||||
private final transient IEssentials ess;
|
||||
private final transient EssentialsConf doneFile;
|
||||
|
||||
EssentialsUpgrade(final IEssentials essentials) {
|
||||
ess = essentials;
|
||||
if (!ess.getDataFolder().exists()) {
|
||||
ess.getDataFolder().mkdirs();
|
||||
}
|
||||
doneFile = new EssentialsConf(new File(ess.getDataFolder(), "upgrades-done.yml"));
|
||||
doneFile.load();
|
||||
}
|
||||
|
||||
public void convertKits() {
|
||||
Kits kits = ess.getKits();
|
||||
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();
|
||||
if (section == null) {
|
||||
LOGGER.info("No kits found to migrate.");
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Object> legacyKits = ess.getSettings().getKitSection().getValues(true);
|
||||
|
||||
for (Map.Entry<String, Object> entry : legacyKits.entrySet()) {
|
||||
LOGGER.info("Converting " + entry.getKey());
|
||||
config.set("kits." + entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
config.save();
|
||||
doneFile.setProperty("kitsyml", true);
|
||||
doneFile.save();
|
||||
LOGGER.info("Done converting kits.");
|
||||
}
|
||||
|
||||
private void moveMotdRulesToFile(String name) {
|
||||
if (doneFile.getBoolean("move" + name + "ToFile", false)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final File file = new File(ess.getDataFolder(), name + ".txt");
|
||||
if (file.exists()) {
|
||||
return;
|
||||
}
|
||||
final File configFile = new File(ess.getDataFolder(), "config.yml");
|
||||
if (!configFile.exists()) {
|
||||
return;
|
||||
}
|
||||
final EssentialsConf conf = new EssentialsConf(configFile);
|
||||
conf.load();
|
||||
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);
|
||||
|
||||
for (String line : lines) {
|
||||
writer.println(line);
|
||||
}
|
||||
writer.close();
|
||||
}
|
||||
doneFile.setProperty("move" + name + "ToFile", true);
|
||||
doneFile.save();
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeLinesFromConfig(File file, String regex, 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());
|
||||
final BufferedWriter bWriter = new BufferedWriter(new FileWriter(tempFile));
|
||||
do {
|
||||
final String line = bReader.readLine();
|
||||
if (line == null) {
|
||||
break;
|
||||
}
|
||||
if (line.matches(regex)) {
|
||||
if (!needUpdate && info != null) {
|
||||
bWriter.write(info, 0, info.length());
|
||||
bWriter.newLine();
|
||||
}
|
||||
needUpdate = true;
|
||||
} else {
|
||||
if (line.endsWith("\r\n")) {
|
||||
bWriter.write(line, 0, line.length() - 2);
|
||||
} else if (line.endsWith("\r") || line.endsWith("\n")) {
|
||||
bWriter.write(line, 0, line.length() - 1);
|
||||
} else {
|
||||
bWriter.write(line, 0, line.length());
|
||||
}
|
||||
bWriter.newLine();
|
||||
}
|
||||
} while (true);
|
||||
bReader.close();
|
||||
bWriter.close();
|
||||
if (needUpdate) {
|
||||
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) {
|
||||
throw new Exception(tl("configFileMoveError"));
|
||||
}
|
||||
if (!tempFile.renameTo(file)) {
|
||||
throw new Exception(tl("configFileRenameError"));
|
||||
}
|
||||
} else {
|
||||
tempFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateUsersPowerToolsFormat() {
|
||||
if (doneFile.getBoolean("updateUsersPowerToolsFormat", false)) {
|
||||
return;
|
||||
}
|
||||
final File userdataFolder = new File(ess.getDataFolder(), "userdata");
|
||||
if (!userdataFolder.exists() || !userdataFolder.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
final File[] userFiles = userdataFolder.listFiles();
|
||||
|
||||
for (File file : userFiles) {
|
||||
if (!file.isFile() || !file.getName().endsWith(".yml")) {
|
||||
continue;
|
||||
}
|
||||
final EssentialsConf config = new EssentialsConf(file);
|
||||
try {
|
||||
config.load();
|
||||
if (config.hasProperty("powertools")) {
|
||||
@SuppressWarnings("unchecked") final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false);
|
||||
if (powertools == null) {
|
||||
continue;
|
||||
}
|
||||
for (Map.Entry<String, Object> entry : powertools.entrySet()) {
|
||||
if (entry.getValue() instanceof String) {
|
||||
List<String> temp = new ArrayList<>();
|
||||
temp.add((String) entry.getValue());
|
||||
powertools.put(entry.getKey(), temp);
|
||||
}
|
||||
}
|
||||
config.forceSave();
|
||||
}
|
||||
} catch (RuntimeException ex) {
|
||||
LOGGER.log(Level.INFO, "File: " + file.toString());
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
doneFile.setProperty("updateUsersPowerToolsFormat", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private void updateUsersHomesFormat() {
|
||||
if (doneFile.getBoolean("updateUsersHomesFormat", false)) {
|
||||
return;
|
||||
}
|
||||
final File userdataFolder = new File(ess.getDataFolder(), "userdata");
|
||||
if (!userdataFolder.exists() || !userdataFolder.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
final File[] userFiles = userdataFolder.listFiles();
|
||||
|
||||
for (File file : userFiles) {
|
||||
if (!file.isFile() || !file.getName().endsWith(".yml")) {
|
||||
continue;
|
||||
}
|
||||
final EssentialsConf config = new EssentialsConf(file);
|
||||
try {
|
||||
|
||||
config.load();
|
||||
if (config.hasProperty("home") && config.hasProperty("home.default")) {
|
||||
@SuppressWarnings("unchecked") 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);
|
||||
Location loc;
|
||||
String worldName;
|
||||
|
||||
if (worlds == null) {
|
||||
continue;
|
||||
}
|
||||
for (String world : worlds) {
|
||||
if (defworld.equalsIgnoreCase(world)) {
|
||||
continue;
|
||||
}
|
||||
loc = getFakeLocation(config, "home.worlds." + world);
|
||||
if (loc == null) {
|
||||
continue;
|
||||
}
|
||||
worldName = loc.getWorld().getName().toLowerCase(Locale.ENGLISH);
|
||||
if (worldName != null && !worldName.isEmpty()) {
|
||||
config.setProperty("homes." + worldName, loc);
|
||||
}
|
||||
}
|
||||
config.removeProperty("home");
|
||||
config.forceSave();
|
||||
}
|
||||
|
||||
} catch (RuntimeException ex) {
|
||||
LOGGER.log(Level.INFO, "File: " + file.toString());
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
doneFile.setProperty("updateUsersHomesFormat", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private void sanitizeAllUserFilenames() {
|
||||
if (doneFile.getBoolean("sanitizeAllUserFilenames", false)) {
|
||||
return;
|
||||
}
|
||||
final File usersFolder = new File(ess.getDataFolder(), "userdata");
|
||||
if (!usersFolder.exists()) {
|
||||
return;
|
||||
}
|
||||
final File[] listOfFiles = usersFolder.listFiles();
|
||||
for (File listOfFile : listOfFiles) {
|
||||
final String filename = listOfFile.getName();
|
||||
if (!listOfFile.isFile() || !filename.endsWith(".yml")) {
|
||||
continue;
|
||||
}
|
||||
final String sanitizedFilename = StringUtil.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml";
|
||||
if (sanitizedFilename.equals(filename)) {
|
||||
continue;
|
||||
}
|
||||
final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp");
|
||||
final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename);
|
||||
if (!listOfFile.renameTo(tmpFile)) {
|
||||
LOGGER.log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename));
|
||||
continue;
|
||||
}
|
||||
if (newFile.exists()) {
|
||||
LOGGER.log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename));
|
||||
continue;
|
||||
}
|
||||
if (!tmpFile.renameTo(newFile)) {
|
||||
LOGGER.log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
|
||||
}
|
||||
}
|
||||
doneFile.setProperty("sanitizeAllUserFilenames", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private World getFakeWorld(final String name) {
|
||||
final File bukkitDirectory = ess.getDataFolder().getParentFile().getParentFile();
|
||||
final File worldDirectory = new File(bukkitDirectory, name);
|
||||
if (worldDirectory.exists() && worldDirectory.isDirectory()) {
|
||||
return new FakeWorld(worldDirectory.getName(), World.Environment.NORMAL);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Location getFakeLocation(EssentialsConf config, String path) {
|
||||
String worldName = config.getString((path != null ? path + "." : "") + "world");
|
||||
if (worldName == null || worldName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
World world = getFakeWorld(worldName);
|
||||
if (world == null) {
|
||||
return null;
|
||||
}
|
||||
return new Location(world, config.getDouble((path != null ? path + "." : "") + "x", 0), config.getDouble((path != null ? path + "." : "") + "y", 0), config.getDouble((path != null ? path + "." : "") + "z", 0), (float) config.getDouble((path != null ? path + "." : "") + "yaw", 0), (float) config.getDouble((path != null ? path + "." : "") + "pitch", 0));
|
||||
}
|
||||
|
||||
private void deleteOldItemsCsv() {
|
||||
if (doneFile.getBoolean("deleteOldItemsCsv", false)) {
|
||||
return;
|
||||
}
|
||||
final File file = new File(ess.getDataFolder(), "items.csv");
|
||||
if (file.exists()) {
|
||||
try {
|
||||
final Set<BigInteger> oldconfigs = new HashSet<>();
|
||||
oldconfigs.add(new BigInteger("66ec40b09ac167079f558d1099e39f10", 16)); // sep 1
|
||||
oldconfigs.add(new BigInteger("34284de1ead43b0bee2aae85e75c041d", 16)); // crlf
|
||||
oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24
|
||||
oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf
|
||||
|
||||
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)) {
|
||||
while (dis.read(buffer) != -1) {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSpawnsToNewSpawnsConfig() {
|
||||
if (doneFile.getBoolean("updateSpawnsToNewSpawnsConfig", false)) {
|
||||
return;
|
||||
}
|
||||
final File configFile = new File(ess.getDataFolder(), "spawn.yml");
|
||||
if (configFile.exists()) {
|
||||
|
||||
final EssentialsConf config = new EssentialsConf(configFile);
|
||||
try {
|
||||
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);
|
||||
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)) {
|
||||
new YamlStorageWriter(writer).save(spawns);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
doneFile.setProperty("updateSpawnsToNewSpawnsConfig", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private void updateJailsToNewJailsConfig() {
|
||||
if (doneFile.getBoolean("updateJailsToNewJailsConfig", false)) {
|
||||
return;
|
||||
}
|
||||
final File configFile = new File(ess.getDataFolder(), "jail.yml");
|
||||
if (configFile.exists()) {
|
||||
|
||||
final EssentialsConf config = new EssentialsConf(configFile);
|
||||
try {
|
||||
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);
|
||||
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)) {
|
||||
new YamlStorageWriter(writer).save(jails);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
doneFile.setProperty("updateJailsToNewJailsConfig", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private void warnMetrics() {
|
||||
if (doneFile.getBoolean("warnMetrics", false)) {
|
||||
return;
|
||||
}
|
||||
doneFile.setProperty("warnMetrics", true);
|
||||
doneFile.save();
|
||||
}
|
||||
|
||||
private void uuidFileChange() {
|
||||
if (doneFile.getBoolean("uuidFileChange", false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false);
|
||||
|
||||
final File userdir = new File(ess.getDataFolder(), "userdata");
|
||||
if (!userdir.exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int countFiles = 0;
|
||||
int countReqFiles = 0;
|
||||
for (String string : userdir.list()) {
|
||||
if (!string.endsWith(".yml") || string.length() < 5) {
|
||||
continue;
|
||||
}
|
||||
|
||||
countFiles++;
|
||||
|
||||
final String name = string.substring(0, string.length() - 4);
|
||||
UUID uuid = null;
|
||||
|
||||
try {
|
||||
uuid = UUID.fromString(name);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
countReqFiles++;
|
||||
}
|
||||
|
||||
if (countFiles > 100) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (countReqFiles < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
ess.getLogger().info("#### Starting Essentials UUID userdata conversion in a few seconds. ####");
|
||||
ess.getLogger().info("We recommend you take a backup of your server before upgrading from the old username system.");
|
||||
|
||||
try {
|
||||
Thread.sleep(15000);
|
||||
} catch (InterruptedException ex) {
|
||||
// NOOP
|
||||
}
|
||||
|
||||
uuidFileConvert(ess, ignoreUFCache);
|
||||
|
||||
doneFile.setProperty("uuidFileChange", true);
|
||||
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;
|
||||
}
|
||||
|
||||
ess.getLogger().info("Starting Essentials ban format conversion");
|
||||
|
||||
final File userdir = new File(ess.getDataFolder(), "userdata");
|
||||
if (!userdir.exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int countFiles = 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.getLogger().info("Converted " + countFiles + "/" + userdir.list().length);
|
||||
}
|
||||
|
||||
countFiles++;
|
||||
final File pFile = new File(userdir, string);
|
||||
final EssentialsConf conf = new EssentialsConf(pFile);
|
||||
conf.load();
|
||||
|
||||
String banReason;
|
||||
Long banTimeout;
|
||||
|
||||
try {
|
||||
banReason = conf.getConfigurationSection("ban").getString("reason");
|
||||
} catch (NullPointerException n) {
|
||||
banReason = null;
|
||||
}
|
||||
|
||||
final String playerName = conf.getString("lastAccountName");
|
||||
if (playerName != null && playerName.length() > 1 && banReason != null && banReason.length() > 1) {
|
||||
try {
|
||||
if (conf.getConfigurationSection("ban").contains("timeout")) {
|
||||
banTimeout = Long.parseLong(conf.getConfigurationSection("ban").getString("timeout"));
|
||||
} else {
|
||||
banTimeout = 0L;
|
||||
}
|
||||
} catch (NumberFormatException n) {
|
||||
banTimeout = 0L;
|
||||
}
|
||||
|
||||
if (BanLookup.isBanned(ess, playerName)) {
|
||||
updateBan(playerName, banReason, banTimeout);
|
||||
}
|
||||
}
|
||||
conf.removeProperty("ban");
|
||||
conf.save();
|
||||
}
|
||||
|
||||
doneFile.setProperty("banFormatChange", true);
|
||||
doneFile.save();
|
||||
ess.getLogger().info("Ban format update complete.");
|
||||
}
|
||||
|
||||
private void updateBan(String playerName, String banReason, Long banTimeout) {
|
||||
if (banTimeout == 0) {
|
||||
Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, null, Console.NAME);
|
||||
} else {
|
||||
Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, new Date(banTimeout), Console.NAME);
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
if (!userdataFolder.isDirectory()) {
|
||||
ess.getLogger().warning("Missing userdata folder, aborting");
|
||||
return;
|
||||
}
|
||||
File[] files = userdataFolder.listFiles(YML_FILTER);
|
||||
|
||||
final DecimalFormat format = new DecimalFormat("#0.00");
|
||||
final Map<String, UUID> names = Maps.newHashMap();
|
||||
|
||||
for (int index = 0; index < files.length; index++) {
|
||||
final File file = files[index];
|
||||
try {
|
||||
UUID uuid = null;
|
||||
final String filename = file.getName();
|
||||
final String configData = new String(java.nio.file.Files.readAllBytes(file.toPath()), Charsets.UTF_8);
|
||||
|
||||
if (filename.length() > 36) {
|
||||
try {
|
||||
// ".yml" ending has 4 chars...
|
||||
uuid = UUID.fromString(filename.substring(0, filename.length() - 4));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
final Matcher uuidMatcher = PATTERN_CONFIG_UUID.matcher(configData);
|
||||
if (uuidMatcher.find()) {
|
||||
try {
|
||||
uuid = UUID.fromString(uuidMatcher.group(1));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
if (uuid == null) {
|
||||
// Don't import
|
||||
continue;
|
||||
}
|
||||
|
||||
final Matcher nameMatcher = PATTERN_CONFIG_NAME.matcher(configData);
|
||||
if (nameMatcher.find()) {
|
||||
final String username = nameMatcher.group(1);
|
||||
if (username != null && username.length() > 0) {
|
||||
names.put(StringUtil.safeString(username), uuid);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ess.getUserMap().getNames().putAll(names);
|
||||
ess.getUserMap().reloadConfig();
|
||||
|
||||
doneFile.setProperty("userMapRepaired", true);
|
||||
doneFile.save();
|
||||
ess.getLogger().info("Completed usermap repair.");
|
||||
}
|
||||
|
||||
public void beforeSettings() {
|
||||
if (!ess.getDataFolder().exists()) {
|
||||
ess.getDataFolder().mkdirs();
|
||||
}
|
||||
moveMotdRulesToFile("motd");
|
||||
moveMotdRulesToFile("rules");
|
||||
}
|
||||
|
||||
public void afterSettings() {
|
||||
sanitizeAllUserFilenames();
|
||||
updateUsersPowerToolsFormat();
|
||||
updateUsersHomesFormat();
|
||||
deleteOldItemsCsv();
|
||||
updateSpawnsToNewSpawnsConfig();
|
||||
updateJailsToNewJailsConfig();
|
||||
uuidFileChange();
|
||||
banFormatChange();
|
||||
warnMetrics();
|
||||
repairUserMap();
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.Files;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
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;
|
||||
|
||||
public EssentialsUserConf(final String username, final UUID uuid, final File configFile) {
|
||||
super(configFile);
|
||||
this.username = username;
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean legacyFileExists() {
|
||||
final File file = new File(configFile.getParentFile(), username + ".yml");
|
||||
return file.exists();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertLegacyFile() {
|
||||
final File file = new File(configFile.getParentFile(), username + ".yml");
|
||||
try {
|
||||
Files.move(file, new File(configFile.getParentFile(), uuid + ".yml"));
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex);
|
||||
}
|
||||
|
||||
setProperty("lastAccountName", username);
|
||||
}
|
||||
|
||||
private File getAltFile() {
|
||||
final UUID fn = UUID.nameUUIDFromBytes(("OfflinePlayer:" + username.toLowerCase(Locale.ENGLISH)).getBytes(Charsets.UTF_8));
|
||||
return new File(configFile.getParentFile(), fn.toString() + ".yml");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean altFileExists() {
|
||||
if (username.equals(username.toLowerCase())) {
|
||||
return false;
|
||||
}
|
||||
return getAltFile().exists();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertAltFile() {
|
||||
try {
|
||||
Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml"));
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,69 +7,83 @@ 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 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>();
|
||||
}
|
||||
public ExecuteTimer()
|
||||
{
|
||||
times = new ArrayList<ExecuteRecord>();
|
||||
}
|
||||
|
||||
public void start() {
|
||||
times.clear();
|
||||
mark("start");
|
||||
public void start()
|
||||
{
|
||||
times.clear();
|
||||
mark("start");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void mark(final String label) {
|
||||
if (!times.isEmpty() || "start".equals(label)) {
|
||||
times.add(new ExecuteRecord(label, System.nanoTime()));
|
||||
}
|
||||
}
|
||||
public void mark(final String label)
|
||||
{
|
||||
if (!times.isEmpty() || "start".equals(label))
|
||||
{
|
||||
times.add(new ExecuteRecord(label, System.nanoTime()));
|
||||
}
|
||||
}
|
||||
|
||||
public String end() {
|
||||
final StringBuilder output = new StringBuilder();
|
||||
output.append("execution time: ");
|
||||
String mark;
|
||||
long time0 = 0;
|
||||
long time1 = 0;
|
||||
long time2 = 0;
|
||||
double duration;
|
||||
public String end()
|
||||
{
|
||||
final StringBuilder output = new StringBuilder();
|
||||
output.append("execution time: ");
|
||||
String mark;
|
||||
long time0 = 0;
|
||||
long time1 = 0;
|
||||
long time2 = 0;
|
||||
double duration;
|
||||
|
||||
for (ExecuteRecord pair : times) {
|
||||
mark = pair.getMark();
|
||||
time2 = pair.getTime();
|
||||
if (time1 > 0) {
|
||||
duration = (time2 - time1) / 1000000.0;
|
||||
output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - ");
|
||||
} else {
|
||||
time0 = time2;
|
||||
}
|
||||
time1 = time2;
|
||||
}
|
||||
duration = (time1 - time0) / 1000000.0;
|
||||
output.append("Total: ").append(decimalFormat.format(duration)).append("ms");
|
||||
times.clear();
|
||||
return output.toString();
|
||||
}
|
||||
for (ExecuteRecord pair : times)
|
||||
{
|
||||
mark = (String)pair.getMark();
|
||||
time2 = (Long)pair.getTime();
|
||||
if (time1 > 0)
|
||||
{
|
||||
duration = (time2 - time1)/1000000.0;
|
||||
output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - ");
|
||||
}
|
||||
else
|
||||
{
|
||||
time0 = time2;
|
||||
}
|
||||
time1 = time2;
|
||||
}
|
||||
duration = (time1 - time0)/1000000.0;
|
||||
output.append("Total: ").append(decimalFormat.format(duration)).append("ms");
|
||||
times.clear();
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
|
||||
private static class ExecuteRecord {
|
||||
private final String mark;
|
||||
private final long time;
|
||||
static private class ExecuteRecord
|
||||
{
|
||||
private final String mark;
|
||||
private final long time;
|
||||
|
||||
public ExecuteRecord(final String mark, final long time) {
|
||||
this.mark = mark;
|
||||
this.time = time;
|
||||
}
|
||||
public ExecuteRecord(final String mark, final long time)
|
||||
{
|
||||
this.mark = mark;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getMark() {
|
||||
return mark;
|
||||
}
|
||||
public String getMark()
|
||||
{
|
||||
return mark;
|
||||
}
|
||||
|
||||
public long getTime() {
|
||||
return time;
|
||||
}
|
||||
}
|
||||
public long getTime()
|
||||
{
|
||||
return time;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.II18n;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -12,155 +12,166 @@ import java.text.MessageFormat;
|
||||
import java.util.*;
|
||||
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;
|
||||
}
|
||||
public class I18n implements 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 final transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
|
||||
private final transient IEssentials ess;
|
||||
|
||||
protected Object handleGetObject(String key) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
public I18n(final IEssentials ess)
|
||||
{
|
||||
this.ess = ess;
|
||||
customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
|
||||
localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale);
|
||||
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
|
||||
}
|
||||
|
||||
public I18n(final IEssentials ess) {
|
||||
this.ess = ess;
|
||||
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
|
||||
localeBundle = defaultBundle;
|
||||
customBundle = NULL_BUNDLE;
|
||||
}
|
||||
public void onEnable()
|
||||
{
|
||||
instance = this;
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
}
|
||||
public void onDisable()
|
||||
{
|
||||
instance = null;
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
instance = null;
|
||||
}
|
||||
@Override
|
||||
public Locale getCurrentLocale()
|
||||
{
|
||||
return currentLocale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locale getCurrentLocale() {
|
||||
return currentLocale;
|
||||
}
|
||||
public String translate(final String string)
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
return customBundle.getString(string);
|
||||
}
|
||||
catch (MissingResourceException ex)
|
||||
{
|
||||
return localeBundle.getString(string);
|
||||
}
|
||||
}
|
||||
catch (MissingResourceException ex)
|
||||
{
|
||||
Logger.getLogger("Minecraft").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex);
|
||||
return defaultBundle.getString(string);
|
||||
}
|
||||
}
|
||||
|
||||
private String translate(final String string) {
|
||||
try {
|
||||
try {
|
||||
return customBundle.getString(string);
|
||||
} catch (MissingResourceException ex) {
|
||||
return localeBundle.getString(string);
|
||||
}
|
||||
} catch (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 _(final String string, final Object... objects)
|
||||
{
|
||||
if (instance == null) {
|
||||
return "";
|
||||
}
|
||||
if (objects.length == 0)
|
||||
{
|
||||
return instance.translate(string);
|
||||
}
|
||||
else
|
||||
{
|
||||
return instance.format(string, objects);
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
final String format = translate(string);
|
||||
MessageFormat messageFormat = messageFormatCache.get(format);
|
||||
if (messageFormat == null)
|
||||
{
|
||||
messageFormat = new MessageFormat(format);
|
||||
messageFormatCache.put(format, messageFormat);
|
||||
}
|
||||
return messageFormat.format(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) {
|
||||
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).replace(' ', ' '); // replace nbsp with a space
|
||||
}
|
||||
public void updateLocale(final String loc)
|
||||
{
|
||||
if (loc == null || loc.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
final String[] parts = loc.split("[_\\.]");
|
||||
if (parts.length == 1)
|
||||
{
|
||||
currentLocale = new Locale(parts[0]);
|
||||
}
|
||||
if (parts.length == 2)
|
||||
{
|
||||
currentLocale = new Locale(parts[0], parts[1]);
|
||||
}
|
||||
if (parts.length == 3)
|
||||
{
|
||||
currentLocale = new Locale(parts[0], parts[1], parts[2]);
|
||||
}
|
||||
Logger.getLogger("Minecraft").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
|
||||
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
|
||||
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale);
|
||||
}
|
||||
|
||||
public void updateLocale(final String loc) {
|
||||
if (loc != null && !loc.isEmpty()) {
|
||||
final String[] parts = loc.split("[_\\.]");
|
||||
if (parts.length == 1) {
|
||||
currentLocale = new Locale(parts[0]);
|
||||
}
|
||||
if (parts.length == 2) {
|
||||
currentLocale = new Locale(parts[0], parts[1]);
|
||||
}
|
||||
if (parts.length == 3) {
|
||||
currentLocale = new Locale(parts[0], parts[1], parts[2]);
|
||||
}
|
||||
}
|
||||
ResourceBundle.clearCache();
|
||||
messageFormatCache = new HashMap<String, MessageFormat>();
|
||||
Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
|
||||
|
||||
try {
|
||||
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale);
|
||||
} catch (MissingResourceException ex) {
|
||||
localeBundle = NULL_BUNDLE;
|
||||
}
|
||||
|
||||
try {
|
||||
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
|
||||
} catch (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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
private static class FileResClassLoader extends ClassLoader {
|
||||
private final transient File dataFolder;
|
||||
private static class FileResClassLoader extends ClassLoader
|
||||
{
|
||||
private final transient File dataFolder;
|
||||
|
||||
FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) {
|
||||
super(classLoader);
|
||||
this.dataFolder = ess.getDataFolder();
|
||||
}
|
||||
public FileResClassLoader(final ClassLoader classLoader, final IEssentials ess)
|
||||
{
|
||||
super(classLoader);
|
||||
this.dataFolder = ess.getDataFolder();
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getResource(final String string) {
|
||||
final File file = new File(dataFolder, string);
|
||||
if (file.exists()) {
|
||||
try {
|
||||
return file.toURI().toURL();
|
||||
} catch (MalformedURLException ex) {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public URL getResource(final String string)
|
||||
{
|
||||
final File file = new File(dataFolder, string);
|
||||
if (file.exists())
|
||||
{
|
||||
try
|
||||
{
|
||||
return file.toURI().toURL();
|
||||
}
|
||||
catch (MalformedURLException ex)
|
||||
{
|
||||
}
|
||||
}
|
||||
return super.getResource(string);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getResourceAsStream(final String string) {
|
||||
final File file = new File(dataFolder, string);
|
||||
if (file.exists()) {
|
||||
try {
|
||||
return new FileInputStream(file);
|
||||
} catch (FileNotFoundException ex) {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public InputStream getResourceAsStream(final String string)
|
||||
{
|
||||
final File file = new File(dataFolder, string);
|
||||
if (file.exists())
|
||||
{
|
||||
try
|
||||
{
|
||||
return new FileInputStream(file);
|
||||
}
|
||||
catch (FileNotFoundException ex)
|
||||
{
|
||||
}
|
||||
}
|
||||
return super.getResourceAsStream(string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
public interface IConf {
|
||||
void reloadConfig();
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
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 org.bukkit.World;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IEssentials extends Plugin {
|
||||
void addReloadListener(IConf listener);
|
||||
|
||||
void reload();
|
||||
|
||||
List<String> onTabCompleteEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module);
|
||||
|
||||
boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module);
|
||||
|
||||
@Deprecated
|
||||
User getUser(Object base);
|
||||
|
||||
User getUser(UUID base);
|
||||
|
||||
User getUser(String base);
|
||||
|
||||
User getUser(Player base);
|
||||
|
||||
I18n getI18n();
|
||||
|
||||
User getOfflineUser(String name);
|
||||
|
||||
World getWorld(String name);
|
||||
|
||||
int broadcastMessage(String message);
|
||||
|
||||
int broadcastMessage(IUser sender, String message);
|
||||
|
||||
int broadcastMessage(String permission, String message);
|
||||
|
||||
ISettings getSettings();
|
||||
|
||||
BukkitScheduler getScheduler();
|
||||
|
||||
IJails getJails();
|
||||
|
||||
IWarps getWarps();
|
||||
|
||||
Worth getWorth();
|
||||
|
||||
Backup getBackup();
|
||||
|
||||
Kits getKits();
|
||||
|
||||
Methods getPaymentMethod();
|
||||
|
||||
BukkitTask runTaskAsynchronously(Runnable run);
|
||||
|
||||
BukkitTask runTaskLaterAsynchronously(Runnable run, long delay);
|
||||
|
||||
BukkitTask runTaskTimerAsynchronously(Runnable run, long delay, long period);
|
||||
|
||||
int scheduleSyncDelayedTask(Runnable run);
|
||||
|
||||
int scheduleSyncDelayedTask(Runnable run, long delay);
|
||||
|
||||
int scheduleSyncRepeatingTask(Runnable run, long delay, long period);
|
||||
|
||||
TNTExplodeListener getTNTListener();
|
||||
|
||||
PermissionsHandler getPermissionsHandler();
|
||||
|
||||
AlternativeCommandsHandler getAlternativeCommandsHandler();
|
||||
|
||||
void showError(CommandSource sender, Throwable exception, String commandLabel);
|
||||
|
||||
IItemDb getItemDb();
|
||||
|
||||
UserMap getUserMap();
|
||||
|
||||
Metrics getMetrics();
|
||||
|
||||
void setMetrics(Metrics metrics);
|
||||
|
||||
EssentialsTimer getTimer();
|
||||
|
||||
@Deprecated
|
||||
List<String> getVanishedPlayers();
|
||||
|
||||
Collection<Player> getOnlinePlayers();
|
||||
|
||||
Iterable<User> getOnlineUsers();
|
||||
|
||||
SpawnerProvider getSpawnerProvider();
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
|
||||
public interface IEssentialsModule {
|
||||
}
|
||||
@@ -1,333 +0,0 @@
|
||||
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;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
public interface ISettings extends IConf {
|
||||
boolean areSignsDisabled();
|
||||
|
||||
IText getAnnounceNewPlayerFormat();
|
||||
|
||||
boolean getAnnounceNewPlayers();
|
||||
|
||||
String getNewPlayerKit();
|
||||
|
||||
String getBackupCommand();
|
||||
|
||||
long getBackupInterval();
|
||||
|
||||
String getChatFormat(String group);
|
||||
|
||||
int getChatRadius();
|
||||
|
||||
int getNearRadius();
|
||||
|
||||
char getChatShout();
|
||||
|
||||
char getChatQuestion();
|
||||
|
||||
BigDecimal getCommandCost(IEssentialsCommand cmd);
|
||||
|
||||
BigDecimal getCommandCost(String label);
|
||||
|
||||
String getCurrencySymbol();
|
||||
|
||||
int getOversizedStackSize();
|
||||
|
||||
int getDefaultStackSize();
|
||||
|
||||
double getHealCooldown();
|
||||
|
||||
Set<String> getSocialSpyCommands();
|
||||
|
||||
boolean getSocialSpyListenMutedPlayers();
|
||||
|
||||
Set<String> getMuteCommands();
|
||||
|
||||
/**
|
||||
* @Deprecated in favor of {@link Kits#getKits()}
|
||||
*/
|
||||
@Deprecated
|
||||
ConfigurationSection getKits();
|
||||
|
||||
/**
|
||||
* @Deprecated in favor of {@link Kits#getKit(String)}
|
||||
*/
|
||||
@Deprecated
|
||||
Map<String, Object> getKit(String kit);
|
||||
|
||||
/**
|
||||
* @Deprecated in favor of {@link Kits#addKit(String, List, long)}}
|
||||
*/
|
||||
@Deprecated
|
||||
void addKit(String name, List<String> lines, long delay);
|
||||
|
||||
@Deprecated
|
||||
ConfigurationSection getKitSection();
|
||||
|
||||
boolean isSkippingUsedOneTimeKitsFromKitList();
|
||||
|
||||
String getLocale();
|
||||
|
||||
String getNewbieSpawn();
|
||||
|
||||
String getNicknamePrefix();
|
||||
|
||||
ChatColor getOperatorColor() throws Exception;
|
||||
|
||||
boolean getPerWarpPermission();
|
||||
|
||||
boolean getProtectBoolean(final String configName, boolean def);
|
||||
|
||||
int getProtectCreeperMaxHeight();
|
||||
|
||||
List<Material> getProtectList(final String configName);
|
||||
|
||||
boolean getProtectPreventSpawn(final String creatureName);
|
||||
|
||||
String getProtectString(final String configName);
|
||||
|
||||
boolean getRespawnAtHome();
|
||||
|
||||
Set getMultipleHomes();
|
||||
|
||||
int getHomeLimit(String set);
|
||||
|
||||
int getHomeLimit(User user);
|
||||
|
||||
int getSpawnMobLimit();
|
||||
|
||||
BigDecimal getStartingBalance();
|
||||
|
||||
boolean isTeleportSafetyEnabled();
|
||||
|
||||
boolean isForceDisableTeleportSafety();
|
||||
|
||||
double getTeleportCooldown();
|
||||
|
||||
double getTeleportDelay();
|
||||
|
||||
boolean hidePermissionlessHelp();
|
||||
|
||||
boolean isCommandDisabled(final IEssentialsCommand cmd);
|
||||
|
||||
boolean isCommandDisabled(String label);
|
||||
|
||||
boolean isCommandOverridden(String name);
|
||||
|
||||
boolean isDebug();
|
||||
|
||||
boolean isEcoDisabled();
|
||||
|
||||
@Deprecated
|
||||
boolean isTradeInStacks(int id);
|
||||
|
||||
boolean isTradeInStacks(Material type);
|
||||
|
||||
List<Material> itemSpawnBlacklist();
|
||||
|
||||
List<EssentialsSign> enabledSigns();
|
||||
|
||||
boolean permissionBasedItemSpawn();
|
||||
|
||||
boolean showNonEssCommandsInHelp();
|
||||
|
||||
boolean warnOnBuildDisallow();
|
||||
|
||||
boolean warnOnSmite();
|
||||
|
||||
BigDecimal getMaxMoney();
|
||||
|
||||
BigDecimal getMinMoney();
|
||||
|
||||
boolean isEcoLogEnabled();
|
||||
|
||||
boolean isEcoLogUpdateEnabled();
|
||||
|
||||
boolean removeGodOnDisconnect();
|
||||
|
||||
boolean changeDisplayName();
|
||||
|
||||
boolean changePlayerListName();
|
||||
|
||||
boolean isPlayerCommand(String string);
|
||||
|
||||
boolean useBukkitPermissions();
|
||||
|
||||
boolean addPrefixSuffix();
|
||||
|
||||
boolean disablePrefix();
|
||||
|
||||
boolean disableSuffix();
|
||||
|
||||
long getAutoAfk();
|
||||
|
||||
long getAutoAfkKick();
|
||||
|
||||
boolean getFreezeAfkPlayers();
|
||||
|
||||
boolean cancelAfkOnMove();
|
||||
|
||||
boolean cancelAfkOnInteract();
|
||||
|
||||
boolean sleepIgnoresAfkPlayers();
|
||||
|
||||
boolean isAfkListName();
|
||||
|
||||
String getAfkListName();
|
||||
|
||||
boolean areDeathMessagesEnabled();
|
||||
|
||||
void setDebug(boolean debug);
|
||||
|
||||
Set<String> getNoGodWorlds();
|
||||
|
||||
boolean getUpdateBedAtDaytime();
|
||||
|
||||
boolean allowUnsafeEnchantments();
|
||||
|
||||
boolean getRepairEnchanted();
|
||||
|
||||
boolean isWorldTeleportPermissions();
|
||||
|
||||
boolean isWorldHomePermissions();
|
||||
|
||||
boolean registerBackInListener();
|
||||
|
||||
boolean getDisableItemPickupWhileAfk();
|
||||
|
||||
EventPriority getRespawnPriority();
|
||||
|
||||
EventPriority getSpawnJoinPriority();
|
||||
|
||||
long getTpaAcceptCancellation();
|
||||
|
||||
long getTeleportInvulnerability();
|
||||
|
||||
boolean isTeleportInvulnerability();
|
||||
|
||||
long getLoginAttackDelay();
|
||||
|
||||
int getSignUsePerSecond();
|
||||
|
||||
double getMaxFlySpeed();
|
||||
|
||||
double getMaxWalkSpeed();
|
||||
|
||||
int getMailsPerMinute();
|
||||
|
||||
long getEconomyLagWarning();
|
||||
|
||||
long getPermissionsLagWarning();
|
||||
|
||||
void setEssentialsChatActive(boolean b);
|
||||
|
||||
long getMaxTempban();
|
||||
|
||||
Map<String, Object> getListGroupConfig();
|
||||
|
||||
int getMaxNickLength();
|
||||
|
||||
boolean ignoreColorsInMaxLength();
|
||||
|
||||
boolean hideDisplayNameInVanish();
|
||||
|
||||
int getMaxUserCacheCount();
|
||||
|
||||
boolean allowSilentJoinQuit();
|
||||
|
||||
boolean isCustomJoinMessage();
|
||||
|
||||
String getCustomJoinMessage();
|
||||
|
||||
boolean isCustomQuitMessage();
|
||||
|
||||
String getCustomQuitMessage();
|
||||
|
||||
boolean isNotifyNoNewMail();
|
||||
|
||||
boolean isDropItemsIfFull();
|
||||
|
||||
boolean isLastMessageReplyRecipient();
|
||||
|
||||
BigDecimal getMinimumPayAmount();
|
||||
|
||||
long getLastMessageReplyRecipientTimeout();
|
||||
|
||||
boolean isMilkBucketEasterEggEnabled();
|
||||
|
||||
boolean isSendFlyEnableOnJoin();
|
||||
|
||||
boolean isWorldTimePermissions();
|
||||
|
||||
boolean isSpawnOnJoin();
|
||||
|
||||
List<String> getSpawnOnJoinGroups();
|
||||
|
||||
boolean isUserInSpawnOnJoinGroup(IUser user);
|
||||
|
||||
boolean isTeleportToCenterLocation();
|
||||
|
||||
boolean isCommandCooldownsEnabled();
|
||||
|
||||
long getCommandCooldownMs(String label);
|
||||
|
||||
Entry<Pattern, Long> getCommandCooldownEntry(String label);
|
||||
|
||||
boolean isCommandCooldownPersistent(String label);
|
||||
|
||||
boolean isNpcsInBalanceRanking();
|
||||
|
||||
NumberFormat getCurrencyFormat();
|
||||
|
||||
List<EssentialsSign> getUnprotectedSignNames();
|
||||
|
||||
boolean isPastebinCreateKit();
|
||||
|
||||
boolean isAllowBulkBuySell();
|
||||
|
||||
boolean isAddingPrefixInPlayerlist();
|
||||
|
||||
boolean isAddingSuffixInPlayerlist();
|
||||
|
||||
int getNotifyPlayerOfMailCooldown();
|
||||
|
||||
int getMotdDelay();
|
||||
|
||||
boolean isDirectHatAllowed();
|
||||
|
||||
List<String> getDefaultEnabledConfirmCommands();
|
||||
|
||||
boolean isConfirmCommandEnabledByDefault(String commandName);
|
||||
|
||||
boolean isTeleportBackWhenFreedFromJail();
|
||||
|
||||
boolean isCompassTowardsHomePerm();
|
||||
|
||||
boolean isAllowWorldInBroadcastworld();
|
||||
|
||||
String getItemDbType();
|
||||
|
||||
boolean isForceEnableRecipe();
|
||||
|
||||
boolean allowOldIdSigns();
|
||||
|
||||
boolean isWaterSafe();
|
||||
|
||||
boolean isSafeUsermap();
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import org.bukkit.Location;
|
||||
|
||||
|
||||
public interface ITarget {
|
||||
Location getLocation();
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.commands.IEssentialsCommand;
|
||||
import net.ess3.api.ITeleport;
|
||||
import net.ess3.api.MaxMoneyException;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
public interface IUser {
|
||||
boolean isAuthorized(String node);
|
||||
|
||||
boolean isAuthorized(IEssentialsCommand cmd);
|
||||
|
||||
boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix);
|
||||
|
||||
boolean isPermissionSet(String node);
|
||||
|
||||
void healCooldown() throws Exception;
|
||||
|
||||
void giveMoney(BigDecimal value) throws MaxMoneyException;
|
||||
|
||||
void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException;
|
||||
|
||||
void payUser(final User reciever, final BigDecimal value) throws Exception;
|
||||
|
||||
void takeMoney(BigDecimal value);
|
||||
|
||||
void takeMoney(final BigDecimal value, final CommandSource initiator);
|
||||
|
||||
boolean canAfford(BigDecimal value);
|
||||
|
||||
Boolean canSpawnItem(final Material material);
|
||||
|
||||
void setLastLocation();
|
||||
|
||||
void setLogoutLocation();
|
||||
|
||||
void requestTeleport(final User player, final boolean here);
|
||||
|
||||
/**
|
||||
* Returns whether this user has an outstanding teleport request to deal with.
|
||||
*
|
||||
* @return whether there is a teleport request
|
||||
*/
|
||||
boolean hasOutstandingTeleportRequest();
|
||||
|
||||
ITeleport getTeleport();
|
||||
|
||||
BigDecimal getMoney();
|
||||
|
||||
void setMoney(final BigDecimal value) throws MaxMoneyException;
|
||||
|
||||
void setAfk(final boolean set);
|
||||
|
||||
/**
|
||||
* '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
|
||||
*/
|
||||
boolean isHidden();
|
||||
|
||||
void setHidden(boolean vanish);
|
||||
|
||||
boolean isGodModeEnabled();
|
||||
|
||||
String getGroup();
|
||||
|
||||
boolean inGroup(final String group);
|
||||
|
||||
boolean canBuild();
|
||||
|
||||
long getTeleportRequestTime();
|
||||
|
||||
void enableInvulnerabilityAfterTeleport();
|
||||
|
||||
void resetInvulnerabilityAfterTeleport();
|
||||
|
||||
boolean hasInvulnerabilityAfterTeleport();
|
||||
|
||||
/**
|
||||
* 'Vanished' Represents when a player is hidden from others by Essentials. This status does NOT include when the
|
||||
* player is hidden via other plugins. Use isHidden() if you want to check if a user is vanished by any supported
|
||||
* plugin.
|
||||
*
|
||||
* @return If the user is vanished or not
|
||||
*
|
||||
* @see isHidden
|
||||
*/
|
||||
boolean isVanished();
|
||||
|
||||
void setVanished(boolean vanish);
|
||||
|
||||
boolean isIgnoreExempt();
|
||||
|
||||
void sendMessage(String message);
|
||||
|
||||
/*
|
||||
* UserData
|
||||
*/
|
||||
Location getHome(String name) throws Exception;
|
||||
|
||||
Location getHome(Location loc) throws Exception;
|
||||
|
||||
List<String> getHomes();
|
||||
|
||||
void setHome(String name, Location loc);
|
||||
|
||||
void delHome(String name) throws Exception;
|
||||
|
||||
boolean hasHome();
|
||||
|
||||
Location getLastLocation();
|
||||
|
||||
Location getLogoutLocation();
|
||||
|
||||
long getLastTeleportTimestamp();
|
||||
|
||||
void setLastTeleportTimestamp(long time);
|
||||
|
||||
String getJail();
|
||||
|
||||
void setJail(String jail);
|
||||
|
||||
List<String> getMails();
|
||||
|
||||
void addMail(String mail);
|
||||
|
||||
boolean isAfk();
|
||||
|
||||
void setIgnoreMsg(boolean ignoreMsg);
|
||||
|
||||
boolean isIgnoreMsg();
|
||||
|
||||
void setConfigProperty(String node, Object object);
|
||||
|
||||
Set<String> getConfigKeys();
|
||||
|
||||
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);
|
||||
|
||||
/*
|
||||
* PlayerExtension
|
||||
*/
|
||||
Player getBase();
|
||||
|
||||
CommandSource getSource();
|
||||
|
||||
String getName();
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.storage.ManagedFile;
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.IItemDb;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.perm.Permissions;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.Cleanup;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
|
||||
public class ItemDb implements IItemDb
|
||||
{
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public ItemDb(final IEssentials ess)
|
||||
{
|
||||
this.ess = ess;
|
||||
file = new ManagedFile("items.csv", ess);
|
||||
}
|
||||
private final transient Map<String, Long> items = new HashMap<String, Long>();
|
||||
private final transient ManagedFile file;
|
||||
private static final Pattern SPLIT = Pattern.compile("[^a-zA-Z0-9]");
|
||||
|
||||
@Override
|
||||
public void onReload()
|
||||
{
|
||||
final List<String> lines = file.getLines();
|
||||
|
||||
if (lines.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
items.clear();
|
||||
|
||||
for (String line : lines)
|
||||
{
|
||||
line = line.trim();
|
||||
if (line.length() > 0 && line.charAt(0) == '#')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
final String[] parts = SPLIT.split(line);
|
||||
if (parts.length < 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
final long numeric = Integer.parseInt(parts[1]);
|
||||
|
||||
final long durability = parts.length > 2 && !(parts[2].length() == 1 && parts[2].charAt(0) == '0') ? Short.parseShort(parts[2]) : 0;
|
||||
items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric | (durability << 32));
|
||||
}
|
||||
}
|
||||
|
||||
public ItemStack get(final String id, final IUser user) throws Exception
|
||||
{
|
||||
final ItemStack stack = get(id.toLowerCase(Locale.ENGLISH));
|
||||
|
||||
@Cleanup
|
||||
com.earth2me.essentials.api.ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
|
||||
final int defaultStackSize = settings.getData().getGeneral().getDefaultStacksize();
|
||||
|
||||
if (defaultStackSize > 0)
|
||||
{
|
||||
stack.setAmount(defaultStackSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
final int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize();
|
||||
if (oversizedStackSize > 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user))
|
||||
{
|
||||
stack.setAmount(oversizedStackSize);
|
||||
}
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
public ItemStack get(final String id, final int quantity) throws Exception
|
||||
{
|
||||
final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH));
|
||||
retval.setAmount(quantity);
|
||||
return retval;
|
||||
}
|
||||
|
||||
public ItemStack get(final String id) throws Exception
|
||||
{
|
||||
int itemid = 0;
|
||||
String itemname = null;
|
||||
short metaData = 0;
|
||||
if (id.matches("^\\d+[:+',;.]\\d+$"))
|
||||
{
|
||||
itemid = Integer.parseInt(id.split("[:+',;.]")[0]);
|
||||
metaData = Short.parseShort(id.split("[:+',;.]")[1]);
|
||||
}
|
||||
else if (id.matches("^\\d+$"))
|
||||
{
|
||||
itemid = Integer.parseInt(id);
|
||||
}
|
||||
else if (id.matches("^[^:+',;.]+[:+',;.]\\d+$"))
|
||||
{
|
||||
itemname = id.split("[:+',;.]")[0].toLowerCase(Locale.ENGLISH);
|
||||
metaData = Short.parseShort(id.split("[:+',;.]")[1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
itemname = id.toLowerCase(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
if (itemname != null)
|
||||
{
|
||||
if (items.containsKey(itemname))
|
||||
{
|
||||
long item = items.get(itemname);
|
||||
itemid = (int)(item & 0xffffffffL);
|
||||
if (metaData == 0)
|
||||
{
|
||||
metaData = (short)((item >> 32) & 0xffffL);
|
||||
}
|
||||
}
|
||||
else if (Material.getMaterial(itemname) != null)
|
||||
{
|
||||
itemid = Material.getMaterial(itemname).getId();
|
||||
metaData = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception(_("unknownItemName", id));
|
||||
}
|
||||
}
|
||||
|
||||
final Material mat = Material.getMaterial(itemid);
|
||||
if (mat == null)
|
||||
{
|
||||
throw new Exception(_("unknownItemId", itemid));
|
||||
}
|
||||
final ItemStack retval = new ItemStack(mat);
|
||||
retval.setAmount(mat.getMaxStackSize());
|
||||
retval.setDurability(metaData);
|
||||
return retval;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.IJails;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
|
||||
import net.ess3.api.IEssentials;
|
||||
import net.ess3.api.IUser;
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import lombok.Cleanup;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
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.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
@@ -23,242 +25,277 @@ import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
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 IJails
|
||||
{
|
||||
private static final transient Logger LOGGER = Bukkit.getLogger();
|
||||
|
||||
public Jails(final IEssentials ess)
|
||||
{
|
||||
super(ess, com.earth2me.essentials.settings.Jails.class);
|
||||
onReload();
|
||||
registerListeners();
|
||||
}
|
||||
|
||||
private void registerListeners()
|
||||
{
|
||||
final PluginManager pluginManager = ess.getServer().getPluginManager();
|
||||
final JailBlockListener blockListener = new JailBlockListener();
|
||||
final JailPlayerListener playerListener = new JailPlayerListener();
|
||||
pluginManager.registerEvents(blockListener, ess);
|
||||
pluginManager.registerEvents(playerListener, ess);
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getStorageFile()
|
||||
{
|
||||
return new File(ess.getDataFolder(), "jail.yml");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location getJail(final String jailName) throws Exception
|
||||
{
|
||||
acquireReadLock();
|
||||
try
|
||||
{
|
||||
if (getData().getJails() == null || jailName == null
|
||||
|| !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH)))
|
||||
{
|
||||
throw new Exception(_("jailNotExist"));
|
||||
}
|
||||
Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)).getBukkitLocation();
|
||||
if (loc == null || loc.getWorld() == null)
|
||||
{
|
||||
throw new Exception(_("jailNotExist"));
|
||||
}
|
||||
return loc;
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getList() throws Exception
|
||||
{
|
||||
acquireReadLock();
|
||||
try
|
||||
{
|
||||
if (getData().getJails() == null)
|
||||
{
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return new ArrayList<String>(getData().getJails().keySet());
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeJail(final String jail) throws Exception
|
||||
{
|
||||
acquireWriteLock();
|
||||
try
|
||||
{
|
||||
if (getData().getJails() == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToJail(final IUser user, final String jail) throws Exception
|
||||
{
|
||||
acquireReadLock();
|
||||
try
|
||||
{
|
||||
if (!(user.isOnline()))
|
||||
{
|
||||
Location loc = getJail(jail);
|
||||
user.getTeleport().now(loc, false, TeleportCause.COMMAND);
|
||||
}
|
||||
user.acquireWriteLock();
|
||||
try
|
||||
{
|
||||
user.getData().setJail(jail);
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
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, com.earth2me.essentials.storage.Location>());
|
||||
}
|
||||
getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.Location(loc));
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
private class JailBlockListener implements Listener
|
||||
{
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onBlockBreak(final BlockBreakEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (user.getData().isJailed())
|
||||
{
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
public Jails(final IEssentials ess) {
|
||||
super(ess, com.earth2me.essentials.settings.Jails.class);
|
||||
reloadConfig();
|
||||
}
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onBlockPlace(final BlockPlaceEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (user.getData().isJailed())
|
||||
{
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void registerListeners() {
|
||||
enabled = true;
|
||||
final PluginManager pluginManager = ess.getServer().getPluginManager();
|
||||
final JailListener blockListener = new JailListener();
|
||||
pluginManager.registerEvents(blockListener, ess);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
LOGGER.log(Level.INFO, "Registering Jail listener");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getStorageFile() {
|
||||
return new File(ess.getDataFolder(), "jail.yml");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finishRead() {
|
||||
checkRegister();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finishWrite() {
|
||||
checkRegister();
|
||||
}
|
||||
|
||||
public void resetListener() {
|
||||
enabled = false;
|
||||
checkRegister();
|
||||
}
|
||||
|
||||
private void checkRegister() {
|
||||
if (enabled == false && getCount() > 0) {
|
||||
registerListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location getJail(final String jailName) throws Exception {
|
||||
acquireReadLock();
|
||||
try {
|
||||
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));
|
||||
if (loc == null || loc.getWorld() == null) {
|
||||
throw new Exception(tl("jailNotExist"));
|
||||
}
|
||||
return loc;
|
||||
} finally {
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getList() throws Exception {
|
||||
acquireReadLock();
|
||||
try {
|
||||
if (getData().getJails() == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return new ArrayList<String>(getData().getJails().keySet());
|
||||
} finally {
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeJail(final String jail) throws Exception {
|
||||
acquireWriteLock();
|
||||
try {
|
||||
if (getData().getJails() == null) {
|
||||
return;
|
||||
}
|
||||
getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH));
|
||||
} finally {
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToJail(final IUser user, final String jail) throws Exception {
|
||||
acquireReadLock();
|
||||
try {
|
||||
if (user.getBase().isOnline()) {
|
||||
Location loc = getJail(jail);
|
||||
user.getTeleport().now(loc, false, TeleportCause.COMMAND);
|
||||
}
|
||||
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().getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
|
||||
} finally {
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
try {
|
||||
return getList().size();
|
||||
} catch (Exception ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onBlockDamage(final BlockDamageEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (user.getData().isJailed())
|
||||
{
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
private class JailPlayerListener implements Listener
|
||||
{
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onPlayerInteract(final PlayerInteractEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (user.getData().isJailed())
|
||||
{
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onJailBlockPlace(final BlockPlaceEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isJailed()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onPlayerRespawn(final PlayerRespawnEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onJailBlockDamage(final BlockDamageEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isJailed()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
event.setRespawnLocation(getJail(user.getData().getJail()));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ess.getSettings().isDebug())
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onJailEntityDamageByEntity(final EntityDamageByEntityEvent event) {
|
||||
if (event.getCause() != DamageCause.ENTITY_ATTACK || event.getEntity().getType() != EntityType.PLAYER) {
|
||||
return;
|
||||
}
|
||||
final Entity damager = event.getDamager();
|
||||
if (damager.getType() == EntityType.PLAYER) {
|
||||
final User user = ess.getUser((Player) damager);
|
||||
if (user != null && user.isJailed()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onPlayerTeleport(final PlayerTeleportEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onJailPlayerInteract(final PlayerInteractEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (user.isJailed()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
event.setTo(getJail(user.getData().getJail()));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ess.getSettings().isDebug())
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
|
||||
}
|
||||
}
|
||||
user.sendMessage(_("jailMessage"));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onJailPlayerRespawn(final PlayerRespawnEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onPlayerJoin(final PlayerJoinEvent event)
|
||||
{
|
||||
@Cleanup
|
||||
final IUser user = ess.getUser(event.getPlayer());
|
||||
user.acquireReadLock();
|
||||
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
event.setRespawnLocation(getJail(user.getJail()));
|
||||
} catch (Exception 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onJailPlayerTeleport(final PlayerTeleportEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
event.setTo(getJail(user.getJail()));
|
||||
} catch (Exception 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()));
|
||||
}
|
||||
}
|
||||
user.sendMessage(tl("jailMessage"));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onJailPlayerJoin(final PlayerJoinEvent event) {
|
||||
final User user = ess.getUser(event.getPlayer());
|
||||
final long currentTime = System.currentTimeMillis();
|
||||
user.checkJailTimeout(currentTime);
|
||||
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
sendToJail(user, user.getJail());
|
||||
} catch (Exception 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()));
|
||||
}
|
||||
}
|
||||
user.sendMessage(tl("jailMessage"));
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
sendToJail(user, user.getData().getJail());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ess.getSettings().isDebug())
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
|
||||
}
|
||||
}
|
||||
user.sendMessage(_("jailMessage"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.Trade.OverflowType;
|
||||
import com.earth2me.essentials.commands.NoChargeException;
|
||||
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
|
||||
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 net.ess3.api.IEssentials;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
public class Kit {
|
||||
final IEssentials ess;
|
||||
final String kitName;
|
||||
final Map<String, Object> kit;
|
||||
final Trade charge;
|
||||
|
||||
public Kit(final String kitName, final IEssentials ess) throws Exception {
|
||||
this.kitName = kitName;
|
||||
this.ess = ess;
|
||||
this.kit = ess.getKits().getKit(kitName);
|
||||
this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess);
|
||||
|
||||
if (kit == null) {
|
||||
throw new Exception(tl("kitNotFound"));
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return kitName;
|
||||
}
|
||||
|
||||
public void checkPerms(final User user) throws Exception {
|
||||
if (!user.isAuthorized("essentials.kits." + kitName)) {
|
||||
throw new Exception(tl("noKitPermission", "essentials.kits." + kitName));
|
||||
}
|
||||
}
|
||||
|
||||
public void checkDelay(final User user) throws Exception {
|
||||
long nextUse = getNextUse(user);
|
||||
|
||||
if (nextUse == 0L) {
|
||||
return;
|
||||
} else if (nextUse < 0L) {
|
||||
user.sendMessage(tl("kitOnce"));
|
||||
throw new NoChargeException();
|
||||
} else {
|
||||
user.sendMessage(tl("kitTimed", DateUtil.formatDateDiff(nextUse)));
|
||||
throw new NoChargeException();
|
||||
}
|
||||
}
|
||||
|
||||
public void checkAffordable(final User user) throws Exception {
|
||||
charge.isAffordableFor(user);
|
||||
}
|
||||
|
||||
public void setTime(final User user) throws Exception {
|
||||
final Calendar time = new GregorianCalendar();
|
||||
user.setKitTimestamp(kitName, time.getTimeInMillis());
|
||||
}
|
||||
|
||||
public void chargeUser(final User user) throws Exception {
|
||||
charge.charge(user);
|
||||
}
|
||||
|
||||
public long getNextUse(final User user) throws Exception {
|
||||
if (user.isAuthorized("essentials.kit.exemptdelay")) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
final Calendar time = new GregorianCalendar();
|
||||
|
||||
double delay = 0;
|
||||
try {
|
||||
// Make sure delay is valid
|
||||
delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d;
|
||||
} catch (Exception e) {
|
||||
throw new Exception(tl("kitError2"));
|
||||
}
|
||||
|
||||
// When was the last kit used?
|
||||
final long lastTime = user.getKitTimestamp(kitName);
|
||||
|
||||
// When can be use the kit again?
|
||||
final Calendar delayTime = new GregorianCalendar();
|
||||
delayTime.setTimeInMillis(lastTime);
|
||||
delayTime.add(Calendar.SECOND, (int) delay);
|
||||
delayTime.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));
|
||||
|
||||
if (lastTime == 0L || lastTime > time.getTimeInMillis()) {
|
||||
// If we have no record of kit use, or its corrupted, give them benefit of the doubt.
|
||||
return 0L;
|
||||
} else if (delay < 0d) {
|
||||
// If the kit has a negative kit time, it can only be used once.
|
||||
return -1;
|
||||
} else if (delayTime.before(time)) {
|
||||
// If the kit was used in the past, but outside the delay time, it can be used.
|
||||
return 0L;
|
||||
} else {
|
||||
// If the kit has been used recently, return the next time it can be used.
|
||||
return delayTime.getTimeInMillis();
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public List<String> getItems(final User user) throws Exception {
|
||||
return getItems();
|
||||
}
|
||||
|
||||
public List<String> getItems() throws Exception {
|
||||
if (kit == null) {
|
||||
throw new Exception(tl("kitNotFound"));
|
||||
}
|
||||
try {
|
||||
final List<String> itemList = new ArrayList<String>();
|
||||
final Object kitItems = kit.get("items");
|
||||
if (kitItems instanceof List) {
|
||||
for (Object item : (List) kitItems) {
|
||||
if (item instanceof String) {
|
||||
itemList.add(item.toString());
|
||||
continue;
|
||||
}
|
||||
throw new Exception("Invalid kit item: " + item.toString());
|
||||
}
|
||||
return itemList;
|
||||
}
|
||||
throw new Exception("Invalid item list");
|
||||
} catch (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 void 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);
|
||||
|
||||
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);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (kitItem.startsWith("/")) {
|
||||
String command = kitItem.substring(1);
|
||||
String name = user.getName();
|
||||
command = command.replace("{player}", name);
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
|
||||
continue;
|
||||
}
|
||||
|
||||
final String[] parts = kitItem.split(" +");
|
||||
final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1);
|
||||
|
||||
if (parseStack.getType() == Material.AIR) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final MetaItemStack metaStack = new MetaItemStack(parseStack);
|
||||
|
||||
if (parts.length > 2) {
|
||||
// We pass a null sender here because kits should not do perm checks
|
||||
metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess);
|
||||
}
|
||||
|
||||
final Map<Integer, ItemStack> overfilled;
|
||||
final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks");
|
||||
if (allowOversizedStacks) {
|
||||
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack());
|
||||
} else {
|
||||
overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack());
|
||||
}
|
||||
for (ItemStack itemStack : overfilled.values()) {
|
||||
int spillAmount = itemStack.getAmount();
|
||||
if (!allowOversizedStacks) {
|
||||
itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize());
|
||||
}
|
||||
while (spillAmount > 0) {
|
||||
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
|
||||
spillAmount -= itemStack.getAmount();
|
||||
}
|
||||
spew = true;
|
||||
}
|
||||
}
|
||||
user.getBase().updateInventory();
|
||||
if (spew) {
|
||||
user.sendMessage(tl("kitInvFull"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
user.getBase().updateInventory();
|
||||
ess.getLogger().log(Level.WARNING, e.getMessage());
|
||||
throw new Exception(tl("kitError2"), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,114 +1,90 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.NumberUtil;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.IKits;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.settings.Kit;
|
||||
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
|
||||
import java.io.File;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import static com.earth2me.essentials.I18n.capitalCase;
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
public class Kits implements IConf {
|
||||
public class Kits extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Kits> implements IKits
|
||||
{
|
||||
public Kits(final IEssentials ess)
|
||||
{
|
||||
super(ess, com.earth2me.essentials.settings.Kits.class);
|
||||
onReload();
|
||||
}
|
||||
|
||||
private final EssentialsConf config;
|
||||
private ConfigurationSection kits;
|
||||
@Override
|
||||
public File getStorageFile() throws IOException
|
||||
{
|
||||
return new File(ess.getDataFolder(), "kits.yml");
|
||||
}
|
||||
|
||||
public Kits(final IEssentials essentials) {
|
||||
config = new EssentialsConf(new File(essentials.getDataFolder(), "kits.yml"));
|
||||
config.setTemplateName("/kits.yml");
|
||||
@Override
|
||||
public Kit getKit(String kitName) throws Exception
|
||||
{
|
||||
acquireReadLock();
|
||||
try
|
||||
{
|
||||
if (getData().getKits() == null || kitName == null
|
||||
|| !getData().getKits().containsKey(kitName.toLowerCase(Locale.ENGLISH)))
|
||||
{
|
||||
throw new Exception(_("kitError2"));
|
||||
}
|
||||
final Kit kit = getData().getKits().get(kitName.toLowerCase(Locale.ENGLISH));
|
||||
if (kit == null)
|
||||
{
|
||||
throw new Exception(_("kitError2"));
|
||||
}
|
||||
return kit;
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig();
|
||||
}
|
||||
@Override
|
||||
public void sendKit(IUser user, String kitName) throws Exception
|
||||
{
|
||||
final Kit kit = getKit(kitName);
|
||||
sendKit(user, kit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
config.load();
|
||||
kits = _getKits();
|
||||
}
|
||||
@Override
|
||||
public void sendKit(IUser user, Kit kit) throws Exception
|
||||
{
|
||||
final List<ItemStack> itemList = kit.getItems();
|
||||
user.giveItems(itemList, true);
|
||||
}
|
||||
|
||||
private ConfigurationSection _getKits() {
|
||||
if (config.isConfigurationSection("kits")) {
|
||||
final ConfigurationSection section = config.getConfigurationSection("kits");
|
||||
final ConfigurationSection newSection = new MemoryConfiguration();
|
||||
for (String kitItem : section.getKeys(false)) {
|
||||
if (section.isConfigurationSection(kitItem)) {
|
||||
newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem));
|
||||
}
|
||||
}
|
||||
return newSection;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Collection<String> getList() throws Exception
|
||||
{
|
||||
acquireReadLock();
|
||||
try
|
||||
{
|
||||
if (getData().getKits() == null)
|
||||
{
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return new ArrayList<String>(getData().getKits().keySet());
|
||||
}
|
||||
finally
|
||||
{
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public EssentialsConf getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public ConfigurationSection getKits() {
|
||||
return kits;
|
||||
}
|
||||
|
||||
public Map<String, Object> getKit(String name) {
|
||||
name = name.replace('.', '_').replace('/', '_');
|
||||
if (getKits() != null) {
|
||||
final ConfigurationSection kits = getKits();
|
||||
// For some reason, YAML doesn't sees keys as always lowercase even if they aren't defined like that.
|
||||
// Workaround is to toLowercase when getting from the config, but showing normally elsewhere.
|
||||
// ODDLY ENOUGH when you get the configuration section for ALL kits, it will return the proper
|
||||
// case of each kit. But when you check for each kit's configuration section, it won't return the kit
|
||||
// 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) {
|
||||
// Will overwrite but w/e
|
||||
config.set("kits." + name + ".delay", delay);
|
||||
config.set("kits." + name + ".items", lines);
|
||||
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)) {
|
||||
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);
|
||||
if (costPrice.signum() > 0) {
|
||||
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
|
||||
}
|
||||
|
||||
Kit kit = new Kit(kitItem, ess);
|
||||
double nextUse = kit.getNextUse(user);
|
||||
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
|
||||
continue;
|
||||
} else if (nextUse != 0) {
|
||||
name = tl("kitDelay", name);
|
||||
}
|
||||
|
||||
list.append(" ").append(name).append(cost);
|
||||
}
|
||||
}
|
||||
return list.toString().trim();
|
||||
} catch (Exception ex) {
|
||||
throw new Exception(tl("kitError"), ex);
|
||||
}
|
||||
|
||||
}
|
||||
@Override
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return getData().getKits().isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import org.bukkit.Location;
|
||||
|
||||
|
||||
public class LocationTarget implements ITarget {
|
||||
private final Location location;
|
||||
|
||||
LocationTarget(Location location) {
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location getLocation() {
|
||||
return location;
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.security.DigestInputStream;
|
||||
import java.security.DigestOutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
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;
|
||||
|
||||
public ManagedFile(final String filename, final IEssentials ess) {
|
||||
file = new File(ess.getDataFolder(), filename);
|
||||
|
||||
if (file.exists()) {
|
||||
try {
|
||||
if (checkForVersion(file, ess.getDescription().getVersion()) && !file.delete()) {
|
||||
throw new IOException("Could not delete file " + file.toString());
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (!file.exists()) {
|
||||
try {
|
||||
copyResourceAscii("/" + filename, file);
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded"), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyResourceAscii(final String resourceName, final File file) throws IOException {
|
||||
final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName));
|
||||
try {
|
||||
final MessageDigest digest = getDigest();
|
||||
final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest);
|
||||
try {
|
||||
final OutputStreamWriter writer = new OutputStreamWriter(digestStream);
|
||||
try {
|
||||
final char[] buffer = new char[BUFFERSIZE];
|
||||
do {
|
||||
final int length = reader.read(buffer);
|
||||
if (length >= 0) {
|
||||
writer.write(buffer, 0, length);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
writer.write("\n");
|
||||
writer.flush();
|
||||
final BigInteger hashInt = new BigInteger(1, digest.digest());
|
||||
digestStream.on(false);
|
||||
digestStream.write('#');
|
||||
digestStream.write(hashInt.toString(16).getBytes());
|
||||
} finally {
|
||||
writer.close();
|
||||
}
|
||||
} finally {
|
||||
digestStream.close();
|
||||
}
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean checkForVersion(final File file, final String version) throws IOException {
|
||||
if (file.length() < 33) {
|
||||
return false;
|
||||
}
|
||||
final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
|
||||
try {
|
||||
final byte[] buffer = new byte[(int) file.length()];
|
||||
int position = 0;
|
||||
do {
|
||||
final int length = bis.read(buffer, position, Math.min((int) file.length() - position, BUFFERSIZE));
|
||||
if (length < 0) {
|
||||
break;
|
||||
}
|
||||
position += length;
|
||||
} while (position < file.length());
|
||||
final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
|
||||
if (bais.skip(file.length() - 33) != file.length() - 33) {
|
||||
return false;
|
||||
}
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
|
||||
try {
|
||||
String hash = reader.readLine();
|
||||
if (hash != null && hash.matches("#[a-f0-9]{32}")) {
|
||||
hash = hash.substring(1);
|
||||
bais.reset();
|
||||
final String versionline = reader.readLine();
|
||||
if (versionline != null && versionline.matches("#version: .+")) {
|
||||
final String versioncheck = versionline.substring(10);
|
||||
if (!versioncheck.equalsIgnoreCase(version)) {
|
||||
bais.reset();
|
||||
final MessageDigest digest = getDigest();
|
||||
final DigestInputStream digestStream = new DigestInputStream(bais, digest);
|
||||
try {
|
||||
final byte[] bytes = new byte[(int) file.length() - 33];
|
||||
digestStream.read(bytes);
|
||||
final BigInteger correct = new BigInteger(hash, 16);
|
||||
final BigInteger test = new BigInteger(1, digest.digest());
|
||||
if (correct.equals(test)) {
|
||||
return true;
|
||||
} 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;
|
||||
}
|
||||
|
||||
public static MessageDigest getDigest() throws IOException {
|
||||
try {
|
||||
return MessageDigest.getInstance("MD5");
|
||||
} catch (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>();
|
||||
do {
|
||||
final String line = reader.readLine();
|
||||
if (line == null) {
|
||||
break;
|
||||
} else {
|
||||
lines.add(line);
|
||||
}
|
||||
} while (true);
|
||||
return lines;
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,587 +0,0 @@
|
||||
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;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Banner;
|
||||
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.potion.Potion;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
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<>();
|
||||
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<>();
|
||||
|
||||
static {
|
||||
for (DyeColor color : DyeColor.values()) {
|
||||
colorMap.put(color.name(), color);
|
||||
}
|
||||
for (FireworkEffect.Type type : FireworkEffect.Type.values()) {
|
||||
fireworkShape.put(type.name(), type);
|
||||
}
|
||||
}
|
||||
|
||||
private final transient Pattern splitPattern = Pattern.compile("[:+',;.]");
|
||||
private ItemStack stack;
|
||||
private FireworkEffect.Builder builder = FireworkEffect.builder();
|
||||
private PotionEffectType pEffectType;
|
||||
private PotionEffect pEffect;
|
||||
private boolean validFirework = false;
|
||||
private boolean validPotionEffect = false;
|
||||
private boolean validPotionDuration = false;
|
||||
private boolean validPotionPower = false;
|
||||
private boolean isSplashPotion = false;
|
||||
private boolean completePotion = false;
|
||||
private int power = 1;
|
||||
private int duration = 120;
|
||||
|
||||
public MetaItemStack(final ItemStack stack) {
|
||||
this.stack = stack.clone();
|
||||
}
|
||||
|
||||
public ItemStack getItemStack() {
|
||||
return stack;
|
||||
}
|
||||
|
||||
public boolean isValidFirework() {
|
||||
return validFirework;
|
||||
}
|
||||
|
||||
public boolean isValidPotion() {
|
||||
return validPotionEffect && validPotionDuration && validPotionPower;
|
||||
}
|
||||
|
||||
public FireworkEffect.Builder getFireworkBuilder() {
|
||||
return builder;
|
||||
}
|
||||
|
||||
public PotionEffect getPotionEffect() {
|
||||
return pEffect;
|
||||
}
|
||||
|
||||
public boolean completePotion() {
|
||||
return completePotion;
|
||||
}
|
||||
|
||||
private void resetPotionMeta() {
|
||||
pEffect = null;
|
||||
pEffectType = null;
|
||||
validPotionEffect = false;
|
||||
validPotionDuration = false;
|
||||
validPotionPower = false;
|
||||
isSplashPotion = false;
|
||||
completePotion = true;
|
||||
}
|
||||
|
||||
public boolean canSpawn(final IEssentials ess) {
|
||||
try {
|
||||
ess.getServer().getUnsafe().modifyItemStack(stack.clone(), "{}");
|
||||
return true;
|
||||
} catch (NullPointerException 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 {
|
||||
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) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
|
||||
}
|
||||
} catch (NoSuchMethodError nsme) {
|
||||
throw new Exception(tl("noMetaJson"), nsme);
|
||||
} catch (Throwable throwable) {
|
||||
throw new Exception(throwable.getMessage(), throwable);
|
||||
}
|
||||
} else {
|
||||
for (int i = fromArg; i < string.length; i++) {
|
||||
addStringMeta(sender, allowUnsafe, string[i], ess);
|
||||
}
|
||||
if (validFirework) {
|
||||
if (!hasMetaPermission(sender, "firework", true, true, ess)) {
|
||||
throw new Exception(tl("noMetaFirework"));
|
||||
}
|
||||
FireworkEffect effect = builder.build();
|
||||
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"));
|
||||
}
|
||||
stack.setItemMeta(fmeta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addStringMeta(final CommandSource sender, final boolean allowUnsafe, final String string, final IEssentials ess) throws Exception {
|
||||
final String[] split = splitPattern.split(string, 2);
|
||||
if (split.length < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
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('_', ' '));
|
||||
final ItemMeta meta = stack.getItemMeta();
|
||||
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 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;
|
||||
setUnbreakable(stack, value);
|
||||
} 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.setOwningPlayer(ess.getServer().getOfflinePlayer(owner));
|
||||
stack.setItemMeta(meta);
|
||||
} else {
|
||||
throw new Exception(tl("onlyPlayerSkulls"));
|
||||
}
|
||||
} 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]);
|
||||
meta.setPages(pages);
|
||||
stack.setItemMeta(meta);
|
||||
} 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() == 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") && (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 (MaterialUtil.isFirework(stack.getType())) {
|
||||
//WARNING - Meta for fireworks will be ignored after this point.
|
||||
addFireworkMeta(sender, false, string, ess);
|
||||
} else if (MaterialUtil.isPotion(stack.getType())) {
|
||||
//WARNING - Meta for potions will be ignored after this point.
|
||||
addPotionMeta(sender, false, string, ess);
|
||||
} 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("#"))) {
|
||||
// Either integer or hexadecimal
|
||||
final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta();
|
||||
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 { // Int
|
||||
meta.setColor(Color.fromRGB(Integer.parseInt(input)));
|
||||
}
|
||||
stack.setItemMeta(meta);
|
||||
} else if (color.length == 3) { // r,g,b
|
||||
final int red = NumberUtil.isInt(color[0]) ? Integer.parseInt(color[0]) : 0;
|
||||
final int green = NumberUtil.isInt(color[1]) ? Integer.parseInt(color[1]) : 0;
|
||||
final int blue = NumberUtil.isInt(color[2]) ? Integer.parseInt(color[2]) : 0;
|
||||
final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta();
|
||||
meta.setColor(Color.fromRGB(red, green, blue));
|
||||
stack.setItemMeta(meta);
|
||||
} else {
|
||||
throw new Exception(tl("leatherSyntax"));
|
||||
}
|
||||
} else {
|
||||
parseEnchantmentStrings(sender, allowUnsafe, split, ess);
|
||||
}
|
||||
}
|
||||
|
||||
public void addItemFlags(final String string) throws Exception {
|
||||
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();
|
||||
|
||||
for (String s : split) {
|
||||
for (ItemFlag flag : ItemFlag.values()) {
|
||||
if (s.equalsIgnoreCase(flag.name())) {
|
||||
meta.addItemFlags(flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (meta.getItemFlags().isEmpty()) {
|
||||
throw new Exception(tl("invalidItemFlagMeta", string));
|
||||
}
|
||||
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
|
||||
public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
|
||||
if (MaterialUtil.isFirework(stack.getType())) {
|
||||
final String[] split = splitPattern.split(string, 2);
|
||||
if (split.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c"))) {
|
||||
if (validFirework) {
|
||||
if (!hasMetaPermission(sender, "firework", true, true, ess)) {
|
||||
throw new Exception(tl("noMetaFirework"));
|
||||
}
|
||||
FireworkEffect effect = builder.build();
|
||||
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"));
|
||||
}
|
||||
stack.setItemMeta(fmeta);
|
||||
builder = FireworkEffect.builder();
|
||||
}
|
||||
|
||||
List<Color> primaryColors = new ArrayList<Color>();
|
||||
String[] colors = split[1].split(",");
|
||||
for (String color : colors) {
|
||||
if (colorMap.containsKey(color.toUpperCase())) {
|
||||
validFirework = true;
|
||||
primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
|
||||
} else {
|
||||
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
|
||||
}
|
||||
}
|
||||
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]);
|
||||
if (fireworkShape.containsKey(split[1].toUpperCase())) {
|
||||
finalEffect = fireworkShape.get(split[1].toUpperCase());
|
||||
} else {
|
||||
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
|
||||
}
|
||||
if (finalEffect != null) {
|
||||
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) {
|
||||
if (colorMap.containsKey(color.toUpperCase())) {
|
||||
fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
|
||||
} else {
|
||||
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
|
||||
}
|
||||
}
|
||||
if (!fadeColors.isEmpty()) {
|
||||
builder.withFade(fadeColors);
|
||||
}
|
||||
} else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) {
|
||||
String[] effects = split[1].split(",");
|
||||
for (String effect : effects) {
|
||||
if (effect.equalsIgnoreCase("twinkle")) {
|
||||
builder.flicker(true);
|
||||
} else if (effect.equalsIgnoreCase("trail")) {
|
||||
builder.trail(true);
|
||||
} else {
|
||||
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
|
||||
if (MaterialUtil.isPotion(stack.getType())) {
|
||||
final String[] split = splitPattern.split(string, 2);
|
||||
|
||||
if (split.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) {
|
||||
pEffectType = Potions.getByName(split[1]);
|
||||
if (pEffectType != null && pEffectType.getName() != null) {
|
||||
if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess)) {
|
||||
validPotionEffect = true;
|
||||
} else {
|
||||
throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH)));
|
||||
}
|
||||
} else {
|
||||
throw new Exception(tl("invalidPotionMeta", split[1]));
|
||||
}
|
||||
} else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p"))) {
|
||||
if (NumberUtil.isInt(split[1])) {
|
||||
validPotionPower = true;
|
||||
power = Integer.parseInt(split[1]);
|
||||
if (power > 0 && power < 4) {
|
||||
power -= 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;
|
||||
duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds
|
||||
} else {
|
||||
throw new Exception(tl("invalidPotionMeta", split[1]));
|
||||
}
|
||||
} else if (split[0].equalsIgnoreCase("splash") || (allowShortName && split[0].equalsIgnoreCase("s"))) {
|
||||
isSplashPotion = Boolean.valueOf(split[1]);
|
||||
}
|
||||
|
||||
if (isValidPotion()) {
|
||||
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"));
|
||||
}
|
||||
pmeta.addCustomEffect(pEffect, true);
|
||||
stack.setItemMeta(pmeta);
|
||||
if (ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_9_R1)) {
|
||||
if (isSplashPotion && stack.getType() != Material.SPLASH_POTION) {
|
||||
stack.setType(Material.SPLASH_POTION);
|
||||
} else if (!isSplashPotion && stack.getType() != Material.POTION) {
|
||||
stack.setType(Material.POTION);
|
||||
}
|
||||
} else {
|
||||
Potion potion = Potion.fromItemStack(stack);
|
||||
potion.setSplash(isSplashPotion);
|
||||
potion.apply(stack);
|
||||
}
|
||||
resetPotionMeta();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void parseEnchantmentStrings(final CommandSource sender, final boolean allowUnsafe, final String[] split, final IEssentials ess) throws Exception {
|
||||
final Enchantment enchantment = Enchantments.getByName(split[0]);
|
||||
if (enchantment == null || !hasMetaPermission(sender, "enchantments." + enchantment.getName().toLowerCase(Locale.ENGLISH), false, false, ess)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int level = -1;
|
||||
if (split.length > 1) {
|
||||
try {
|
||||
level = Integer.parseInt(split[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
level = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel())) {
|
||||
level = enchantment.getMaxLevel();
|
||||
}
|
||||
addEnchantment(sender, allowUnsafe, enchantment, level);
|
||||
}
|
||||
|
||||
public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception {
|
||||
if (enchantment == null) {
|
||||
throw new Exception(tl("enchantmentNotFound"));
|
||||
}
|
||||
try {
|
||||
if (stack.getType().equals(Material.ENCHANTED_BOOK)) {
|
||||
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
|
||||
{
|
||||
if (level == 0) {
|
||||
stack.removeEnchantment(enchantment);
|
||||
} else {
|
||||
if (allowUnsafe) {
|
||||
stack.addUnsafeEnchantment(enchantment, level);
|
||||
} else {
|
||||
stack.addEnchantment(enchantment, level);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
public Enchantment getEnchantment(final User user, final String name) throws Exception {
|
||||
final Enchantment enchantment = Enchantments.getByName(name);
|
||||
if (enchantment == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
|
||||
|
||||
if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false)) {
|
||||
throw new Exception(tl("enchantmentPerm", enchantmentName));
|
||||
}
|
||||
return enchantment;
|
||||
}
|
||||
|
||||
public void addBannerMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
|
||||
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 ) {}
|
||||
|
||||
final BannerMeta meta = (BannerMeta) stack.getItemMeta();
|
||||
if (split[0].equalsIgnoreCase("basecolor")) {
|
||||
Color color = Color.fromRGB(Integer.valueOf(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);
|
||||
meta.addPattern(pattern);
|
||||
}
|
||||
|
||||
stack.setItemMeta(meta);
|
||||
} else if (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 ) {}
|
||||
|
||||
// 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();
|
||||
if (split[0].equalsIgnoreCase("basecolor")) {
|
||||
Color color = Color.fromRGB(Integer.valueOf(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);
|
||||
banner.addPattern(pattern);
|
||||
}
|
||||
banner.update();
|
||||
meta.setBlockState(banner);
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasMetaPermission(final CommandSource sender, final String metaPerm, final boolean graceful, final boolean includeBase, final IEssentials ess) throws Exception {
|
||||
final User user = sender != null && sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
|
||||
return hasMetaPermission(user, metaPerm, graceful, includeBase);
|
||||
}
|
||||
|
||||
private boolean hasMetaPermission(final User user, final String metaPerm, final boolean graceful, final boolean includeBase) throws Exception {
|
||||
final String permBase = includeBase ? "essentials.itemspawn.meta-" : "essentials.";
|
||||
if (user == null || user.isAuthorized(permBase + metaPerm)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (graceful) {
|
||||
return false;
|
||||
} else {
|
||||
throw new Exception(tl("noMetaPerm", metaPerm));
|
||||
}
|
||||
}
|
||||
|
||||
private static int bukkitUnbreakableSupport = -1;
|
||||
private static Method spigotMethod;
|
||||
private static Method setUnbreakableMethod;
|
||||
|
||||
private void setUnbreakable(ItemStack is, boolean unbreakable) {
|
||||
ItemMeta meta = is.getItemMeta();
|
||||
try {
|
||||
if (bukkitUnbreakableSupport == -1) {
|
||||
try {
|
||||
ItemMeta.class.getDeclaredMethod("setUnbreakable", boolean.class);
|
||||
bukkitUnbreakableSupport = 1;
|
||||
} catch (NoSuchMethodException | SecurityException ex) {
|
||||
bukkitUnbreakableSupport = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (bukkitUnbreakableSupport == 1) {
|
||||
meta.setUnbreakable(unbreakable);
|
||||
} else {
|
||||
if (spigotMethod == null) {
|
||||
spigotMethod = meta.getClass().getDeclaredMethod("spigot");
|
||||
spigotMethod.setAccessible(true);
|
||||
}
|
||||
Object itemStackSpigot = spigotMethod.invoke(meta);
|
||||
if (setUnbreakableMethod == null) {
|
||||
setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE);
|
||||
setUnbreakableMethod.setAccessible(true);
|
||||
}
|
||||
setUnbreakableMethod.invoke(itemStackSpigot, unbreakable);
|
||||
}
|
||||
is.setItemMeta(meta);
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,181 +1,117 @@
|
||||
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.*;
|
||||
|
||||
import java.util.*;
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
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;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.entity.CreatureType;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
||||
// 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 {
|
||||
CHICKEN("Chicken", Enemies.FRIENDLY, EntityType.CHICKEN),
|
||||
COW("Cow", Enemies.FRIENDLY, EntityType.COW),
|
||||
CREEPER("Creeper", Enemies.ENEMY, EntityType.CREEPER),
|
||||
GHAST("Ghast", Enemies.ENEMY, EntityType.GHAST),
|
||||
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),
|
||||
SHEEP("Sheep", Enemies.FRIENDLY, "", EntityType.SHEEP),
|
||||
SKELETON("Skeleton", Enemies.ENEMY, EntityType.SKELETON),
|
||||
SLIME("Slime", Enemies.ENEMY, EntityType.SLIME),
|
||||
SPIDER("Spider", Enemies.ENEMY, EntityType.SPIDER),
|
||||
SQUID("Squid", Enemies.FRIENDLY, EntityType.SQUID),
|
||||
ZOMBIE("Zombie", Enemies.ENEMY, EntityType.ZOMBIE),
|
||||
WOLF("Wolf", Enemies.NEUTRAL, "", EntityType.WOLF),
|
||||
CAVESPIDER("CaveSpider", Enemies.ENEMY, EntityType.CAVE_SPIDER),
|
||||
ENDERMAN("Enderman", Enemies.ENEMY, "", EntityType.ENDERMAN),
|
||||
SILVERFISH("Silverfish", Enemies.ENEMY, "", EntityType.SILVERFISH),
|
||||
ENDERDRAGON("EnderDragon", Enemies.ENEMY, EntityType.ENDER_DRAGON),
|
||||
VILLAGER("Villager", Enemies.FRIENDLY, EntityType.VILLAGER),
|
||||
BLAZE("Blaze", Enemies.ENEMY, EntityType.BLAZE),
|
||||
MUSHROOMCOW("MushroomCow", Enemies.FRIENDLY, EntityType.MUSHROOM_COW),
|
||||
MAGMACUBE("MagmaCube", Enemies.ENEMY, EntityType.MAGMA_CUBE),
|
||||
SNOWMAN("Snowman", Enemies.FRIENDLY, "", EntityType.SNOWMAN),
|
||||
OCELOT("Ocelot", Enemies.NEUTRAL, EntityType.OCELOT),
|
||||
IRONGOLEM("IronGolem", Enemies.NEUTRAL, EntityType.IRON_GOLEM),
|
||||
WITHER("Wither", Enemies.ENEMY, EntityType.WITHER),
|
||||
BAT("Bat", Enemies.FRIENDLY, EntityType.BAT),
|
||||
WITCH("Witch", Enemies.ENEMY, EntityType.WITCH),
|
||||
BOAT("Boat", Enemies.NEUTRAL, EntityType.BOAT),
|
||||
MINECART("Minecart", Enemies.NEUTRAL, EntityType.MINECART),
|
||||
MINECART_CHEST("ChestMinecart", Enemies.NEUTRAL, EntityType.MINECART_CHEST),
|
||||
MINECART_FURNACE("FurnaceMinecart", Enemies.NEUTRAL, EntityType.MINECART_FURNACE),
|
||||
MINECART_TNT("TNTMinecart", Enemies.NEUTRAL, EntityType.MINECART_TNT),
|
||||
MINECART_HOPPER("HopperMinecart", Enemies.NEUTRAL, EntityType.MINECART_HOPPER),
|
||||
MINECART_MOB_SPAWNER("SpawnerMinecart", Enemies.NEUTRAL, EntityType.MINECART_MOB_SPAWNER),
|
||||
ENDERCRYSTAL("EnderCrystal", Enemies.NEUTRAL, EntityType.ENDER_CRYSTAL),
|
||||
EXPERIENCEORB("ExperienceOrb", Enemies.NEUTRAL, "EXPERIENCE_ORB"),
|
||||
ARMOR_STAND("ArmorStand", Enemies.NEUTRAL, "ARMOR_STAND"),
|
||||
ENDERMITE("Endermite", Enemies.ENEMY, "ENDERMITE"),
|
||||
GUARDIAN("Guardian", Enemies.ENEMY, "GUARDIAN"),
|
||||
ELDER_GUARDIAN("ElderGuardian", Enemies.ENEMY, "ELDER_GUARDIAN"),
|
||||
RABBIT("Rabbit", Enemies.FRIENDLY, "RABBIT"),
|
||||
SHULKER("Shulker", Enemies.ENEMY, "SHULKER"),
|
||||
POLAR_BEAR("PolarBear", Enemies.NEUTRAL, "POLAR_BEAR"),
|
||||
WITHER_SKELETON("WitherSkeleton", Enemies.ENEMY, "WITHER_SKELETON"),
|
||||
STRAY_SKELETON("StraySkeleton", Enemies.ENEMY, "STRAY"),
|
||||
ZOMBIE_VILLAGER("ZombieVillager", Enemies.FRIENDLY, "ZOMBIE_VILLAGER"),
|
||||
SKELETON_HORSE("SkeletonHorse", Enemies.FRIENDLY, "SKELETON_HORSE"),
|
||||
ZOMBIE_HORSE("ZombieHorse", Enemies.FRIENDLY, "ZOMBIE_HORSE"),
|
||||
DONKEY("Donkey", Enemies.FRIENDLY, "DONKEY"),
|
||||
MULE("Mule", Enemies.FRIENDLY, "MULE"),
|
||||
EVOKER("Evoker", Enemies.ENEMY, "EVOKER"),
|
||||
VEX("Vex", Enemies.ENEMY, "VEX"),
|
||||
VINDICATOR("Vindicator", Enemies.ENEMY, "VINDICATOR"),
|
||||
LLAMA("Llama", Enemies.NEUTRAL, "LLAMA"),
|
||||
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")
|
||||
;
|
||||
public enum Mob
|
||||
{
|
||||
CHICKEN("Chicken", Enemies.FRIENDLY, CreatureType.CHICKEN),
|
||||
COW("Cow", Enemies.FRIENDLY, CreatureType.COW),
|
||||
CREEPER("Creeper", Enemies.ENEMY, CreatureType.CREEPER),
|
||||
GHAST("Ghast", Enemies.ENEMY, CreatureType.GHAST),
|
||||
GIANT("Giant", Enemies.ENEMY, CreatureType.GIANT),
|
||||
PIG("Pig", Enemies.FRIENDLY, CreatureType.PIG),
|
||||
PIGZOMB("PigZombie", Enemies.NEUTRAL, CreatureType.PIG_ZOMBIE),
|
||||
SHEEP("Sheep", Enemies.FRIENDLY, "", CreatureType.SHEEP),
|
||||
SKELETON("Skeleton", Enemies.ENEMY, CreatureType.SKELETON),
|
||||
SLIME("Slime", Enemies.ENEMY, CreatureType.SLIME),
|
||||
SPIDER("Spider", Enemies.ENEMY, CreatureType.SPIDER),
|
||||
SQUID("Squid", Enemies.FRIENDLY, CreatureType.SQUID),
|
||||
ZOMBIE("Zombie", Enemies.ENEMY, CreatureType.ZOMBIE),
|
||||
WOLF("Wolf", Enemies.NEUTRAL, CreatureType.WOLF),
|
||||
CAVESPIDER("CaveSpider", Enemies.ENEMY, CreatureType.CAVE_SPIDER),
|
||||
ENDERMAN("Enderman", Enemies.ENEMY, "", CreatureType.ENDERMAN),
|
||||
SILVERFISH("Silverfish", Enemies.ENEMY, "", CreatureType.SILVERFISH),
|
||||
ENDERDRAGON("EnderDragon", Enemies.ENEMY, CreatureType.ENDER_DRAGON),
|
||||
VILLAGER("Villager", Enemies.FRIENDLY, CreatureType.VILLAGER),
|
||||
BLAZE("Blaze", Enemies.ENEMY, CreatureType.BLAZE),
|
||||
MUSHROOMCOW("MushroomCow", Enemies.FRIENDLY, CreatureType.MUSHROOM_COW),
|
||||
MAGMACUBE("MagmaCube", Enemies.ENEMY, CreatureType.MAGMA_CUBE),
|
||||
SNOWMAN("Snowman", Enemies.FRIENDLY, "", CreatureType.SNOWMAN);
|
||||
|
||||
public static final Logger logger = Logger.getLogger("Minecraft");
|
||||
|
||||
public static final Logger logger = Logger.getLogger("Essentials");
|
||||
private Mob(String n, Enemies en, String s, CreatureType type)
|
||||
{
|
||||
this.suffix = s;
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
this.bukkitType = type;
|
||||
}
|
||||
|
||||
Mob(String n, Enemies en, String s, EntityType type) {
|
||||
this.suffix = s;
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
this.bukkitType = type;
|
||||
}
|
||||
private Mob(String n, Enemies en, CreatureType type)
|
||||
{
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
this.bukkitType = type;
|
||||
}
|
||||
public String suffix = "s";
|
||||
final public String name;
|
||||
final public Enemies type;
|
||||
final private CreatureType bukkitType;
|
||||
private static final Map<String, Mob> hashMap = new HashMap<String, Mob>();
|
||||
|
||||
Mob(String n, Enemies en, EntityType type) {
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
this.bukkitType = type;
|
||||
}
|
||||
static
|
||||
{
|
||||
for (Mob mob : Mob.values())
|
||||
{
|
||||
hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob);
|
||||
}
|
||||
}
|
||||
|
||||
public static Set<String> getMobList() {
|
||||
return hashMap.keySet();
|
||||
}
|
||||
|
||||
Mob(String n, Enemies en, String s, String typeName) {
|
||||
this.suffix = s;
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
bukkitType = EnumUtil.getEntityType(typeName);
|
||||
}
|
||||
|
||||
Mob(String n, Enemies en, String typeName) {
|
||||
this.name = n;
|
||||
this.type = en;
|
||||
bukkitType = EnumUtil.getEntityType(typeName);
|
||||
}
|
||||
|
||||
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()) {
|
||||
hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob);
|
||||
if (mob.bukkitType != null) {
|
||||
bukkitMap.put(mob.bukkitType, mob);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Set<String> getMobList() {
|
||||
return Collections.unmodifiableSet(hashMap.keySet());
|
||||
}
|
||||
|
||||
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) {
|
||||
logger.log(Level.WARNING, tl("unableToSpawnMob"));
|
||||
throw new MobException();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
public LivingEntity spawn(final Player player, final Server server, final Location loc) throws MobException
|
||||
{
|
||||
final LivingEntity entity = player.getWorld().spawn(loc, (Class<? extends LivingEntity>)this.bukkitType.getEntityClass());
|
||||
if (entity == null)
|
||||
{
|
||||
logger.log(Level.WARNING, _("unableToSpawnMob"));
|
||||
throw new MobException();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
|
||||
public enum Enemies {
|
||||
FRIENDLY("friendly"),
|
||||
NEUTRAL("neutral"),
|
||||
ENEMY("enemy");
|
||||
public enum Enemies
|
||||
{
|
||||
FRIENDLY("friendly"),
|
||||
NEUTRAL("neutral"),
|
||||
ENEMY("enemy");
|
||||
|
||||
Enemies(final String type) {
|
||||
this.type = type;
|
||||
}
|
||||
private Enemies(final String type)
|
||||
{
|
||||
this.type = type;
|
||||
}
|
||||
final protected String type;
|
||||
}
|
||||
|
||||
final protected String type;
|
||||
}
|
||||
public CreatureType getType()
|
||||
{
|
||||
return bukkitType;
|
||||
}
|
||||
|
||||
public EntityType getType() {
|
||||
return bukkitType;
|
||||
}
|
||||
|
||||
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 static Mob fromName(final String name)
|
||||
{
|
||||
return hashMap.get(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
|
||||
|
||||
public static class MobException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
public static class MobException extends Exception
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.EnumUtil;
|
||||
import net.ess3.nms.refl.ReflUtil;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.Ocelot;
|
||||
import org.bukkit.entity.Villager;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import static com.earth2me.essentials.utils.EnumUtil.getEntityType;
|
||||
|
||||
public class MobCompat {
|
||||
|
||||
// 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");
|
||||
|
||||
// Constants for mobs that have changed since earlier versions
|
||||
public static final EntityType CAT = getEntityType("CAT", "OCELOT");
|
||||
|
||||
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 String oldProfession;
|
||||
private String oldCareer;
|
||||
private 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);
|
||||
}
|
||||
}
|
||||
|
||||
// Older cats are Ocelots, whereas 1.14+ cats are Cats
|
||||
private static Class catClass = ReflUtil.getClassCached("org.bukkit.entity.Cat");
|
||||
private static Class catTypeClass = ReflUtil.getClassCached("org.bukkit.entity.Cat.Type");
|
||||
private static Method catSetTypeMethod = (catClass == null || catTypeClass == null) ? null : ReflUtil.getMethodCached(catClass, "setCatType", catTypeClass);
|
||||
|
||||
private static boolean isNewCat() {
|
||||
return (catClass != null && catTypeClass != null && catSetTypeMethod != null);
|
||||
}
|
||||
|
||||
public static void setCatType(final Entity entity, final CatType type) {
|
||||
if (isNewCat()) {
|
||||
try {
|
||||
catSetTypeMethod.invoke(entity, EnumUtil.valueOf(catTypeClass, type.catTypeName));
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
((Ocelot) entity).setCatType(Ocelot.Type.valueOf(type.ocelotTypeName));
|
||||
}
|
||||
}
|
||||
|
||||
// Older villagers have professions and careers, 1.14+ villagers only have professions
|
||||
private static Class villagerCareerClass = ReflUtil.getClassCached("org.bukkit.entity.Villager.Career");
|
||||
private static Method villagerSetCareerMethod = (villagerCareerClass == null) ? null : ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareerClass);
|
||||
|
||||
private static boolean isCareerVillager() {
|
||||
return (villagerCareerClass != null && villagerSetCareerMethod != null);
|
||||
}
|
||||
|
||||
public static void setVillagerProfession(final Entity entity, final VillagerProfession profession) {
|
||||
if (!isCareerVillager()) {
|
||||
((Villager) entity).setProfession(profession.asEnum());
|
||||
} else {
|
||||
((Villager) entity).setProfession(profession.asEnum());
|
||||
try {
|
||||
villagerSetCareerMethod.invoke(entity, EnumUtil.valueOf(villagerCareerClass, profession.oldCareer));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only 1.14+ villagers have biome variants
|
||||
public static void setVillagerType(final Entity entity, final String type) {
|
||||
Class typeEnum = ReflUtil.getClassCached("org.bukkit.entity.Villager.Type");
|
||||
if (typeEnum == null) return;
|
||||
|
||||
Method villagerSetTypeMethod = ReflUtil.getMethodCached(Villager.class, "setVillagerType", typeEnum);
|
||||
try {
|
||||
villagerSetTypeMethod.invoke(entity, EnumUtil.valueOf(typeEnum, type));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Llamas only exist in 1.11+
|
||||
public static void setLlamaColor(final Entity entity, final String color) {
|
||||
Class llamaClass = ReflUtil.getClassCached("org.bukkit.entity.Llama");
|
||||
if (llamaClass == null) return;
|
||||
|
||||
Class colorEnum = ReflUtil.getClassCached("org.bukkit.entity.Llama.Color");
|
||||
Method setVariantMethod = ReflUtil.getMethodCached(llamaClass, "setColor");
|
||||
|
||||
try {
|
||||
setVariantMethod.invoke(entity, EnumUtil.valueOf(colorEnum, color));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Parrots only exist in 1.12+
|
||||
public static void setParrotVariant(final Entity entity, final String variant) {
|
||||
Class parrotClass = ReflUtil.getClassCached("org.bukkit.entity.Parrot");
|
||||
if (parrotClass == null) return;
|
||||
|
||||
Class variantEnum = ReflUtil.getClassCached("org.bukkit.entity.Parrot.Variant");
|
||||
Method setVariantMethod = ReflUtil.getMethodCached(parrotClass, "setVariant");
|
||||
try {
|
||||
setVariantMethod.invoke(entity, EnumUtil.valueOf(variantEnum, variant));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Tropical fish only exist in 1.13+
|
||||
public static void setTropicalFishPattern(final Entity entity, final String pattern) {
|
||||
Class tropicalFishClass = ReflUtil.getClassCached("org.bukkit.entity.TropicalFish");
|
||||
if (tropicalFishClass == null) return;
|
||||
|
||||
Class patternEnum = ReflUtil.getClassCached("org.bukkit.entity.TropicalFish.Pattern");
|
||||
Method setPatternMethod = ReflUtil.getMethodCached(tropicalFishClass, "setPattern");
|
||||
try {
|
||||
setPatternMethod.invoke(entity, EnumUtil.valueOf(patternEnum, pattern));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Mushroom cow variant API only exists in 1.14+
|
||||
public static void setMooshroomVariant(final Entity entity, final String variant) {
|
||||
Class mushroomCowClass = ReflUtil.getClassCached("org.bukkit.entity.MushroomCow");
|
||||
Class variantEnum = ReflUtil.getClassCached("org.bukkit.entity.MushroomCow.Variant");
|
||||
if (mushroomCowClass == null || variantEnum == null) return;
|
||||
|
||||
Method setVariantMethod = ReflUtil.getMethodCached(mushroomCowClass, "setVariant");
|
||||
try {
|
||||
setVariantMethod.invoke(entity, EnumUtil.valueOf(variantEnum, variant));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Pandas only exists in 1.14+
|
||||
public static void setPandaGene(final Entity entity, final String gene, final boolean mainGene) {
|
||||
Class pandaClass = ReflUtil.getClassCached("org.bukkit.entity.Panda");
|
||||
if (pandaClass == null) return;
|
||||
|
||||
Class geneEnum = ReflUtil.getClassCached("org.bukkit.entity.Panda.Gene");
|
||||
Method setGeneMethod;
|
||||
|
||||
if (mainGene) {
|
||||
setGeneMethod = ReflUtil.getMethodCached(pandaClass, "setMainGene");
|
||||
} else {
|
||||
setGeneMethod = ReflUtil.getMethodCached(pandaClass, "setHiddenGene");
|
||||
}
|
||||
|
||||
try {
|
||||
setGeneMethod.invoke(entity, EnumUtil.valueOf(geneEnum, gene));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
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.inventory.EntityEquipment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.material.Colorable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
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),
|
||||
BABY_HORSE("colt", EntityType.HORSE, Data.BABY, false),
|
||||
BABY_OCELOT("kitten", EntityType.OCELOT, Data.BABY, false),
|
||||
BABY_SHEEP("lamb", EntityType.SHEEP, Data.BABY, false),
|
||||
BABY_COW("calf", EntityType.COW.getEntityClass(), Data.BABY, false),
|
||||
BABY_VILLAGER("child", EntityType.VILLAGER, Data.BABY, false),
|
||||
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),
|
||||
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),
|
||||
SOCKS_HORSE("socks", EntityType.HORSE, Horse.Style.WHITE, false),
|
||||
LEOPARD_HORSE("leopard", EntityType.HORSE, Horse.Style.WHITE_DOTS, true),
|
||||
APPALOOSA_HORSE("appaloosa", EntityType.HORSE, Horse.Style.WHITE_DOTS, false),
|
||||
PAINT_HORSE("paint", EntityType.HORSE, Horse.Style.WHITEFIELD, true),
|
||||
MILKY_HORSE("milky", EntityType.HORSE, Horse.Style.WHITEFIELD, false),
|
||||
SPLOTCHY_HORSE("splotchy", EntityType.HORSE, Horse.Style.WHITEFIELD, false),
|
||||
BLACK_HORSE("black", EntityType.HORSE, Horse.Color.BLACK, true),
|
||||
CHESTNUT_HORSE("chestnut", EntityType.HORSE, Horse.Color.CHESTNUT, true),
|
||||
LIVER_HORSE("liver", EntityType.HORSE, Horse.Color.CHESTNUT, false),
|
||||
CREAMY_HORSE("creamy", EntityType.HORSE, Horse.Color.CREAMY, true),
|
||||
FLAXEN_HORSE("flaxen", EntityType.HORSE, Horse.Color.CREAMY, false),
|
||||
GRAY_HORSE("gray", EntityType.HORSE, Horse.Color.GRAY, true),
|
||||
DAPPLE_HORSE("dapple", EntityType.HORSE, Horse.Color.GRAY, false),
|
||||
BUCKSKIN_HORSE("buckskin", EntityType.HORSE, Horse.Color.DARK_BROWN, true),
|
||||
DARKBROWN_HORSE("darkbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false),
|
||||
DARK_HORSE("dark", EntityType.HORSE, Horse.Color.DARK_BROWN, false),
|
||||
DBROWN_HORSE("dbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false),
|
||||
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, 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(), 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, 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),
|
||||
BOW_SKELETON("bow", EntityType.SKELETON, Material.BOW, true),
|
||||
POWERED_CREEPER("powered", EntityType.CREEPER, Data.ELECTRIFIED, true),
|
||||
ELECTRIC_CREEPER("electric", EntityType.CREEPER, Data.ELECTRIFIED, false),
|
||||
CHARGED_CREEPER("charged", EntityType.CREEPER, Data.ELECTRIFIED, false),
|
||||
SADDLE_PIG("saddle", EntityType.PIG, Data.PIGSADDLE, true),
|
||||
ANGRY_WOLF("angry", EntityType.WOLF, Data.ANGRY, true),
|
||||
RABID_WOLF("rabid", EntityType.WOLF, Data.ANGRY, false),
|
||||
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("", "<1-100>", EntityType.SLIME.getEntityClass(), Data.SIZE, true),
|
||||
NUM_EXPERIENCE_ORB("", "<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)
|
||||
;
|
||||
|
||||
|
||||
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 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 == 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())) {
|
||||
mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data);
|
||||
}
|
||||
}
|
||||
|
||||
return mobList;
|
||||
}
|
||||
|
||||
public static List<String> getValidHelp(final Entity spawned) {
|
||||
List<String> output = new ArrayList<String>();
|
||||
LinkedHashMap<String, MobData> posData = getPossibleData(spawned, true);
|
||||
|
||||
for (MobData data : posData.values()) {
|
||||
output.add(data.helpMessage);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static MobData fromData(final Entity spawned, final String name) {
|
||||
if (name.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
LinkedHashMap<String, MobData> posData = getPossibleData(spawned, false);
|
||||
for (String data : posData.keySet()) {
|
||||
if (name.contains(data)) {
|
||||
return posData.get(data);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMatched() {
|
||||
return this.matched;
|
||||
}
|
||||
|
||||
public void setData(final Entity spawned, final Player target, final String rawData) throws Exception {
|
||||
if (this.value.equals(Data.ANGRY)) {
|
||||
((Wolf) spawned).setAngry(true);
|
||||
} else if (this.value.equals(Data.ADULT)) {
|
||||
((Ageable) spawned).setAdult();
|
||||
} else if (this.value.equals(Data.BABY)) {
|
||||
((Ageable) spawned).setBaby();
|
||||
} else if (this.value.equals(Data.ADULTZOMBIE)) {
|
||||
((Zombie) spawned).setBaby(false);
|
||||
} else if (this.value.equals(Data.BABYZOMBIE)) {
|
||||
((Zombie) spawned).setBaby(true);
|
||||
} else if (this.value.equals(Data.ELECTRIFIED)) {
|
||||
((Creeper) spawned).setPowered(true);
|
||||
} else if (this.value.equals(Data.HORSESADDLE)) {
|
||||
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);
|
||||
tameable.setTamed(true);
|
||||
tameable.setOwner(target);
|
||||
} else if (this.value.equals(Data.COLORABLE)) {
|
||||
final String color = rawData.toUpperCase(Locale.ENGLISH);
|
||||
try {
|
||||
if (color.equals("RANDOM")) {
|
||||
final Random rand = new Random();
|
||||
((Colorable) spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]);
|
||||
} else if (!color.isEmpty()) {
|
||||
((Colorable) spawned).setColor(DyeColor.valueOf(color));
|
||||
}
|
||||
this.matched = rawData;
|
||||
} catch (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) {
|
||||
throw new Exception(tl("invalidNumber"), e);
|
||||
}
|
||||
} else if (this.value.equals(Data.SIZE)) {
|
||||
try {
|
||||
((Slime) spawned).setSize(Integer.parseInt(rawData));
|
||||
this.matched = rawData;
|
||||
} catch (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 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);
|
||||
((Horse) spawned).getInventory().setArmor(new ItemStack((Material) this.value, 1));
|
||||
} else if (this.type.equals(EntityType.ZOMBIE.getEntityClass()) || this.type.equals(EntityType.SKELETON)) {
|
||||
final EntityEquipment invent = ((LivingEntity) spawned).getEquipment();
|
||||
InventoryWorkaround.setItemInMainHand(invent, new ItemStack((Material) this.value, 1));
|
||||
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
|
||||
}
|
||||
} 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;
|
||||
}
|
||||
} else {
|
||||
logger.warning("Unknown mob data type: " + this.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,35 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
||||
public class PlayerExtension {
|
||||
protected Player base;
|
||||
|
||||
public PlayerExtension(final Player base) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
public final Player getBase() {
|
||||
return base;
|
||||
}
|
||||
|
||||
public final Player setBase(final Player base) {
|
||||
return this.base = base;
|
||||
}
|
||||
|
||||
public Server getServer() {
|
||||
return base.getServer();
|
||||
}
|
||||
|
||||
public World getWorld() {
|
||||
return base.getWorld();
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
return base.getLocation();
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.FormatUtil;
|
||||
import org.bukkit.Server;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
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) {
|
||||
if (needComma) {
|
||||
groupString.append(seperator);
|
||||
}
|
||||
needComma = true;
|
||||
if (user.isAfk()) {
|
||||
groupString.append(tl("listAfkTag"));
|
||||
}
|
||||
if (user.isHidden()) {
|
||||
groupString.append(tl("listHiddenTag"));
|
||||
}
|
||||
user.setDisplayNick();
|
||||
groupString.append(user.getDisplayName());
|
||||
groupString.append("\u00a7f");
|
||||
}
|
||||
return groupString.toString();
|
||||
}
|
||||
|
||||
// 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();
|
||||
int playerHidden = 0;
|
||||
int hiddenCount = 0;
|
||||
for (User onlinePlayer : ess.getOnlineUsers()) {
|
||||
if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase()))) {
|
||||
playerHidden++;
|
||||
if (showHidden || user.getBase().canSee(onlinePlayer.getBase())) {
|
||||
hiddenCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
String online;
|
||||
if (hiddenCount > 0) {
|
||||
online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers());
|
||||
} else {
|
||||
online = tl("listAmount", ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers());
|
||||
}
|
||||
return online;
|
||||
}
|
||||
|
||||
// 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()) {
|
||||
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);
|
||||
}
|
||||
list.add(onlineUser);
|
||||
}
|
||||
return 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) {
|
||||
if (configGroup.equalsIgnoreCase(groupName)) {
|
||||
String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" ");
|
||||
for (String groupValue : groupValues) {
|
||||
groupValue = groupValue.toLowerCase(Locale.ENGLISH);
|
||||
if (groupValue == null || groupValue.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
List<User> u = playerList.get(groupValue.trim());
|
||||
if (u == null || u.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
playerList.remove(groupValue);
|
||||
users.addAll(u);
|
||||
}
|
||||
}
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
// Output a playerlist of just a single group, /list <groupname>
|
||||
public static String listGroupUsers(final IEssentials ess, final Map<String, List<User>> playerList, final String groupName) throws Exception {
|
||||
final List<User> users = getMergedList(ess, playerList, groupName);
|
||||
final List<User> groupUsers = playerList.get(groupName);
|
||||
if (groupUsers != null && !groupUsers.isEmpty()) {
|
||||
users.addAll(groupUsers);
|
||||
}
|
||||
if (users == null || 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, ", "));
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
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) {
|
||||
this.name = entity.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location getLocation() {
|
||||
return Bukkit.getServer().getPlayerExact(name).getLocation();
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.NumberUtil;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
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<>();
|
||||
private static final Map<String, PotionEffectType> ALIASPOTIONS = new HashMap<>();
|
||||
|
||||
static {
|
||||
|
||||
POTIONS.put("speed", PotionEffectType.SPEED);
|
||||
ALIASPOTIONS.put("fast", PotionEffectType.SPEED);
|
||||
ALIASPOTIONS.put("runfast", PotionEffectType.SPEED);
|
||||
ALIASPOTIONS.put("sprint", PotionEffectType.SPEED);
|
||||
ALIASPOTIONS.put("swift", PotionEffectType.SPEED);
|
||||
|
||||
POTIONS.put("slowness", PotionEffectType.SLOW);
|
||||
ALIASPOTIONS.put("slow", PotionEffectType.SLOW);
|
||||
ALIASPOTIONS.put("sluggish", PotionEffectType.SLOW);
|
||||
|
||||
POTIONS.put("haste", PotionEffectType.FAST_DIGGING);
|
||||
ALIASPOTIONS.put("superpick", PotionEffectType.FAST_DIGGING);
|
||||
ALIASPOTIONS.put("quickmine", PotionEffectType.FAST_DIGGING);
|
||||
ALIASPOTIONS.put("digspeed", PotionEffectType.FAST_DIGGING);
|
||||
ALIASPOTIONS.put("digfast", PotionEffectType.FAST_DIGGING);
|
||||
ALIASPOTIONS.put("sharp", PotionEffectType.FAST_DIGGING);
|
||||
|
||||
POTIONS.put("fatigue", PotionEffectType.SLOW_DIGGING);
|
||||
ALIASPOTIONS.put("slow", PotionEffectType.SLOW_DIGGING);
|
||||
ALIASPOTIONS.put("dull", PotionEffectType.SLOW_DIGGING);
|
||||
|
||||
POTIONS.put("strength", PotionEffectType.INCREASE_DAMAGE);
|
||||
ALIASPOTIONS.put("strong", PotionEffectType.INCREASE_DAMAGE);
|
||||
ALIASPOTIONS.put("bull", PotionEffectType.INCREASE_DAMAGE);
|
||||
ALIASPOTIONS.put("attack", PotionEffectType.INCREASE_DAMAGE);
|
||||
|
||||
POTIONS.put("heal", PotionEffectType.HEAL);
|
||||
ALIASPOTIONS.put("healthy", PotionEffectType.HEAL);
|
||||
ALIASPOTIONS.put("instaheal", PotionEffectType.HEAL);
|
||||
|
||||
POTIONS.put("harm", PotionEffectType.HARM);
|
||||
ALIASPOTIONS.put("harming", PotionEffectType.HARM);
|
||||
ALIASPOTIONS.put("injure", PotionEffectType.HARM);
|
||||
ALIASPOTIONS.put("damage", PotionEffectType.HARM);
|
||||
ALIASPOTIONS.put("inflict", PotionEffectType.HARM);
|
||||
|
||||
POTIONS.put("jump", PotionEffectType.JUMP);
|
||||
ALIASPOTIONS.put("leap", PotionEffectType.JUMP);
|
||||
|
||||
POTIONS.put("nausea", PotionEffectType.CONFUSION);
|
||||
ALIASPOTIONS.put("sick", PotionEffectType.CONFUSION);
|
||||
ALIASPOTIONS.put("sickness", PotionEffectType.CONFUSION);
|
||||
ALIASPOTIONS.put("confusion", PotionEffectType.CONFUSION);
|
||||
|
||||
POTIONS.put("regeneration", PotionEffectType.REGENERATION);
|
||||
ALIASPOTIONS.put("regen", PotionEffectType.REGENERATION);
|
||||
|
||||
POTIONS.put("resistance", PotionEffectType.DAMAGE_RESISTANCE);
|
||||
ALIASPOTIONS.put("dmgresist", PotionEffectType.DAMAGE_RESISTANCE);
|
||||
ALIASPOTIONS.put("armor", PotionEffectType.DAMAGE_RESISTANCE);
|
||||
|
||||
POTIONS.put("fireresist", PotionEffectType.FIRE_RESISTANCE);
|
||||
ALIASPOTIONS.put("fireresistance", PotionEffectType.FIRE_RESISTANCE);
|
||||
ALIASPOTIONS.put("resistfire", PotionEffectType.FIRE_RESISTANCE);
|
||||
|
||||
POTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING);
|
||||
ALIASPOTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING);
|
||||
|
||||
POTIONS.put("invisibility", PotionEffectType.INVISIBILITY);
|
||||
ALIASPOTIONS.put("invisible", PotionEffectType.INVISIBILITY);
|
||||
ALIASPOTIONS.put("invis", PotionEffectType.INVISIBILITY);
|
||||
ALIASPOTIONS.put("vanish", PotionEffectType.INVISIBILITY);
|
||||
ALIASPOTIONS.put("disappear", PotionEffectType.INVISIBILITY);
|
||||
|
||||
POTIONS.put("blindness", PotionEffectType.BLINDNESS);
|
||||
ALIASPOTIONS.put("blind", PotionEffectType.BLINDNESS);
|
||||
|
||||
POTIONS.put("nightvision", PotionEffectType.NIGHT_VISION);
|
||||
ALIASPOTIONS.put("vision", PotionEffectType.NIGHT_VISION);
|
||||
|
||||
POTIONS.put("hunger", PotionEffectType.HUNGER);
|
||||
ALIASPOTIONS.put("hungry", PotionEffectType.HUNGER);
|
||||
ALIASPOTIONS.put("starve", PotionEffectType.HUNGER);
|
||||
|
||||
POTIONS.put("weakness", PotionEffectType.WEAKNESS);
|
||||
ALIASPOTIONS.put("weak", PotionEffectType.WEAKNESS);
|
||||
|
||||
POTIONS.put("poison", PotionEffectType.POISON);
|
||||
ALIASPOTIONS.put("venom", PotionEffectType.POISON);
|
||||
|
||||
POTIONS.put("wither", PotionEffectType.WITHER);
|
||||
ALIASPOTIONS.put("decay", PotionEffectType.WITHER);
|
||||
|
||||
POTIONS.put("healthboost", PotionEffectType.HEALTH_BOOST);
|
||||
ALIASPOTIONS.put("boost", PotionEffectType.HEALTH_BOOST);
|
||||
|
||||
POTIONS.put("absorption", PotionEffectType.ABSORPTION);
|
||||
ALIASPOTIONS.put("absorb", PotionEffectType.ABSORPTION);
|
||||
|
||||
POTIONS.put("saturation", PotionEffectType.SATURATION);
|
||||
ALIASPOTIONS.put("food", PotionEffectType.SATURATION);
|
||||
|
||||
POTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING);
|
||||
ALIASPOTIONS.put("underwaterbreathing", PotionEffectType.WATER_BREATHING);
|
||||
ALIASPOTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING);
|
||||
ALIASPOTIONS.put("underwaterbreath", PotionEffectType.WATER_BREATHING);
|
||||
ALIASPOTIONS.put("air", PotionEffectType.WATER_BREATHING);
|
||||
|
||||
// 1.9
|
||||
try {
|
||||
POTIONS.put("glowing", PotionEffectType.GLOWING);
|
||||
ALIASPOTIONS.put("glow", PotionEffectType.GLOWING);
|
||||
|
||||
POTIONS.put("levitation", PotionEffectType.LEVITATION);
|
||||
ALIASPOTIONS.put("levitate", PotionEffectType.LEVITATION);
|
||||
|
||||
POTIONS.put("luck", PotionEffectType.LUCK);
|
||||
POTIONS.put("unluck", PotionEffectType.UNLUCK);
|
||||
} catch (Throwable ignored) {}
|
||||
}
|
||||
|
||||
public static PotionEffectType getByName(String name) {
|
||||
PotionEffectType peffect;
|
||||
if (NumberUtil.isInt(name)) {
|
||||
peffect = PotionEffectType.getById(Integer.parseInt(name));
|
||||
} else {
|
||||
peffect = PotionEffectType.getByName(name.toUpperCase(Locale.ENGLISH));
|
||||
}
|
||||
if (peffect == null) {
|
||||
peffect = POTIONS.get(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
if (peffect == null) {
|
||||
peffect = ALIASPOTIONS.get(name.toLowerCase(Locale.ENGLISH));
|
||||
}
|
||||
return peffect;
|
||||
}
|
||||
|
||||
public static Set<Entry<String, PotionEffectType>> entrySet() {
|
||||
return POTIONS.entrySet();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,276 +0,0 @@
|
||||
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;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.inventory.EntityEquipment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
public 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");
|
||||
|
||||
public static String mobList(final User user) {
|
||||
final Set<String> mobList = Mob.getMobList();
|
||||
final Set<String> availableList = new HashSet<String>();
|
||||
for (String mob : mobList) {
|
||||
if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) {
|
||||
availableList.add(mob);
|
||||
}
|
||||
}
|
||||
if (availableList.isEmpty()) {
|
||||
availableList.add(tl("none"));
|
||||
}
|
||||
return StringUtil.joinList(availableList);
|
||||
}
|
||||
|
||||
public static List<String> mobParts(final String mobString) {
|
||||
String[] mobParts = mobString.split(",");
|
||||
|
||||
List<String> mobs = new ArrayList<String>();
|
||||
|
||||
for (String mobPart : mobParts) {
|
||||
String[] mobDatas = mobPart.split(":");
|
||||
mobs.add(mobDatas[0]);
|
||||
}
|
||||
return mobs;
|
||||
}
|
||||
|
||||
public static List<String> mobData(final String mobString) {
|
||||
String[] mobParts = mobString.split(",");
|
||||
|
||||
List<String> mobData = new ArrayList<String>();
|
||||
|
||||
for (String mobPart : mobParts) {
|
||||
String[] mobDatas = mobPart.split(":");
|
||||
if (mobDatas.length == 1) {
|
||||
if (mobPart.contains(":")) {
|
||||
mobData.add("");
|
||||
} else {
|
||||
mobData.add(null);
|
||||
}
|
||||
} else {
|
||||
mobData.add(mobDatas[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return mobData;
|
||||
}
|
||||
|
||||
// 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 {
|
||||
final Block block = LocationUtil.getTarget(user.getBase()).getBlock();
|
||||
if (block == null) {
|
||||
throw new Exception(tl("unableToSpawnMob"));
|
||||
}
|
||||
spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount);
|
||||
}
|
||||
|
||||
// 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 {
|
||||
spawnmob(ess, server, sender, target, target.getLocation(), parts, data, mobCount);
|
||||
}
|
||||
|
||||
// This method spawns a mob at loc, owned by target
|
||||
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));
|
||||
checkSpawnable(ess, sender, mob);
|
||||
}
|
||||
|
||||
final int serverLimit = ess.getSettings().getSpawnMobLimit();
|
||||
int effectiveLimit = serverLimit / parts.size();
|
||||
|
||||
if (effectiveLimit < 1) {
|
||||
effectiveLimit = 1;
|
||||
while (parts.size() > serverLimit) {
|
||||
parts.remove(serverLimit);
|
||||
}
|
||||
}
|
||||
|
||||
if (mobCount > effectiveLimit) {
|
||||
mobCount = effectiveLimit;
|
||||
sender.sendMessage(tl("mobSpawnLimit"));
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new Exception(tl("unableToSpawnMob"), e1);
|
||||
} catch (NumberFormatException e2) {
|
||||
throw new Exception(tl("numberRequired"), e2);
|
||||
} catch (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 {
|
||||
Mob mob;
|
||||
Entity spawnedMob = null;
|
||||
Entity spawnedMount;
|
||||
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
if (i == 0) {
|
||||
mob = Mob.fromName(parts.get(i));
|
||||
spawnedMob = mob.spawn(sloc.getWorld(), server, sloc);
|
||||
defaultMobData(mob.getType(), spawnedMob);
|
||||
|
||||
if (data.get(i) != null) {
|
||||
changeMobData(sender, mob.getType(), spawnedMob, data.get(i).toLowerCase(Locale.ENGLISH), target);
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc);
|
||||
defaultMobData(mMob.getType(), spawnedMount);
|
||||
|
||||
if (data.get(next) != null) {
|
||||
changeMobData(sender, mMob.getType(), spawnedMount, data.get(next).toLowerCase(Locale.ENGLISH), target);
|
||||
}
|
||||
|
||||
spawnedMob.setPassenger(spawnedMount);
|
||||
|
||||
spawnedMob = spawnedMount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkSpawnable(IEssentials ess, CommandSource sender, Mob mob) throws Exception {
|
||||
if (mob == null || mob.getType() == null) {
|
||||
throw new Exception(tl("invalidMob"));
|
||||
}
|
||||
|
||||
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) {
|
||||
throw new Exception(tl("disabledToSpawnMob"));
|
||||
}
|
||||
|
||||
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH))) {
|
||||
throw new Exception(tl("noPermToSpawnMob"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void changeMobData(final CommandSource sender, final EntityType type, final Entity spawned, final String inputData, final User target) throws Exception {
|
||||
String data = inputData;
|
||||
|
||||
if (data.isEmpty()) {
|
||||
sender.sendMessage(tl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned))));
|
||||
}
|
||||
|
||||
if (spawned instanceof Zombie) {
|
||||
((Zombie) spawned).setBaby(false);
|
||||
} else if (spawned instanceof Ageable) {
|
||||
((Ageable) spawned).setAdult();
|
||||
}
|
||||
|
||||
if (spawned instanceof Zombie || type == EntityType.SKELETON) {
|
||||
if (inputData.contains("armor") || inputData.contains("armour")) {
|
||||
final EntityEquipment invent = ((LivingEntity) spawned).getEquipment();
|
||||
if (inputData.contains("noarmor") || inputData.contains("noarmour")) {
|
||||
invent.clear();
|
||||
} else if (inputData.contains("diamond")) {
|
||||
invent.setBoots(new ItemStack(Material.DIAMOND_BOOTS, 1));
|
||||
invent.setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS, 1));
|
||||
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(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 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));
|
||||
invent.setHelmet(new ItemStack(Material.IRON_HELMET, 1));
|
||||
}
|
||||
invent.setBootsDropChance(0f);
|
||||
invent.setLeggingsDropChance(0f);
|
||||
invent.setChestplateDropChance(0f);
|
||||
invent.setHelmetDropChance(0f);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
MobData newData = MobData.fromData(spawned, data);
|
||||
while (newData != null) {
|
||||
newData.setData(spawned, target.getBase(), data);
|
||||
data = data.replace(newData.getMatched(), "");
|
||||
newData = MobData.fromData(spawned, data);
|
||||
}
|
||||
}
|
||||
|
||||
private static void defaultMobData(final EntityType type, final Entity spawned) {
|
||||
if (type == EntityType.SKELETON) {
|
||||
final EntityEquipment invent = ((LivingEntity) spawned).getEquipment();
|
||||
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(Material.BOW, 1));
|
||||
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
|
||||
|
||||
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
|
||||
invent.setBootsDropChance(0.0f);
|
||||
}
|
||||
|
||||
if (type == EntityType.PIG_ZOMBIE) {
|
||||
final PigZombie zombie = ((PigZombie) spawned);
|
||||
setVillager(zombie, false);
|
||||
|
||||
final EntityEquipment invent = zombie.getEquipment();
|
||||
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(GOLDEN_SWORD, 1));
|
||||
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
|
||||
|
||||
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
|
||||
invent.setBootsDropChance(0.0f);
|
||||
}
|
||||
|
||||
if (type == EntityType.ZOMBIE) {
|
||||
final Zombie zombie = ((Zombie) spawned);
|
||||
setVillager(zombie, false);
|
||||
|
||||
final EntityEquipment invent = zombie.getEquipment();
|
||||
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
|
||||
invent.setBootsDropChance(0.0f);
|
||||
}
|
||||
|
||||
if (type == EntityType.HORSE) {
|
||||
((Horse) spawned).setJumpStrength(1.2);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private static void setVillager(Zombie zombie, boolean villager) {
|
||||
try {
|
||||
zombie.setVillager(villager);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.event.EventHandler;
|
||||
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;
|
||||
private transient int timer = -1;
|
||||
|
||||
public TNTExplodeListener(final IEssentials ess) {
|
||||
super();
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
public void enable() {
|
||||
if (!enabled) {
|
||||
enabled = true;
|
||||
timer = ess.scheduleSyncDelayedTask(this, 200);
|
||||
return;
|
||||
}
|
||||
if (timer != -1) {
|
||||
ess.getScheduler().cancelTask(timer);
|
||||
timer = ess.scheduleSyncDelayedTask(this, 200);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onEntityExplode(final EntityExplodeEvent event) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
if (event.getEntity() instanceof LivingEntity) {
|
||||
return;
|
||||
}
|
||||
if (event.blockList().size() < 1) {
|
||||
return;
|
||||
}
|
||||
event.setCancelled(true);
|
||||
event.getLocation().getWorld().createExplosion(event.getLocation(), 0F);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
enabled = false;
|
||||
}
|
||||
}
|
||||
@@ -1,338 +1,302 @@
|
||||
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 org.bukkit.Bukkit;
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.ITeleport;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
|
||||
import com.earth2me.essentials.perm.Permissions;
|
||||
import com.earth2me.essentials.user.CooldownException;
|
||||
import com.earth2me.essentials.user.UserData.TimestampType;
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.logging.Logger;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
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 static com.earth2me.essentials.I18n.tl;
|
||||
public class Teleport implements Runnable, ITeleport
|
||||
{
|
||||
private static final double MOVE_CONSTANT = 0.3;
|
||||
|
||||
|
||||
public class Teleport implements ITeleport {
|
||||
private final IUser teleportOwner;
|
||||
private final IEssentials ess;
|
||||
private TimedTeleport timedTeleport;
|
||||
private static class Target
|
||||
{
|
||||
private final Location location;
|
||||
private final Entity entity;
|
||||
|
||||
private TeleportType tpType;
|
||||
public Target(Location location)
|
||||
{
|
||||
this.location = location;
|
||||
this.entity = null;
|
||||
}
|
||||
|
||||
public Teleport(IUser user, IEssentials ess) {
|
||||
this.teleportOwner = user;
|
||||
this.ess = ess;
|
||||
tpType = TeleportType.NORMAL;
|
||||
}
|
||||
public Target(Entity entity)
|
||||
{
|
||||
this.entity = entity;
|
||||
this.location = null;
|
||||
}
|
||||
|
||||
public enum TeleportType {
|
||||
TPA,
|
||||
BACK,
|
||||
NORMAL
|
||||
}
|
||||
public Location getLocation()
|
||||
{
|
||||
if (this.entity != null)
|
||||
{
|
||||
return this.entity.getLocation();
|
||||
}
|
||||
return location;
|
||||
}
|
||||
}
|
||||
private IUser user;
|
||||
private int teleTimer = -1;
|
||||
private long started; // time this task was initiated
|
||||
private long delay; // how long to delay the teleport
|
||||
private int health;
|
||||
// note that I initially stored a clone of the location for reference, but...
|
||||
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
|
||||
// so, the X/Y/Z values are stored instead and rounded off
|
||||
private long initX;
|
||||
private long initY;
|
||||
private long initZ;
|
||||
private Target teleportTarget;
|
||||
private Trade chargeFor;
|
||||
private final IEssentials ess;
|
||||
private static final Logger logger = Logger.getLogger("Minecraft");
|
||||
private TeleportCause cause;
|
||||
|
||||
public void cooldown(boolean check) throws Exception {
|
||||
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();
|
||||
private void initTimer(long delay, Target target, Trade chargeFor, TeleportCause cause)
|
||||
{
|
||||
this.started = System.currentTimeMillis();
|
||||
this.delay = delay;
|
||||
this.health = user.getHealth();
|
||||
this.initX = Math.round(user.getLocation().getX() * MOVE_CONSTANT);
|
||||
this.initY = Math.round(user.getLocation().getY() * MOVE_CONSTANT);
|
||||
this.initZ = Math.round(user.getLocation().getZ() * MOVE_CONSTANT);
|
||||
this.teleportTarget = target;
|
||||
this.chargeFor = chargeFor;
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
// When was the last teleportPlayer used?
|
||||
final long lastTime = teleportOwner.getLastTeleportTimestamp();
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
|
||||
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;
|
||||
} else if (lastTime > earliestLong
|
||||
&& cooldownApplies()) {
|
||||
time.setTimeInMillis(lastTime);
|
||||
time.add(Calendar.SECOND, (int) cooldown);
|
||||
time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
|
||||
throw new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis())));
|
||||
}
|
||||
}
|
||||
// if justCheck is set, don't update lastTeleport; we're just checking
|
||||
if (!check) {
|
||||
teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis());
|
||||
}
|
||||
}
|
||||
if (user == null || !user.isOnline() || user.getLocation() == null)
|
||||
{
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (Math.round(user.getLocation().getX() * MOVE_CONSTANT) != initX
|
||||
|| Math.round(user.getLocation().getY() * MOVE_CONSTANT) != initY
|
||||
|| Math.round(user.getLocation().getZ() * MOVE_CONSTANT) != initZ
|
||||
|| user.getHealth() < health)
|
||||
{ // user moved, cancel teleport
|
||||
cancel(true);
|
||||
return;
|
||||
}
|
||||
|
||||
private boolean cooldownApplies() {
|
||||
boolean applies = true;
|
||||
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;
|
||||
}
|
||||
health = user.getHealth(); // in case user healed, then later gets injured
|
||||
|
||||
private void warnUser(final IUser user, final double delay) {
|
||||
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())));
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
if (now > started + delay)
|
||||
{
|
||||
try
|
||||
{
|
||||
cooldown(false);
|
||||
user.sendMessage(_("teleportationCommencing"));
|
||||
try
|
||||
{
|
||||
|
||||
//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 {
|
||||
if (cooldown) {
|
||||
cooldown(false);
|
||||
}
|
||||
final ITarget target = new LocationTarget(loc);
|
||||
now(teleportOwner, target, cause);
|
||||
}
|
||||
now(teleportTarget, cause);
|
||||
if (chargeFor != null)
|
||||
{
|
||||
chargeFor.charge(user);
|
||||
}
|
||||
}
|
||||
catch (Throwable ex)
|
||||
{
|
||||
ess.getCommandHandler().showCommandError(user.getBase(), "teleport", ex);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
user.sendMessage(_("cooldownWithMessage", ex.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception {
|
||||
if (cooldown) {
|
||||
cooldown(false);
|
||||
}
|
||||
final ITarget target = new PlayerTarget(entity);
|
||||
now(teleportOwner, target, cause);
|
||||
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
|
||||
}
|
||||
public Teleport(IUser user, IEssentials ess)
|
||||
{
|
||||
this.user = user;
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception {
|
||||
cancel(false);
|
||||
teleportee.setLastLocation();
|
||||
Location loc = target.getLocation();
|
||||
public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
final Player player = user.getBase();
|
||||
final Location bed = player.getBedSpawnLocation();
|
||||
final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, bed == null ? player.getWorld().getSpawnLocation() : bed, bed != null);
|
||||
ess.getServer().getPluginManager().callEvent(pre);
|
||||
teleport(new Target(pre.getRespawnLocation()), chargeFor, cause);
|
||||
}
|
||||
|
||||
if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) {
|
||||
if (ess.getSettings().isTeleportSafetyEnabled()) {
|
||||
if (ess.getSettings().isForceDisableTeleportSafety()) {
|
||||
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
|
||||
} else {
|
||||
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()) {
|
||||
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
|
||||
} else {
|
||||
if (ess.getSettings().isTeleportToCenterLocation()) {
|
||||
loc = LocationUtil.getRoundedDestination(loc);
|
||||
}
|
||||
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
final Location loc = ess.getWarps().getWarp(warp);
|
||||
teleport(new Target(loc), chargeFor, cause);
|
||||
user.sendMessage(_("warpingTo", warp));
|
||||
}
|
||||
|
||||
//The teleportPlayer function is used when you want to normally teleportPlayer someone to a location or player.
|
||||
//This method is nolonger used internally and will be removed.
|
||||
@Deprecated
|
||||
@Override
|
||||
public void teleport(Location loc, Trade chargeFor) throws Exception {
|
||||
teleport(loc, chargeFor, TeleportCause.PLUGIN);
|
||||
}
|
||||
public void cooldown(boolean check) throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
user.checkCooldown(TimestampType.LASTTELEPORT, ess.getGroups().getTeleportCooldown(user), !check, Permissions.TELEPORT_COOLDOWN_BYPASS);
|
||||
}
|
||||
catch (CooldownException ex)
|
||||
{
|
||||
throw new Exception(_("timeBeforeTeleport", ex.getMessage()));
|
||||
|
||||
@Override
|
||||
public void teleport(Location loc, Trade chargeFor, 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);
|
||||
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName()));
|
||||
teleport(teleportOwner, target, chargeFor, cause);
|
||||
}
|
||||
public void cancel(boolean notifyUser)
|
||||
{
|
||||
if (teleTimer == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
ess.getServer().getScheduler().cancelTask(teleTimer);
|
||||
if (notifyUser)
|
||||
{
|
||||
user.sendMessage(_("pendingTeleportCancelled"));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
teleTimer = -1;
|
||||
}
|
||||
}
|
||||
|
||||
//This is used when teleporting to stored location
|
||||
@Override
|
||||
public void teleportPlayer(IUser teleportee, Location loc, Trade chargeFor, TeleportCause cause) throws Exception {
|
||||
teleport(teleportee, new LocationTarget(loc), chargeFor, cause);
|
||||
}
|
||||
public void cancel()
|
||||
{
|
||||
cancel(false);
|
||||
}
|
||||
|
||||
//This is used on /tphere
|
||||
@Override
|
||||
public void teleportPlayer(IUser teleportee, Player entity, Trade chargeFor, TeleportCause cause) throws Exception {
|
||||
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()));
|
||||
}
|
||||
public void teleport(Location loc, Trade chargeFor) throws Exception
|
||||
{
|
||||
teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN);
|
||||
}
|
||||
|
||||
private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception {
|
||||
double delay = ess.getSettings().getTeleportDelay();
|
||||
public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
teleport(new Target(loc), chargeFor, cause);
|
||||
}
|
||||
|
||||
Trade cashCharge = chargeFor;
|
||||
public void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
teleport(new Target(entity), chargeFor, cause);
|
||||
}
|
||||
|
||||
if (chargeFor != null) {
|
||||
chargeFor.isAffordableFor(teleportOwner);
|
||||
private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
double delay = ess.getGroups().getTeleportDelay(user);
|
||||
|
||||
//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 (chargeFor != null)
|
||||
{
|
||||
chargeFor.isAffordableFor(user);
|
||||
}
|
||||
cooldown(true);
|
||||
if (delay <= 0 || Permissions.TELEPORT_TIMER_BYPASS.isAuthorized(user))
|
||||
{
|
||||
cooldown(false);
|
||||
now(target, cause);
|
||||
if (chargeFor != null)
|
||||
{
|
||||
chargeFor.charge(user);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
cooldown(true);
|
||||
if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") || teleportee.isAuthorized("essentials.teleport.timer.bypass")) {
|
||||
cooldown(false);
|
||||
now(teleportee, target, cause);
|
||||
if (cashCharge != null) {
|
||||
cashCharge.charge(teleportOwner);
|
||||
}
|
||||
return;
|
||||
}
|
||||
cancel();
|
||||
Calendar c = new GregorianCalendar();
|
||||
c.add(Calendar.SECOND, (int)delay);
|
||||
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
|
||||
user.sendMessage(_("dontMoveMessage", Util.formatDateDiff(c.getTimeInMillis())));
|
||||
initTimer((long)(delay * 1000.0), target, chargeFor, cause);
|
||||
|
||||
cancel(false);
|
||||
warnUser(teleportee, delay);
|
||||
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
|
||||
}
|
||||
teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10);
|
||||
}
|
||||
|
||||
private void teleportOther(IUser teleporter, IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception {
|
||||
double delay = ess.getSettings().getTeleportDelay();
|
||||
private void now(Target target, TeleportCause cause) throws Exception
|
||||
{
|
||||
cancel();
|
||||
user.setLastLocation();
|
||||
user.getBase().teleport(Util.getSafeDestination(target.getLocation()), cause);
|
||||
}
|
||||
|
||||
Trade cashCharge = chargeFor;
|
||||
public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception
|
||||
{
|
||||
if (cooldown)
|
||||
{
|
||||
cooldown(false);
|
||||
}
|
||||
now(new Target(loc), cause);
|
||||
}
|
||||
|
||||
if (teleporter != null && chargeFor != null) {
|
||||
chargeFor.isAffordableFor(teleporter);
|
||||
public void now(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
|
||||
{
|
||||
cooldown(false);
|
||||
chargeFor.charge(user);
|
||||
now(new Target(loc), cause);
|
||||
}
|
||||
|
||||
//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);
|
||||
}
|
||||
}
|
||||
public void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception
|
||||
{
|
||||
if (cooldown)
|
||||
{
|
||||
cooldown(false);
|
||||
}
|
||||
now(new Target(entity), cause);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
public void back(Trade chargeFor) throws Exception
|
||||
{
|
||||
user.acquireReadLock();
|
||||
try
|
||||
{
|
||||
teleport(new Target(user.getData().getLastLocation().getBukkitLocation()), chargeFor, TeleportCause.COMMAND);
|
||||
}
|
||||
finally
|
||||
{
|
||||
user.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
cancel(false);
|
||||
warnUser(teleportee, delay);
|
||||
initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false);
|
||||
}
|
||||
public void back() throws Exception
|
||||
{
|
||||
user.acquireReadLock();
|
||||
try
|
||||
{
|
||||
now(new Target(user.getData().getLastLocation().getBukkitLocation()), TeleportCause.COMMAND);
|
||||
}
|
||||
finally
|
||||
{
|
||||
user.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
//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 {
|
||||
double delay = ess.getSettings().getTeleportDelay();
|
||||
if (chargeFor != null) {
|
||||
chargeFor.isAffordableFor(teleportOwner);
|
||||
}
|
||||
cooldown(true);
|
||||
if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass")) {
|
||||
cooldown(false);
|
||||
respawnNow(teleportOwner, cause);
|
||||
if (chargeFor != null) {
|
||||
chargeFor.charge(teleportOwner);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
cancel(false);
|
||||
warnUser(teleportOwner, delay);
|
||||
initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true);
|
||||
}
|
||||
|
||||
void respawnNow(IUser teleportee, TeleportCause cause) throws Exception {
|
||||
final Player player = teleportee.getBase();
|
||||
Location bed = player.getBedSpawnLocation();
|
||||
if (bed != null) {
|
||||
now(teleportee, new LocationTarget(bed), cause);
|
||||
} 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);
|
||||
now(teleportee, new LocationTarget(pre.getRespawnLocation()), cause);
|
||||
}
|
||||
}
|
||||
|
||||
//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 {
|
||||
UserWarpEvent event = new UserWarpEvent(teleportee, warp, chargeFor);
|
||||
Bukkit.getServer().getPluginManager().callEvent(event);
|
||||
|
||||
if(event.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
warp = event.getWarp();
|
||||
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()));
|
||||
}
|
||||
teleport(teleportee, new LocationTarget(loc), chargeFor, cause);
|
||||
}
|
||||
|
||||
//The back function is a wrapper used to teleportPlayer a player /back to their previous location.
|
||||
@Override
|
||||
public void back(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
|
||||
public void back(IUser teleporter, 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()));
|
||||
teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND);
|
||||
}
|
||||
|
||||
//This function is used to throw a user back after a jail sentence
|
||||
@Override
|
||||
public void back() throws Exception {
|
||||
now(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND);
|
||||
}
|
||||
|
||||
public void setTpType(TeleportType tpType) {
|
||||
this.tpType = tpType;
|
||||
}
|
||||
|
||||
//If we need to cancelTimer a pending teleportPlayer call this method
|
||||
private void cancel(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) {
|
||||
timedTeleport = new TimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn);
|
||||
}
|
||||
public void home(IUser user, String home, Trade chargeFor) throws Exception
|
||||
{
|
||||
final Location loc = user.getHome(home);
|
||||
if (loc == null)
|
||||
{
|
||||
throw new NotEnoughArgumentsException();
|
||||
}
|
||||
teleport(new Target(loc), chargeFor, TeleportCause.COMMAND);
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
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 static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
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;
|
||||
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;
|
||||
// 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;
|
||||
|
||||
TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, 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 (Exception ex) {
|
||||
teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
|
||||
if (teleportOwner != teleportUser) {
|
||||
teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage()));
|
||||
}
|
||||
}
|
||||
try {
|
||||
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 ignored) {}
|
||||
|
||||
} catch (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(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,359 +1,337 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.ChargeException;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.ISettings;
|
||||
import com.earth2me.essentials.api.IUser;
|
||||
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
|
||||
import com.earth2me.essentials.craftbukkit.SetExpFix;
|
||||
import com.earth2me.essentials.utils.NumberUtil;
|
||||
import net.ess3.api.IEssentials;
|
||||
import net.ess3.api.IUser;
|
||||
import net.ess3.api.MaxMoneyException;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Item;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.earth2me.essentials.perm.NoCommandCostPermissions;
|
||||
import com.earth2me.essentials.perm.Permissions;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
import lombok.Cleanup;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Item;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
|
||||
public class Trade {
|
||||
private final transient String command;
|
||||
private final transient Trade fallbackTrade;
|
||||
private final transient BigDecimal money;
|
||||
private final transient ItemStack itemStack;
|
||||
private final transient Integer exp;
|
||||
private final transient IEssentials ess;
|
||||
public class Trade
|
||||
{
|
||||
private final transient String command;
|
||||
private final transient Double money;
|
||||
private final transient ItemStack itemStack;
|
||||
private final transient Integer exp;
|
||||
private final transient IEssentials ess;
|
||||
|
||||
public Trade(final String command, final IEssentials ess)
|
||||
{
|
||||
this(command, null, null, null, ess);
|
||||
}
|
||||
|
||||
public enum TradeType {
|
||||
MONEY,
|
||||
EXP,
|
||||
ITEM
|
||||
}
|
||||
public Trade(final double money, final IEssentials ess)
|
||||
{
|
||||
this(null, money, null, null, ess);
|
||||
}
|
||||
|
||||
public Trade(final ItemStack items, final IEssentials ess)
|
||||
{
|
||||
this(null, null, items, null, ess);
|
||||
}
|
||||
|
||||
public enum OverflowType {
|
||||
ABORT,
|
||||
DROP,
|
||||
RETURN
|
||||
}
|
||||
public Trade(final int exp, final IEssentials ess)
|
||||
{
|
||||
this(null, null, null, exp, ess);
|
||||
}
|
||||
|
||||
public Trade(final String command, final IEssentials ess) {
|
||||
this(command, null, null, null, null, ess);
|
||||
}
|
||||
private Trade(final String command, final Double money, final ItemStack item, final Integer exp, final IEssentials ess)
|
||||
{
|
||||
this.command = command;
|
||||
this.money = money;
|
||||
this.itemStack = item;
|
||||
this.exp = exp;
|
||||
this.ess = ess;
|
||||
}
|
||||
|
||||
public Trade(final String command, final Trade fallback, final IEssentials ess) {
|
||||
this(command, fallback, null, null, null, ess);
|
||||
}
|
||||
public void isAffordableFor(final IUser user) throws ChargeException
|
||||
{
|
||||
final double mon = user.getMoney();
|
||||
if (getMoney() != null
|
||||
&& mon < getMoney()
|
||||
&& getMoney() > 0
|
||||
&& !Permissions.ECO_LOAN.isAuthorized(user))
|
||||
{
|
||||
throw new ChargeException(_("notEnoughMoney"));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public Trade(final double money, final com.earth2me.essentials.IEssentials ess) {
|
||||
this(null, null, BigDecimal.valueOf(money), null, null, (IEssentials) ess);
|
||||
}
|
||||
if (getItemStack() != null
|
||||
&& !InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
|
||||
{
|
||||
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
|
||||
}
|
||||
|
||||
public Trade(final BigDecimal money, final IEssentials ess) {
|
||||
this(null, null, money, null, null, ess);
|
||||
}
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
|
||||
public Trade(final ItemStack items, final IEssentials ess) {
|
||||
this(null, null, null, items, null, ess);
|
||||
}
|
||||
if (command != null && !command.isEmpty()
|
||||
&& !NoCommandCostPermissions.getPermission(command).isAuthorized(user)
|
||||
&& mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command)
|
||||
&& 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command)
|
||||
&& !Permissions.ECO_LOAN.isAuthorized(user))
|
||||
{
|
||||
throw new ChargeException(_("notEnoughMoney"));
|
||||
}
|
||||
|
||||
public Trade(final int exp, final IEssentials ess) {
|
||||
this(null, null, null, null, exp, ess);
|
||||
}
|
||||
if (exp != null && exp > 0
|
||||
&& SetExpFix.getTotalExperience(user) < exp)
|
||||
{
|
||||
throw new ChargeException(_("notEnoughExperience"));
|
||||
}
|
||||
}
|
||||
|
||||
private Trade(final String command, final Trade fallback, final BigDecimal money, final ItemStack item, final Integer exp, final IEssentials ess) {
|
||||
this.command = command;
|
||||
this.fallbackTrade = fallback;
|
||||
this.money = money;
|
||||
this.itemStack = item;
|
||||
this.exp = exp;
|
||||
this.ess = ess;
|
||||
}
|
||||
public void pay(final IUser user)
|
||||
{
|
||||
pay(user, true);
|
||||
}
|
||||
|
||||
public void isAffordableFor(final IUser user) throws ChargeException {
|
||||
public boolean pay(final IUser user, final boolean dropItems)
|
||||
{
|
||||
boolean success = true;
|
||||
if (getMoney() != null && getMoney() > 0)
|
||||
{
|
||||
user.giveMoney(getMoney());
|
||||
}
|
||||
if (getItemStack() != null)
|
||||
{
|
||||
if (dropItems)
|
||||
{
|
||||
final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItem(user.getInventory(), true, getItemStack());
|
||||
final Location loc = user.getLocation();
|
||||
for (ItemStack dropStack : leftOver.values())
|
||||
{
|
||||
final int maxStackSize = dropStack.getType().getMaxStackSize();
|
||||
final int stacks = dropStack.getAmount() / maxStackSize;
|
||||
final int leftover = dropStack.getAmount() % maxStackSize;
|
||||
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
|
||||
for (int i = 0; i < stacks; i++)
|
||||
{
|
||||
final ItemStack stack = dropStack.clone();
|
||||
stack.setAmount(maxStackSize);
|
||||
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
|
||||
}
|
||||
if (leftover > 0)
|
||||
{
|
||||
final ItemStack stack = dropStack.clone();
|
||||
stack.setAmount(leftover);
|
||||
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
success = InventoryWorkaround.addAllItems(user.getInventory(), true, getItemStack());
|
||||
}
|
||||
user.updateInventory();
|
||||
}
|
||||
if (getExperience() != null)
|
||||
{
|
||||
SetExpFix.setTotalExperience(user, SetExpFix.getTotalExperience(user) + getExperience());
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge.");
|
||||
}
|
||||
public void charge(final IUser user) throws ChargeException
|
||||
{
|
||||
if (getMoney() != null)
|
||||
{
|
||||
final double mon = user.getMoney();
|
||||
if (mon < getMoney() && getMoney() > 0 && !Permissions.ECO_LOAN.isAuthorized(user))
|
||||
{
|
||||
throw new ChargeException(_("notEnoughMoney"));
|
||||
}
|
||||
user.takeMoney(getMoney());
|
||||
}
|
||||
if (getItemStack() != null)
|
||||
{
|
||||
if (!InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
|
||||
{
|
||||
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
|
||||
}
|
||||
InventoryWorkaround.removeItem(user.getInventory(), true, true, getItemStack());
|
||||
user.updateInventory();
|
||||
}
|
||||
if (command != null && !command.isEmpty()
|
||||
&& !NoCommandCostPermissions.getPermission(command).isAuthorized(user))
|
||||
{
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
final double mon = user.getMoney();
|
||||
final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command);
|
||||
if (mon < cost && cost > 0 && !Permissions.ECO_LOAN.isAuthorized(user))
|
||||
{
|
||||
throw new ChargeException(_("notEnoughMoney"));
|
||||
}
|
||||
user.takeMoney(cost);
|
||||
}
|
||||
if (getExperience() != null)
|
||||
{
|
||||
final int experience = SetExpFix.getTotalExperience(user);
|
||||
if (experience < getExperience() && getExperience() > 0)
|
||||
{
|
||||
throw new ChargeException(_("notEnoughExperience"));
|
||||
}
|
||||
SetExpFix.setTotalExperience(user, experience - getExperience());
|
||||
}
|
||||
}
|
||||
|
||||
if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) {
|
||||
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)));
|
||||
}
|
||||
public Double getMoney()
|
||||
{
|
||||
return money;
|
||||
}
|
||||
|
||||
if (getItemStack() != null && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
|
||||
throw new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack())));
|
||||
}
|
||||
public ItemStack getItemStack()
|
||||
{
|
||||
return itemStack;
|
||||
}
|
||||
|
||||
BigDecimal money;
|
||||
if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) {
|
||||
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess)));
|
||||
}
|
||||
public Integer getExperience()
|
||||
{
|
||||
return exp;
|
||||
}
|
||||
private static FileWriter fw = null;
|
||||
|
||||
if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) {
|
||||
throw new ChargeException(tl("notEnoughExperience"));
|
||||
}
|
||||
}
|
||||
public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess)
|
||||
{
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
if (!settings.getData().getEconomy().isLogEnabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (fw == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
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("\",\"");
|
||||
if (sender != null)
|
||||
{
|
||||
sb.append(sender);
|
||||
}
|
||||
sb.append("\",");
|
||||
if (charge == null)
|
||||
{
|
||||
sb.append("\"\",\"\",\"\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (charge.getItemStack() != null)
|
||||
{
|
||||
sb.append(charge.getItemStack().getAmount()).append(",");
|
||||
sb.append(charge.getItemStack().getType().toString()).append(",");
|
||||
sb.append(charge.getItemStack().getDurability());
|
||||
}
|
||||
if (charge.getMoney() != null)
|
||||
{
|
||||
sb.append(charge.getMoney()).append(",");
|
||||
sb.append("money").append(",");
|
||||
sb.append(settings.getData().getEconomy().getCurrencySymbol());
|
||||
}
|
||||
if (charge.getExperience() != null)
|
||||
{
|
||||
sb.append(charge.getExperience()).append(",");
|
||||
sb.append("exp").append(",");
|
||||
sb.append("\"\"");
|
||||
}
|
||||
}
|
||||
sb.append(",\"");
|
||||
if (receiver != null)
|
||||
{
|
||||
sb.append(receiver);
|
||||
}
|
||||
sb.append("\",");
|
||||
if (pay == null)
|
||||
{
|
||||
sb.append("\"\",\"\",\"\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (pay.getItemStack() != null)
|
||||
{
|
||||
sb.append(pay.getItemStack().getAmount()).append(",");
|
||||
sb.append(pay.getItemStack().getType().toString()).append(",");
|
||||
sb.append(pay.getItemStack().getDurability());
|
||||
}
|
||||
if (pay.getMoney() != null)
|
||||
{
|
||||
sb.append(pay.getMoney()).append(",");
|
||||
sb.append("money").append(",");
|
||||
sb.append(settings.getData().getEconomy().getCurrencySymbol());
|
||||
}
|
||||
if (pay.getExperience() != null)
|
||||
{
|
||||
sb.append(pay.getExperience()).append(",");
|
||||
sb.append("exp").append(",");
|
||||
sb.append("\"\"");
|
||||
}
|
||||
}
|
||||
if (loc == null)
|
||||
{
|
||||
sb.append(",\"\",\"\",\"\",\"\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.append(",\"");
|
||||
sb.append(loc.getWorld().getName()).append("\",");
|
||||
sb.append(loc.getBlockX()).append(",");
|
||||
sb.append(loc.getBlockY()).append(",");
|
||||
sb.append(loc.getBlockZ()).append(",");
|
||||
}
|
||||
sb.append("\n");
|
||||
try
|
||||
{
|
||||
fw.write(sb.toString());
|
||||
fw.flush();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
//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.
|
||||
|
||||
if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) || (loc != null && !ess.getSettings().isEcoLogEnabled())) {
|
||||
return;
|
||||
}
|
||||
if (fw == null) {
|
||||
try {
|
||||
fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true);
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
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("\",\"");
|
||||
if (sender != null) {
|
||||
sb.append(sender);
|
||||
}
|
||||
sb.append("\",");
|
||||
if (charge == null) {
|
||||
sb.append("\"\",\"\",\"\"");
|
||||
} else {
|
||||
if (charge.getItemStack() != null) {
|
||||
sb.append(charge.getItemStack().getAmount()).append(",");
|
||||
sb.append(charge.getItemStack().getType().toString()).append(",");
|
||||
sb.append(charge.getItemStack().getDurability());
|
||||
}
|
||||
if (charge.getMoney() != null) {
|
||||
sb.append(charge.getMoney()).append(",");
|
||||
sb.append("money").append(",");
|
||||
sb.append(ess.getSettings().getCurrencySymbol());
|
||||
}
|
||||
if (charge.getExperience() != null) {
|
||||
sb.append(charge.getExperience()).append(",");
|
||||
sb.append("exp").append(",");
|
||||
sb.append("\"\"");
|
||||
}
|
||||
}
|
||||
sb.append(",\"");
|
||||
if (receiver != null) {
|
||||
sb.append(receiver);
|
||||
}
|
||||
sb.append("\",");
|
||||
if (pay == null) {
|
||||
sb.append("\"\",\"\",\"\"");
|
||||
} else {
|
||||
if (pay.getItemStack() != null) {
|
||||
sb.append(pay.getItemStack().getAmount()).append(",");
|
||||
sb.append(pay.getItemStack().getType().toString()).append(",");
|
||||
sb.append(pay.getItemStack().getDurability());
|
||||
}
|
||||
if (pay.getMoney() != null) {
|
||||
sb.append(pay.getMoney()).append(",");
|
||||
sb.append("money").append(",");
|
||||
sb.append(ess.getSettings().getCurrencySymbol());
|
||||
}
|
||||
if (pay.getExperience() != null) {
|
||||
sb.append(pay.getExperience()).append(",");
|
||||
sb.append("exp").append(",");
|
||||
sb.append("\"\"");
|
||||
}
|
||||
}
|
||||
if (loc == null) {
|
||||
sb.append(",\"\",\"\",\"\",\"\"");
|
||||
} else {
|
||||
sb.append(",\"");
|
||||
sb.append(loc.getWorld().getName()).append("\",");
|
||||
sb.append(loc.getBlockX()).append(",");
|
||||
sb.append(loc.getBlockY()).append(",");
|
||||
sb.append(loc.getBlockZ()).append(",");
|
||||
}
|
||||
sb.append("\n");
|
||||
try {
|
||||
fw.write(sb.toString());
|
||||
fw.flush();
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static void closeLog() {
|
||||
if (fw != null) {
|
||||
try {
|
||||
fw.close();
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger("Essentials").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
fw = null;
|
||||
}
|
||||
}
|
||||
public static void closeLog()
|
||||
{
|
||||
if (fw != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
fw.close();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
|
||||
}
|
||||
fw = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.google.common.io.Files;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.*;
|
||||
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 loading = false;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
writeScheduler.scheduleWithFixedDelay(writeTaskRunnable, 5, 5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void loadAllUsers(final ConcurrentSkipListMap<String, UUID> names, final ConcurrentSkipListMap<UUID, ArrayList<String>> history) {
|
||||
try {
|
||||
if (!userList.exists()) {
|
||||
userList.createNewFile();
|
||||
}
|
||||
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "Reading usermap from disk");
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return;
|
||||
}
|
||||
|
||||
names.clear();
|
||||
history.clear();
|
||||
loading = true;
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(userList))) {
|
||||
while (true) {
|
||||
final String line = reader.readLine();
|
||||
if (line == null) {
|
||||
break;
|
||||
} else {
|
||||
final String[] values = splitPattern.split(line);
|
||||
if (values.length == 2) {
|
||||
final String name = values[0];
|
||||
final UUID uuid = UUID.fromString(values[1]);
|
||||
names.put(name, uuid);
|
||||
if (!history.containsKey(uuid)) {
|
||||
final ArrayList<String> list = new ArrayList<>();
|
||||
list.add(name);
|
||||
history.put(uuid, list);
|
||||
} else {
|
||||
final ArrayList<String> list = history.get(uuid);
|
||||
if (!list.contains(name)) {
|
||||
list.add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
loading = false;
|
||||
} catch (IOException ex) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void writeUUIDMap() {
|
||||
pendingWrite = true;
|
||||
}
|
||||
|
||||
public void forceWriteUUIDMap() {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "Forcing usermap write to disk");
|
||||
}
|
||||
pendingWrite = true;
|
||||
writeTaskRunnable.run();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
writeScheduler.submit(writeTaskRunnable);
|
||||
writeScheduler.shutdown();
|
||||
}
|
||||
|
||||
private static class WriteRunner implements Runnable {
|
||||
private final File location;
|
||||
private final File endFile;
|
||||
private final Map<String, UUID> names;
|
||||
|
||||
private WriteRunner(final File location, final File endFile, final Map<String, UUID> names) {
|
||||
this.location = location;
|
||||
this.endFile = endFile;
|
||||
this.names = new HashMap<>(names);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
pendingWrite = false;
|
||||
if (loading || names.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
File configFile = null;
|
||||
|
||||
try {
|
||||
configFile = File.createTempFile("usermap", ".tmp.csv", location);
|
||||
|
||||
final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile));
|
||||
for (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) {
|
||||
try {
|
||||
if (configFile != null && configFile.exists()) {
|
||||
Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv"));
|
||||
}
|
||||
} catch (Exception ex2) {
|
||||
Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2);
|
||||
}
|
||||
Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,926 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.commands.IEssentialsCommand;
|
||||
import com.earth2me.essentials.messaging.IMessageRecipient;
|
||||
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
|
||||
import com.earth2me.essentials.register.payment.Method;
|
||||
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.entity.Player;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
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 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;
|
||||
private transient long lastActivity = System.currentTimeMillis();
|
||||
private boolean hidden = false;
|
||||
private boolean rightClickJump = false;
|
||||
private transient Location afkPosition = null;
|
||||
private boolean invSee = false;
|
||||
private boolean recipeSee = false;
|
||||
private boolean enderSee = false;
|
||||
private transient long teleportInvulnerabilityTimestamp = 0;
|
||||
private boolean ignoreMsg = false;
|
||||
private String afkMessage;
|
||||
private long afkSince;
|
||||
private Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
|
||||
private String confirmingClearCommand;
|
||||
private long lastNotifiedAboutMailsMs;
|
||||
|
||||
public User(final Player base, final IEssentials ess) {
|
||||
super(base, ess);
|
||||
teleport = new Teleport(this, ess);
|
||||
if (isAfk()) {
|
||||
afkPosition = this.getLocation();
|
||||
}
|
||||
if (this.getBase().isOnline()) {
|
||||
lastOnlineActivity = System.currentTimeMillis();
|
||||
}
|
||||
this.messageRecipient = new SimpleMessageRecipient(ess, this);
|
||||
}
|
||||
|
||||
User update(final Player base) {
|
||||
setBase(base);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthorized(final IEssentialsCommand cmd) {
|
||||
return isAuthorized(cmd, "essentials.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) {
|
||||
return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthorized(final String node) {
|
||||
final boolean result = isAuthorizedCheck(node);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " - " + result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPermissionSet(final String node) {
|
||||
return isPermSetCheck(node);
|
||||
}
|
||||
|
||||
private boolean isAuthorizedCheck(final String node) {
|
||||
|
||||
if (base instanceof OfflinePlayer) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return ess.getPermissionsHandler().hasPermission(base, node);
|
||||
} catch (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 (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;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void healCooldown() throws Exception {
|
||||
final Calendar now = new GregorianCalendar();
|
||||
if (getLastHealTimestamp() > 0) {
|
||||
final double cooldown = ess.getSettings().getHealCooldown();
|
||||
final Calendar cooldownTime = new GregorianCalendar();
|
||||
cooldownTime.setTimeInMillis(getLastHealTimestamp());
|
||||
cooldownTime.add(Calendar.SECOND, (int) cooldown);
|
||||
cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
|
||||
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) {
|
||||
throw new Exception(tl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())));
|
||||
}
|
||||
}
|
||||
setLastHealTimestamp(now.getTimeInMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void giveMoney(final BigDecimal value) throws MaxMoneyException {
|
||||
giveMoney(value, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException {
|
||||
if (value.signum() == 0) {
|
||||
return;
|
||||
}
|
||||
setMoney(getMoney().add(value));
|
||||
sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess)));
|
||||
if (initiator != null) {
|
||||
initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void payUser(final User reciever, final BigDecimal value) 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));
|
||||
sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName()));
|
||||
reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName()));
|
||||
} else {
|
||||
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void takeMoney(final BigDecimal value) {
|
||||
takeMoney(value, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void takeMoney(final BigDecimal value, final CommandSource initiator) {
|
||||
if (value.signum() == 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setMoney(getMoney().subtract(value));
|
||||
} catch (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)));
|
||||
if (initiator != null) {
|
||||
initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canAfford(final BigDecimal cost) {
|
||||
return canAfford(cost, true);
|
||||
}
|
||||
|
||||
public boolean canAfford(final BigDecimal cost, final boolean permcheck) {
|
||||
if (cost.signum() <= 0) {
|
||||
return true;
|
||||
}
|
||||
final BigDecimal remainingBalance = getMoney().subtract(cost);
|
||||
if (!permcheck || isAuthorized("essentials.eco.loan")) {
|
||||
return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0);
|
||||
}
|
||||
return (remainingBalance.signum() >= 0);
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
ess.runTaskAsynchronously(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
_dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void _dispose() {
|
||||
if (!base.isOnline()) {
|
||||
this.base = new OfflinePlayer(getConfigUUID(), ess.getServer());
|
||||
}
|
||||
cleanup();
|
||||
}
|
||||
|
||||
@Override
|
||||
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
|
||||
public void setLastLocation() {
|
||||
setLastLocation(this.getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLogoutLocation() {
|
||||
setLogoutLocation(this.getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestTeleport(final User player, final boolean here) {
|
||||
teleportRequestTime = System.currentTimeMillis();
|
||||
teleportRequester = player == null ? null : player.getBase().getUniqueId();
|
||||
teleportRequestHere = here;
|
||||
if (player == null) {
|
||||
teleportLocation = null;
|
||||
} else {
|
||||
teleportLocation = here ? player.getLocation() : this.getLocation();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasOutstandingTeleportRequest() {
|
||||
if (getTeleportRequest() != null) { // Player has outstanding teleport request.
|
||||
long timeout = ess.getSettings().getTpaAcceptCancellation();
|
||||
if (timeout != 0) {
|
||||
if ((System.currentTimeMillis() - getTeleportRequestTime()) / 1000 <= timeout) { // Player has outstanding request
|
||||
return true;
|
||||
} else { // outstanding request expired.
|
||||
requestTeleport(null, false);
|
||||
return false;
|
||||
}
|
||||
} else { // outstanding request does not expire
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public UUID getTeleportRequest() {
|
||||
return teleportRequester;
|
||||
}
|
||||
|
||||
public boolean isTpRequestHere() {
|
||||
return teleportRequestHere;
|
||||
}
|
||||
|
||||
public Location getTpRequestLocation() {
|
||||
return teleportLocation;
|
||||
}
|
||||
|
||||
public String getNick(final boolean longnick) {
|
||||
return getNick(longnick, true, true);
|
||||
}
|
||||
|
||||
public String getNick(final boolean longnick, final boolean withPrefix, final boolean withSuffix) {
|
||||
final StringBuilder prefix = new StringBuilder();
|
||||
String nickname;
|
||||
String suffix = "";
|
||||
final String nick = getNickname();
|
||||
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) {
|
||||
nickname = getName();
|
||||
} else if (nick.equalsIgnoreCase(getName())) {
|
||||
nickname = nick;
|
||||
} else {
|
||||
nickname = FormatUtil.replaceFormat(ess.getSettings().getNicknamePrefix()) + nick;
|
||||
suffix = "§r";
|
||||
}
|
||||
|
||||
if (this.getBase().isOp()) {
|
||||
try {
|
||||
final ChatColor opPrefix = ess.getSettings().getOperatorColor();
|
||||
if (opPrefix != null && opPrefix.toString().length() > 0) {
|
||||
prefix.insert(0, opPrefix.toString());
|
||||
suffix = "§r";
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
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('&', '§');
|
||||
prefix.insert(0, ptext);
|
||||
suffix = "§r";
|
||||
}
|
||||
if (withSuffix || !ess.getSettings().disableSuffix()) {
|
||||
final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§');
|
||||
suffix = stext + "§r";
|
||||
suffix = suffix.replace("§f§f", "§f").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);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public void setDisplayNick() {
|
||||
if (base.isOnline() && ess.getSettings().changeDisplayName()) {
|
||||
this.getBase().setDisplayName(getNick(true));
|
||||
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());
|
||||
try {
|
||||
this.getBase().setPlayerListName(name);
|
||||
} catch (IllegalArgumentException e) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Teleport getTeleport() {
|
||||
return teleport;
|
||||
}
|
||||
|
||||
public long getLastOnlineActivity() {
|
||||
return lastOnlineActivity;
|
||||
}
|
||||
|
||||
public void setLastOnlineActivity(final long timestamp) {
|
||||
lastOnlineActivity = timestamp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getMoney() {
|
||||
final long start = System.nanoTime();
|
||||
final BigDecimal value = _getMoney();
|
||||
final long elapsed = System.nanoTime() - start;
|
||||
if (elapsed > ess.getSettings().getEconomyLagWarning()) {
|
||||
ess.getLogger().log(Level.INFO, "Lag Notice - Slow Economy Response - Request took over {0}ms!", elapsed / 1000000.0);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private BigDecimal _getMoney() {
|
||||
if (ess.getSettings().isEcoDisabled()) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().info("Internal economy functions disabled, aborting balance check.");
|
||||
}
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
if (Methods.hasMethod()) {
|
||||
try {
|
||||
final Method method = Methods.getMethod();
|
||||
if (!method.hasAccount(this.getName())) {
|
||||
throw new Exception();
|
||||
}
|
||||
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
|
||||
return BigDecimal.valueOf(account.balance());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
}
|
||||
return super.getMoney();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMoney(final BigDecimal value) throws MaxMoneyException {
|
||||
if (ess.getSettings().isEcoDisabled()) {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().info("Internal economy functions disabled, aborting balance change.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
final BigDecimal oldBalance = _getMoney();
|
||||
|
||||
UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value);
|
||||
ess.getServer().getPluginManager().callEvent(updateEvent);
|
||||
BigDecimal newBalance = updateEvent.getNewBalance();
|
||||
|
||||
if (Methods.hasMethod()) {
|
||||
try {
|
||||
final Method method = Methods.getMethod();
|
||||
if (!method.hasAccount(this.getName())) {
|
||||
throw new Exception();
|
||||
}
|
||||
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
|
||||
account.set(newBalance.doubleValue());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
}
|
||||
super.setMoney(newBalance, true);
|
||||
Trade.log("Update", "Set", "API", getName(), new Trade(newBalance, ess), null, null, null, ess);
|
||||
}
|
||||
|
||||
public void updateMoneyCache(final BigDecimal value) {
|
||||
if (ess.getSettings().isEcoDisabled()) {
|
||||
return;
|
||||
}
|
||||
if (Methods.hasMethod() && super.getMoney() != value) {
|
||||
try {
|
||||
super.setMoney(value, false);
|
||||
} catch (MaxMoneyException ex) {
|
||||
// We don't want to throw any errors here, just updating a cache
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAfk(final boolean set) {
|
||||
final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set);
|
||||
ess.getServer().getPluginManager().callEvent(afkEvent);
|
||||
if (afkEvent.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") || set && ess.getSettings().sleepIgnoresAfkPlayers());
|
||||
if (set && !isAfk()) {
|
||||
afkPosition = this.getLocation();
|
||||
this.afkSince = System.currentTimeMillis();
|
||||
} else if (!set && isAfk()) {
|
||||
afkPosition = null;
|
||||
this.afkMessage = null;
|
||||
this.afkSince = 0;
|
||||
}
|
||||
_setAfk(set);
|
||||
updateAfkListName();
|
||||
}
|
||||
|
||||
private void updateAfkListName() {
|
||||
if (ess.getSettings().isAfkListName()) {
|
||||
if(isAfk()) {
|
||||
String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName());
|
||||
getBase().setPlayerListName(afkName);
|
||||
} else {
|
||||
getBase().setPlayerListName(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean toggleAfk() {
|
||||
setAfk(!isAfk());
|
||||
return isAfk();
|
||||
}
|
||||
|
||||
@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) {
|
||||
setLastLogout(getLastOnlineActivity());
|
||||
}
|
||||
}
|
||||
|
||||
//Returns true if status expired during this check
|
||||
public boolean checkJailTimeout(final long currentTime) {
|
||||
if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) {
|
||||
final JailStatusChangeEvent event = new JailStatusChangeEvent(this, null, false);
|
||||
ess.getServer().getPluginManager().callEvent(event);
|
||||
|
||||
if (!event.isCancelled()) {
|
||||
setJailTimeout(0);
|
||||
setJailed(false);
|
||||
sendMessage(tl("haveBeenReleased"));
|
||||
setJail(null);
|
||||
if (ess.getSettings().isTeleportBackWhenFreedFromJail()) {
|
||||
try {
|
||||
getTeleport().back();
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
getTeleport().respawn(null, TeleportCause.PLUGIN);
|
||||
} catch (Exception ex1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//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);
|
||||
ess.getServer().getPluginManager().callEvent(event);
|
||||
|
||||
if (!event.isCancelled()) {
|
||||
setMuteTimeout(0);
|
||||
sendMessage(tl("canTalkAgain"));
|
||||
setMuted(false);
|
||||
setMuteReason(null);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void updateActivity(final boolean broadcast) {
|
||||
if (isAfk()) {
|
||||
setAfk(false);
|
||||
if (broadcast && !isHidden()) {
|
||||
setDisplayNick();
|
||||
final String msg = tl("userIsNotAway", getDisplayName());
|
||||
if (!msg.isEmpty()) {
|
||||
ess.broadcastMessage(this, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void updateActivityOnMove(final boolean broadcast) {
|
||||
if(ess.getSettings().cancelAfkOnMove()) {
|
||||
updateActivity(broadcast);
|
||||
}
|
||||
}
|
||||
|
||||
public void updateActivityOnInteract(final boolean broadcast) {
|
||||
if(ess.getSettings().cancelAfkOnInteract()) {
|
||||
updateActivity(broadcast);
|
||||
}
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
// Graceful time before the first afk check call.
|
||||
if (System.currentTimeMillis() - lastActivity <= 10000) {
|
||||
return;
|
||||
}
|
||||
|
||||
final long autoafkkick = ess.getSettings().getAutoAfkKick();
|
||||
if (autoafkkick > 0
|
||||
&& lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
|
||||
&& !isAuthorized("essentials.kick.exempt")
|
||||
&& !isAuthorized("essentials.afk.kickexempt")) {
|
||||
final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
|
||||
lastActivity = 0;
|
||||
this.getBase().kickPlayer(kickReason);
|
||||
|
||||
|
||||
for (User user : ess.getOnlineUsers()) {
|
||||
if (user.isAuthorized("essentials.kick.notify")) {
|
||||
user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason));
|
||||
}
|
||||
}
|
||||
}
|
||||
final long autoafk = ess.getSettings().getAutoAfk();
|
||||
if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk.auto")) {
|
||||
setAfk(true);
|
||||
if (!isHidden()) {
|
||||
setDisplayNick();
|
||||
final String msg = tl("userIsAway", getDisplayName());
|
||||
if (!msg.isEmpty()) {
|
||||
ess.broadcastMessage(this, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Location getAfkPosition() {
|
||||
return afkPosition;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGodModeEnabled() {
|
||||
if (super.isGodModeEnabled()) {
|
||||
// This enables the no-god-in-worlds functionality where the actual player god mode state is never modified in disabled worlds,
|
||||
// but this method gets called every time the player takes damage. In the case that the world has god-mode disabled then this method
|
||||
// will return false and the player will take damage, even though they are in god mode (isGodModeEnabledRaw()).
|
||||
if (!ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
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 false;
|
||||
}
|
||||
|
||||
public boolean isGodModeEnabledRaw() {
|
||||
return super.isGodModeEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGroup() {
|
||||
final String result = ess.getPermissionsHandler().getGroup(base);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "looking up groupname of " + base.getName() + " - " + result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inGroup(final String group) {
|
||||
final boolean result = ess.getPermissionsHandler().inGroup(base, group);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " is in group " + group + " - " + result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canBuild() {
|
||||
if (this.getBase().isOp()) {
|
||||
return true;
|
||||
}
|
||||
return ess.getPermissionsHandler().canBuild(base, getGroup());
|
||||
}
|
||||
|
||||
public long getTeleportRequestTime() {
|
||||
return teleportRequestTime;
|
||||
}
|
||||
|
||||
public boolean isInvSee() {
|
||||
return invSee;
|
||||
}
|
||||
|
||||
public void setInvSee(final boolean set) {
|
||||
invSee = set;
|
||||
}
|
||||
|
||||
public boolean isEnderSee() {
|
||||
return enderSee;
|
||||
}
|
||||
|
||||
public void setEnderSee(final boolean set) {
|
||||
enderSee = set;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableInvulnerabilityAfterTeleport() {
|
||||
final long time = ess.getSettings().getTeleportInvulnerability();
|
||||
if (time > 0) {
|
||||
teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetInvulnerabilityAfterTeleport() {
|
||||
if (teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp < System.currentTimeMillis()) {
|
||||
teleportInvulnerabilityTimestamp = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasInvulnerabilityAfterTeleport() {
|
||||
return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public boolean canInteractVanished() {
|
||||
return isAuthorized("essentials.vanish.interact");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIgnoreMsg() {
|
||||
return ignoreMsg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIgnoreMsg(boolean ignoreMsg) {
|
||||
this.ignoreMsg = ignoreMsg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanished() {
|
||||
return vanished;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVanished(final boolean set) {
|
||||
vanished = set;
|
||||
if (set) {
|
||||
for (User user : ess.getOnlineUsers()) {
|
||||
if (!user.isAuthorized("essentials.vanish.see")) {
|
||||
user.getBase().hidePlayer(getBase());
|
||||
}
|
||||
}
|
||||
setHidden(true);
|
||||
ess.getVanishedPlayersNew().add(getName());
|
||||
if (isAuthorized("essentials.vanish.effect")) {
|
||||
this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false));
|
||||
}
|
||||
} else {
|
||||
for (Player p : ess.getOnlinePlayers()) {
|
||||
p.showPlayer(getBase());
|
||||
}
|
||||
setHidden(false);
|
||||
ess.getVanishedPlayersNew().remove(getName());
|
||||
if (isAuthorized("essentials.vanish.effect")) {
|
||||
this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean checkSignThrottle() {
|
||||
if (isSignThrottled()) {
|
||||
return true;
|
||||
}
|
||||
updateThrottle();
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isSignThrottled() {
|
||||
final long minTime = lastThrottledAction + (1000 / ess.getSettings().getSignUsePerSecond());
|
||||
return (System.currentTimeMillis() < minTime);
|
||||
}
|
||||
|
||||
public void updateThrottle() {
|
||||
lastThrottledAction = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public boolean isFlyClickJump() {
|
||||
return rightClickJump;
|
||||
}
|
||||
|
||||
public void setRightClickJump(boolean rightClickJump) {
|
||||
this.rightClickJump = rightClickJump;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIgnoreExempt() {
|
||||
return this.isAuthorized("essentials.chat.ignoreexempt");
|
||||
}
|
||||
|
||||
public boolean isRecipeSee() {
|
||||
return recipeSee;
|
||||
}
|
||||
|
||||
public void setRecipeSee(boolean recipeSee) {
|
||||
this.recipeSee = recipeSee;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(String message) {
|
||||
if (!message.isEmpty()) {
|
||||
base.sendMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(final User other) {
|
||||
return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object object) {
|
||||
if (!(object instanceof User)) {
|
||||
return false;
|
||||
}
|
||||
return this.getName().equalsIgnoreCase(((User) object).getName());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.getName().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandSource getSource() {
|
||||
return new CommandSource(getBase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return this.getBase().getName();
|
||||
}
|
||||
|
||||
@Override public boolean isReachable() {
|
||||
return getBase().isOnline();
|
||||
}
|
||||
|
||||
@Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) {
|
||||
return this.messageRecipient.sendMessage(recipient, message);
|
||||
}
|
||||
|
||||
@Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) {
|
||||
return this.messageRecipient.onReceiveMessage(sender, message);
|
||||
}
|
||||
|
||||
@Override public IMessageRecipient getReplyRecipient() {
|
||||
return this.messageRecipient.getReplyRecipient();
|
||||
}
|
||||
|
||||
@Override public void setReplyRecipient(IMessageRecipient recipient) {
|
||||
this.messageRecipient.setReplyRecipient(recipient);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAfkMessage() {
|
||||
return this.afkMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAfkMessage(String message) {
|
||||
if (isAfk()) {
|
||||
this.afkMessage = message;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getAfkSince() {
|
||||
return afkSince;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<User, BigDecimal> getConfirmingPayments() {
|
||||
return confirmingPayments;
|
||||
}
|
||||
|
||||
public String getConfirmingClearCommand() {
|
||||
return confirmingClearCommand;
|
||||
}
|
||||
|
||||
public void setConfirmingClearCommand(String command) {
|
||||
this.confirmingClearCommand = command;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_9_R01)) {
|
||||
return getBase().getInventory().getItemInHand();
|
||||
} else {
|
||||
PlayerInventory inventory = getBase().getInventory();
|
||||
return inventory.getItemInMainHand() != null ? inventory.getItemInMainHand() : inventory.getItemInOffHand();
|
||||
}
|
||||
}
|
||||
|
||||
public void notifyOfMail() {
|
||||
List<String> mails = getMails();
|
||||
if (mails != null && !mails.isEmpty()) {
|
||||
int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000;
|
||||
if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) {
|
||||
sendMessage(tl("youHaveNewMail", mails.size()));
|
||||
lastNotifiedAboutMailsMs = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,318 +0,0 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import com.earth2me.essentials.utils.StringUtil;
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.util.concurrent.UncheckedExecutionException;
|
||||
import net.ess3.api.IEssentials;
|
||||
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.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 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 transient Cache<String, User> users;
|
||||
private static boolean legacy = false;
|
||||
|
||||
public UserMap(final IEssentials ess) {
|
||||
super();
|
||||
this.ess = ess;
|
||||
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();
|
||||
try {
|
||||
cacheBuilder.maximumSize(maxCount);
|
||||
} catch (NoSuchMethodError nsme) {
|
||||
legacy = true;
|
||||
legacyMaximumSize(cacheBuilder, maxCount);
|
||||
}
|
||||
cacheBuilder.softValues();
|
||||
if (!legacy) {
|
||||
users = cacheBuilder.build(this);
|
||||
} else {
|
||||
users = legacyBuild(cacheBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean userExists(final UUID uuid) {
|
||||
return keys.contains(uuid);
|
||||
}
|
||||
|
||||
public User getUser(final String name) {
|
||||
try {
|
||||
final String sanitizedName = StringUtil.safeString(name);
|
||||
if (names.containsKey(sanitizedName)) {
|
||||
final UUID uuid = names.get(sanitizedName);
|
||||
return getUser(uuid);
|
||||
}
|
||||
|
||||
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);
|
||||
trackUUID(user.getBase().getUniqueId(), user.getName(), true);
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
} catch (UncheckedExecutionException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public User getUser(final UUID uuid) {
|
||||
try {
|
||||
if (!legacy) {
|
||||
return ((LoadingCache<String, User>) users).get(uuid.toString());
|
||||
} else {
|
||||
return legacyCacheGet(uuid);
|
||||
}
|
||||
} catch (ExecutionException ex) {
|
||||
return null;
|
||||
} catch (UncheckedExecutionException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void trackUUID(final UUID uuid, final String name, boolean replace) {
|
||||
if (uuid != null) {
|
||||
keys.add(uuid);
|
||||
if (name != null && name.length() > 0) {
|
||||
final String keyName = ess.getSettings().isSafeUsermap() ? StringUtil.safeString(name) : name;
|
||||
if (!names.containsKey(keyName)) {
|
||||
names.put(keyName, uuid);
|
||||
uuidMap.writeUUIDMap();
|
||||
} else if (!names.get(keyName).equals(uuid)) {
|
||||
if (replace) {
|
||||
ess.getLogger().info("Found new UUID for " + name + ". Replacing " + names.get(keyName).toString() + " with " + uuid.toString());
|
||||
names.put(keyName, uuid);
|
||||
uuidMap.writeUUIDMap();
|
||||
} else {
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().info("Found old UUID for " + name + " (" + uuid.toString() + "). Not adding to usermap.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public User load(final String stringUUID) throws Exception {
|
||||
UUID uuid = UUID.fromString(stringUUID);
|
||||
Player player = ess.getServer().getPlayer(uuid);
|
||||
if (player != null) {
|
||||
final User user = new User(player, ess);
|
||||
trackUUID(uuid, user.getName(), true);
|
||||
return user;
|
||||
}
|
||||
|
||||
final File userFile = getUserFileFromID(uuid);
|
||||
|
||||
if (userFile.exists()) {
|
||||
player = new OfflinePlayer(uuid, ess.getServer());
|
||||
final User user = new User(player, ess);
|
||||
((OfflinePlayer) player).setName(user.getLastAccountName());
|
||||
trackUUID(uuid, user.getName(), false);
|
||||
return user;
|
||||
}
|
||||
|
||||
throw new Exception("User not found!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
getUUIDMap().forceWriteUUIDMap();
|
||||
loadAllUsersAsync(ess);
|
||||
}
|
||||
|
||||
public void invalidateAll() {
|
||||
users.invalidateAll();
|
||||
}
|
||||
|
||||
public void removeUser(final String name) {
|
||||
if (names == null) {
|
||||
ess.getLogger().warning("Name collection is null, cannot remove user.");
|
||||
return;
|
||||
}
|
||||
UUID uuid = names.get(name);
|
||||
if (uuid != null) {
|
||||
keys.remove(uuid);
|
||||
users.invalidate(uuid.toString());
|
||||
}
|
||||
names.remove(name);
|
||||
names.remove(StringUtil.safeString(name));
|
||||
}
|
||||
|
||||
public Set<UUID> getAllUniqueUsers() {
|
||||
return Collections.unmodifiableSet(keys);
|
||||
}
|
||||
|
||||
public int getUniqueUsers() {
|
||||
return keys.size();
|
||||
}
|
||||
|
||||
protected ConcurrentSkipListMap<String, UUID> getNames() {
|
||||
return names;
|
||||
}
|
||||
|
||||
protected ConcurrentSkipListMap<UUID, ArrayList<String>> getHistory() {
|
||||
return history;
|
||||
}
|
||||
|
||||
public List<String> getUserHistory(final UUID uuid) {
|
||||
return history.get(uuid);
|
||||
}
|
||||
|
||||
public UUIDMap getUUIDMap() {
|
||||
return uuidMap;
|
||||
}
|
||||
|
||||
private File getUserFileFromID(final UUID uuid) {
|
||||
final File userFolder = new File(ess.getDataFolder(), "userdata");
|
||||
return new File(userFolder, uuid.toString() + ".yml");
|
||||
}
|
||||
|
||||
public File getUserFileFromString(final String name) {
|
||||
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) {
|
||||
name = StringUtil.safeString(name);
|
||||
if (ess.getSettings().isDebug()) {
|
||||
ess.getLogger().warning("Using potentially blocking Bukkit UUID lookup for: " + name);
|
||||
}
|
||||
// Don't attempt to look up entirely invalid usernames
|
||||
if (name == null || !validUserPattern.matcher(name).matches()) {
|
||||
return null;
|
||||
}
|
||||
org.bukkit.OfflinePlayer offlinePlayer = ess.getServer().getOfflinePlayer(name);
|
||||
if (offlinePlayer == null) {
|
||||
return null;
|
||||
}
|
||||
UUID uuid;
|
||||
try {
|
||||
uuid = offlinePlayer.getUniqueId();
|
||||
} catch (UnsupportedOperationException | NullPointerException e) {
|
||||
return null;
|
||||
}
|
||||
// This is how Bukkit generates fake UUIDs
|
||||
if (UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)).equals(uuid)) {
|
||||
return null;
|
||||
} else {
|
||||
names.put(name, uuid);
|
||||
return getUser(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
private static Method getLegacy;
|
||||
|
||||
private User legacyCacheGet(UUID uuid) {
|
||||
if (getLegacy == null) {
|
||||
Class<?> usersClass = users.getClass();
|
||||
for (Method m : usersClass.getDeclaredMethods()) {
|
||||
if (m.getName().equals("get")) {
|
||||
getLegacy = m;
|
||||
getLegacy.setAccessible(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
return (User) getLegacy.invoke(users, uuid.toString());
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void legacyMaximumSize(CacheBuilder builder, int maxCount) {
|
||||
try {
|
||||
Method maxSizeLegacy = builder.getClass().getDeclaredMethod("maximumSize", Integer.TYPE);
|
||||
maxSizeLegacy.setAccessible(true);
|
||||
maxSizeLegacy.invoke(builder, maxCount);
|
||||
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Cache<String, User> legacyBuild(CacheBuilder builder) {
|
||||
Method build = null;
|
||||
for (Method method : builder.getClass().getDeclaredMethods()) {
|
||||
if (method.getName().equals("build")) {
|
||||
build = method;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Cache<String, User> legacyUsers;
|
||||
try {
|
||||
assert build != null;
|
||||
build.setAccessible(true);
|
||||
legacyUsers = (Cache<String, User>) build.invoke(builder, this);
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
legacyUsers = null;
|
||||
}
|
||||
return legacyUsers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.ISettings;
|
||||
import com.earth2me.essentials.api.InvalidNameException;
|
||||
import com.earth2me.essentials.external.gnu.inet.encoding.Punycode;
|
||||
import com.earth2me.essentials.external.gnu.inet.encoding.PunycodeException;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.Cleanup;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.bukkit.permissions.PermissionDefault;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
|
||||
|
||||
public final class Util
|
||||
{
|
||||
private Util()
|
||||
{
|
||||
}
|
||||
private final static Pattern INVALIDFILECHARS = Pattern.compile("[^\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");
|
||||
private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");
|
||||
|
||||
public static String sanitizeFileName(String name) throws InvalidNameException
|
||||
{
|
||||
try
|
||||
{
|
||||
String r = name.toLowerCase(Locale.ENGLISH);
|
||||
r = r.replace('.', (char)('\ue200' + '.'));
|
||||
r = r.replace('\\', (char)('\ue200' + '\\'));
|
||||
r = r.replace('/', (char)('\ue200' + '/'));
|
||||
r = r.replace('"', (char)('\ue200' + '"'));
|
||||
r = r.replace('<', (char)('\ue200' + '<'));
|
||||
r = r.replace('>', (char)('\ue200' + '>'));
|
||||
r = r.replace('|', (char)('\ue200' + '|'));
|
||||
r = r.replace('?', (char)('\ue200' + '?'));
|
||||
r = r.replace('*', (char)('\ue200' + '*'));
|
||||
r = r.replace(':', (char)('\ue200' + ':'));
|
||||
r = r.replace('-', (char)('\ue200' + '-'));
|
||||
r = INVALIDFILECHARS.matcher(r).replaceAll("");
|
||||
return Punycode.encode(r);
|
||||
}
|
||||
catch (PunycodeException ex)
|
||||
{
|
||||
throw new InvalidNameException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static String decodeFileName(String name) throws InvalidNameException
|
||||
{
|
||||
try
|
||||
{
|
||||
String r = Punycode.decode(name);
|
||||
r = r.replace((char)('\ue200' + '.'), '.');
|
||||
r = r.replace((char)('\ue200' + '\\'), '\\');
|
||||
r = r.replace((char)('\ue200' + '/'), '/');
|
||||
r = r.replace((char)('\ue200' + '"'), '"');
|
||||
r = r.replace((char)('\ue200' + '<'), '<');
|
||||
r = r.replace((char)('\ue200' + '>'), '>');
|
||||
r = r.replace((char)('\ue200' + '|'), '|');
|
||||
r = r.replace((char)('\ue200' + '?'), '?');
|
||||
r = r.replace((char)('\ue200' + '*'), '*');
|
||||
r = r.replace((char)('\ue200' + ':'), ':');
|
||||
r = r.replace((char)('\ue200' + '-'), '-');
|
||||
return r;
|
||||
}
|
||||
catch (PunycodeException ex)
|
||||
{
|
||||
throw new InvalidNameException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static String sanitizeKey(String name)
|
||||
{
|
||||
return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_");
|
||||
}
|
||||
|
||||
public static String sanitizeString(final String string)
|
||||
{
|
||||
return INVALIDCHARS.matcher(string).replaceAll("");
|
||||
}
|
||||
|
||||
public static String formatDateDiff(long date)
|
||||
{
|
||||
Calendar c = new GregorianCalendar();
|
||||
c.setTimeInMillis(date);
|
||||
Calendar now = new GregorianCalendar();
|
||||
return Util.formatDateDiff(now, c);
|
||||
}
|
||||
|
||||
public static String formatDateDiff(Calendar fromDate, Calendar toDate)
|
||||
{
|
||||
boolean future = false;
|
||||
if (toDate.equals(fromDate))
|
||||
{
|
||||
return _("now");
|
||||
}
|
||||
if (toDate.after(fromDate))
|
||||
{
|
||||
future = true;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int[] types = new int[]
|
||||
{
|
||||
Calendar.YEAR,
|
||||
Calendar.MONTH,
|
||||
Calendar.DAY_OF_MONTH,
|
||||
Calendar.HOUR_OF_DAY,
|
||||
Calendar.MINUTE,
|
||||
Calendar.SECOND
|
||||
};
|
||||
String[] names = new String[]
|
||||
{
|
||||
_("year"),
|
||||
_("years"),
|
||||
_("month"),
|
||||
_("months"),
|
||||
_("day"),
|
||||
_("days"),
|
||||
_("hour"),
|
||||
_("hours"),
|
||||
_("minute"),
|
||||
_("minutes"),
|
||||
_("second"),
|
||||
_("seconds")
|
||||
};
|
||||
for (int i = 0; i < types.length; i++)
|
||||
{
|
||||
int diff = dateDiff(types[i], fromDate, toDate, future);
|
||||
if (diff > 0)
|
||||
{
|
||||
sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
|
||||
}
|
||||
}
|
||||
if (sb.length() == 0)
|
||||
{
|
||||
return "now";
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
|
||||
{
|
||||
int diff = 0;
|
||||
long savedDate = fromDate.getTimeInMillis();
|
||||
while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate)))
|
||||
{
|
||||
savedDate = fromDate.getTimeInMillis();
|
||||
fromDate.add(type, future ? 1 : -1);
|
||||
diff++;
|
||||
}
|
||||
diff--;
|
||||
fromDate.setTimeInMillis(savedDate);
|
||||
return diff;
|
||||
}
|
||||
|
||||
public static long parseDateDiff(String time, boolean future) throws Exception
|
||||
{
|
||||
Pattern timePattern = Pattern.compile(
|
||||
"(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
|
||||
+ "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
|
||||
Matcher m = timePattern.matcher(time);
|
||||
int years = 0;
|
||||
int months = 0;
|
||||
int weeks = 0;
|
||||
int days = 0;
|
||||
int hours = 0;
|
||||
int minutes = 0;
|
||||
int seconds = 0;
|
||||
boolean found = false;
|
||||
while (m.find())
|
||||
{
|
||||
if (m.group() == null || m.group().isEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (int i = 0; i < m.groupCount(); i++)
|
||||
{
|
||||
if (m.group(i) != null && !m.group(i).isEmpty())
|
||||
{
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found)
|
||||
{
|
||||
if (m.group(1) != null && !m.group(1).isEmpty())
|
||||
{
|
||||
years = Integer.parseInt(m.group(1));
|
||||
}
|
||||
if (m.group(2) != null && !m.group(2).isEmpty())
|
||||
{
|
||||
months = Integer.parseInt(m.group(2));
|
||||
}
|
||||
if (m.group(3) != null && !m.group(3).isEmpty())
|
||||
{
|
||||
weeks = Integer.parseInt(m.group(3));
|
||||
}
|
||||
if (m.group(4) != null && !m.group(4).isEmpty())
|
||||
{
|
||||
days = Integer.parseInt(m.group(4));
|
||||
}
|
||||
if (m.group(5) != null && !m.group(5).isEmpty())
|
||||
{
|
||||
hours = Integer.parseInt(m.group(5));
|
||||
}
|
||||
if (m.group(6) != null && !m.group(6).isEmpty())
|
||||
{
|
||||
minutes = Integer.parseInt(m.group(6));
|
||||
}
|
||||
if (m.group(7) != null && !m.group(7).isEmpty())
|
||||
{
|
||||
seconds = Integer.parseInt(m.group(7));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
{
|
||||
throw new Exception(_("illegalDate"));
|
||||
}
|
||||
Calendar c = new GregorianCalendar();
|
||||
if (years > 0)
|
||||
{
|
||||
c.add(Calendar.YEAR, years * (future ? 1 : -1));
|
||||
}
|
||||
if (months > 0)
|
||||
{
|
||||
c.add(Calendar.MONTH, months * (future ? 1 : -1));
|
||||
}
|
||||
if (weeks > 0)
|
||||
{
|
||||
c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1));
|
||||
}
|
||||
if (days > 0)
|
||||
{
|
||||
c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1));
|
||||
}
|
||||
if (hours > 0)
|
||||
{
|
||||
c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
|
||||
}
|
||||
if (minutes > 0)
|
||||
{
|
||||
c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
|
||||
}
|
||||
if (seconds > 0)
|
||||
{
|
||||
c.add(Calendar.SECOND, seconds * (future ? 1 : -1));
|
||||
}
|
||||
return c.getTimeInMillis();
|
||||
}
|
||||
// The player can stand inside these materials
|
||||
private static final Set<Integer> AIR_MATERIALS = new HashSet<Integer>();
|
||||
private static final HashSet<Byte> AIR_MATERIALS_TARGET = new HashSet<Byte>();
|
||||
|
||||
static
|
||||
{
|
||||
AIR_MATERIALS.add(Material.AIR.getId());
|
||||
AIR_MATERIALS.add(Material.SAPLING.getId());
|
||||
AIR_MATERIALS.add(Material.POWERED_RAIL.getId());
|
||||
AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId());
|
||||
AIR_MATERIALS.add(Material.LONG_GRASS.getId());
|
||||
AIR_MATERIALS.add(Material.DEAD_BUSH.getId());
|
||||
AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId());
|
||||
AIR_MATERIALS.add(Material.RED_ROSE.getId());
|
||||
AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId());
|
||||
AIR_MATERIALS.add(Material.RED_MUSHROOM.getId());
|
||||
AIR_MATERIALS.add(Material.TORCH.getId());
|
||||
AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId());
|
||||
AIR_MATERIALS.add(Material.SEEDS.getId());
|
||||
AIR_MATERIALS.add(Material.SIGN_POST.getId());
|
||||
AIR_MATERIALS.add(Material.WOODEN_DOOR.getId());
|
||||
AIR_MATERIALS.add(Material.LADDER.getId());
|
||||
AIR_MATERIALS.add(Material.RAILS.getId());
|
||||
AIR_MATERIALS.add(Material.WALL_SIGN.getId());
|
||||
AIR_MATERIALS.add(Material.LEVER.getId());
|
||||
AIR_MATERIALS.add(Material.STONE_PLATE.getId());
|
||||
AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId());
|
||||
AIR_MATERIALS.add(Material.WOOD_PLATE.getId());
|
||||
AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId());
|
||||
AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId());
|
||||
AIR_MATERIALS.add(Material.STONE_BUTTON.getId());
|
||||
AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId());
|
||||
AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId());
|
||||
AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId());
|
||||
AIR_MATERIALS.add(Material.TRAP_DOOR.getId());
|
||||
AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId());
|
||||
AIR_MATERIALS.add(Material.MELON_STEM.getId());
|
||||
AIR_MATERIALS.add(Material.VINE.getId());
|
||||
AIR_MATERIALS.add(Material.NETHER_WARTS.getId());
|
||||
AIR_MATERIALS.add(Material.WATER_LILY.getId());
|
||||
|
||||
for (Integer integer : AIR_MATERIALS)
|
||||
{
|
||||
AIR_MATERIALS_TARGET.add(integer.byteValue());
|
||||
}
|
||||
AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId());
|
||||
AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId());
|
||||
}
|
||||
|
||||
public static Location getTarget(final LivingEntity entity) throws Exception
|
||||
{
|
||||
final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300);
|
||||
if (block == null)
|
||||
{
|
||||
throw new Exception("Not targeting a block");
|
||||
}
|
||||
return block.getLocation();
|
||||
}
|
||||
|
||||
public static Location getSafeDestination(final Location loc) throws Exception
|
||||
{
|
||||
if (loc == null || loc.getWorld() == null)
|
||||
{
|
||||
throw new Exception(_("destinationNotSet"));
|
||||
}
|
||||
final World world = loc.getWorld();
|
||||
int x = loc.getBlockX();
|
||||
int y = (int)Math.round(loc.getY());
|
||||
int z = loc.getBlockZ();
|
||||
|
||||
while (isBlockAboveAir(world, x, y, z))
|
||||
{
|
||||
y -= 1;
|
||||
if (y < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
while (isBlockUnsafe(world, x, y, z))
|
||||
{
|
||||
y += 1;
|
||||
if (y >= 127)
|
||||
{
|
||||
x += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (isBlockUnsafe(world, x, y, z))
|
||||
{
|
||||
y -= 1;
|
||||
if (y <= 1)
|
||||
{
|
||||
y = 127;
|
||||
x += 1;
|
||||
if (x - 32 > loc.getBlockX())
|
||||
{
|
||||
throw new Exception(_("holeInFloor"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch());
|
||||
}
|
||||
|
||||
private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z)
|
||||
{
|
||||
return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId());
|
||||
}
|
||||
|
||||
public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z)
|
||||
{
|
||||
final Block below = world.getBlockAt(x, y - 1, z);
|
||||
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (below.getType() == Material.FIRE)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId()))
|
||||
|| (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId())))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return isBlockAboveAir(world, x, y, z);
|
||||
}
|
||||
|
||||
public static ItemStack convertBlockToItem(final Block block)
|
||||
{
|
||||
final ItemStack is = new ItemStack(block.getType(), 1, (short)0, block.getData());
|
||||
switch (is.getType())
|
||||
{
|
||||
case WOODEN_DOOR:
|
||||
is.setType(Material.WOOD_DOOR);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case IRON_DOOR_BLOCK:
|
||||
is.setType(Material.IRON_DOOR);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case SIGN_POST:
|
||||
case WALL_SIGN:
|
||||
is.setType(Material.SIGN);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case CROPS:
|
||||
is.setType(Material.SEEDS);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case CAKE_BLOCK:
|
||||
is.setType(Material.CAKE);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case BED_BLOCK:
|
||||
is.setType(Material.BED);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case REDSTONE_WIRE:
|
||||
is.setType(Material.REDSTONE);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case REDSTONE_TORCH_OFF:
|
||||
case REDSTONE_TORCH_ON:
|
||||
is.setType(Material.REDSTONE_TORCH_ON);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case DIODE_BLOCK_OFF:
|
||||
case DIODE_BLOCK_ON:
|
||||
is.setType(Material.DIODE);
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case DOUBLE_STEP:
|
||||
is.setType(Material.STEP);
|
||||
break;
|
||||
case TORCH:
|
||||
case RAILS:
|
||||
case LADDER:
|
||||
case WOOD_STAIRS:
|
||||
case COBBLESTONE_STAIRS:
|
||||
case LEVER:
|
||||
case STONE_BUTTON:
|
||||
case FURNACE:
|
||||
case DISPENSER:
|
||||
case PUMPKIN:
|
||||
case JACK_O_LANTERN:
|
||||
case WOOD_PLATE:
|
||||
case STONE_PLATE:
|
||||
case PISTON_STICKY_BASE:
|
||||
case PISTON_BASE:
|
||||
case IRON_FENCE:
|
||||
case THIN_GLASS:
|
||||
case TRAP_DOOR:
|
||||
case FENCE:
|
||||
case FENCE_GATE:
|
||||
case NETHER_FENCE:
|
||||
is.setDurability((short)0);
|
||||
break;
|
||||
case FIRE:
|
||||
return null;
|
||||
case PUMPKIN_STEM:
|
||||
is.setType(Material.PUMPKIN_SEEDS);
|
||||
break;
|
||||
case MELON_STEM:
|
||||
is.setType(Material.MELON_SEEDS);
|
||||
break;
|
||||
}
|
||||
return is;
|
||||
}
|
||||
private static DecimalFormat df = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US));
|
||||
|
||||
public static String formatCurrency(final double value, final IEssentials ess)
|
||||
{
|
||||
@Cleanup
|
||||
final ISettings settings = ess.getSettings();
|
||||
settings.acquireReadLock();
|
||||
String str = settings.getData().getEconomy().getCurrencySymbol() + df.format(value);
|
||||
if (str.endsWith(".00"))
|
||||
{
|
||||
str = str.substring(0, str.length() - 3);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public static double roundDouble(final double d)
|
||||
{
|
||||
return Math.round(d * 100.0) / 100.0;
|
||||
}
|
||||
|
||||
public static boolean isInt(final String sInt)
|
||||
{
|
||||
try
|
||||
{
|
||||
Integer.parseInt(sInt);
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String joinList(Object... list)
|
||||
{
|
||||
return joinList(", ", list);
|
||||
}
|
||||
|
||||
public static String joinList(String seperator, Object... list)
|
||||
{
|
||||
StringBuilder buf = new StringBuilder();
|
||||
for (Object each : list)
|
||||
{
|
||||
if (buf.length() > 0)
|
||||
{
|
||||
buf.append(seperator);
|
||||
}
|
||||
|
||||
if (each instanceof Collection)
|
||||
{
|
||||
buf.append(joinList(seperator, ((Collection)each).toArray()));
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
buf.append(each.toString());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
buf.append(each.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static void registerPermissions(String path, Collection<String> nodes, boolean hasDefault, IEssentials ess)
|
||||
{
|
||||
if (nodes == null || nodes.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
final PluginManager pluginManager = ess.getServer().getPluginManager();
|
||||
Permission basePerm = pluginManager.getPermission(path + ".*");
|
||||
if (basePerm != null && !basePerm.getChildren().isEmpty())
|
||||
{
|
||||
basePerm.getChildren().clear();
|
||||
}
|
||||
if (basePerm == null)
|
||||
{
|
||||
basePerm = new Permission(path + ".*", PermissionDefault.OP);
|
||||
pluginManager.addPermission(basePerm);
|
||||
Permission mainPerm = pluginManager.getPermission("essentials.*");
|
||||
if (mainPerm == null)
|
||||
{
|
||||
mainPerm = new Permission("essentials.*", PermissionDefault.OP);
|
||||
pluginManager.addPermission(mainPerm);
|
||||
}
|
||||
mainPerm.getChildren().put(basePerm.getName(), Boolean.TRUE);
|
||||
}
|
||||
|
||||
for (String nodeName : nodes)
|
||||
{
|
||||
final String permissionName = path + "." + nodeName;
|
||||
Permission perm = pluginManager.getPermission(permissionName);
|
||||
if (perm == null)
|
||||
{
|
||||
final PermissionDefault defaultPerm = hasDefault && nodeName.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.OP;
|
||||
perm = new Permission(permissionName, defaultPerm);
|
||||
pluginManager.addPermission(perm);
|
||||
}
|
||||
basePerm.getChildren().put(permissionName, Boolean.TRUE);
|
||||
}
|
||||
basePerm.recalculatePermissibles();
|
||||
}
|
||||
private static transient final Pattern DOT_PATTERN = Pattern.compile("\\.");
|
||||
|
||||
public static Permission registerPermission(String permission, PermissionDefault defaultPerm)
|
||||
{
|
||||
final PluginManager pluginManager = Bukkit.getServer().getPluginManager();
|
||||
final String[] parts = DOT_PATTERN.split(permission);
|
||||
final StringBuilder builder = new StringBuilder(permission.length());
|
||||
Permission parent = null;
|
||||
for (int i = 0; i < parts.length - 1; i++)
|
||||
{
|
||||
builder.append(parts[i]).append(".*");
|
||||
String permString = builder.toString();
|
||||
Permission perm = pluginManager.getPermission(permString);
|
||||
if (perm == null)
|
||||
{
|
||||
perm = new Permission(permString, PermissionDefault.FALSE);
|
||||
pluginManager.addPermission(perm);
|
||||
if (parent != null)
|
||||
{
|
||||
parent.getChildren().put(perm.getName(), Boolean.TRUE);
|
||||
}
|
||||
parent = perm;
|
||||
}
|
||||
builder.deleteCharAt(builder.length() - 1);
|
||||
}
|
||||
Permission perm = pluginManager.getPermission(permission);
|
||||
if (perm == null)
|
||||
{
|
||||
perm = new Permission(permission, defaultPerm);
|
||||
pluginManager.addPermission(perm);
|
||||
if (parent != null)
|
||||
{
|
||||
parent.getChildren().put(perm.getName(), Boolean.TRUE);
|
||||
}
|
||||
parent = perm;
|
||||
}
|
||||
perm.recalculatePermissibles();
|
||||
return perm;
|
||||
}
|
||||
private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-FKa-fk]");
|
||||
private static transient final Pattern EASY_COLOR_PATTERN = Pattern.compile("&([0-9a-fk])");
|
||||
|
||||
public static String stripColor(final String input)
|
||||
{
|
||||
if (input == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return VANILLA_COLOR_PATTERN.matcher(input).replaceAll("");
|
||||
}
|
||||
|
||||
public static String replaceColor(final String input)
|
||||
{
|
||||
if (input == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return EASY_COLOR_PATTERN.matcher(input).replaceAll("\u00a7$1");
|
||||
}
|
||||
}
|
||||
@@ -1,167 +1,152 @@
|
||||
package com.earth2me.essentials;
|
||||
|
||||
import static com.earth2me.essentials.I18n._;
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.IWarp;
|
||||
import com.earth2me.essentials.api.IWarps;
|
||||
import com.earth2me.essentials.api.InvalidNameException;
|
||||
import com.earth2me.essentials.commands.WarpNotFoundException;
|
||||
import com.earth2me.essentials.utils.StringUtil;
|
||||
import net.ess3.api.InvalidNameException;
|
||||
import net.ess3.api.InvalidWorldException;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Server;
|
||||
import com.earth2me.essentials.settings.WarpHolder;
|
||||
import com.earth2me.essentials.storage.StorageObjectMap;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
|
||||
|
||||
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 File warpsFolder;
|
||||
private final Server server;
|
||||
public class Warps extends StorageObjectMap<IWarp> implements IWarps
|
||||
{
|
||||
private static final Logger logger = Bukkit.getLogger();
|
||||
|
||||
public Warps(Server server, File dataFolder) {
|
||||
this.server = server;
|
||||
warpsFolder = new File(dataFolder, "warps");
|
||||
if (!warpsFolder.exists()) {
|
||||
warpsFolder.mkdirs();
|
||||
}
|
||||
reloadConfig();
|
||||
}
|
||||
public Warps(IEssentials ess)
|
||||
{
|
||||
super(ess, "warps");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return warpPoints.isEmpty();
|
||||
}
|
||||
@Override
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return getKeySize() == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getList() {
|
||||
final List<String> keys = new ArrayList<String>();
|
||||
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) {
|
||||
keys.add(stringIgnoreCase.getString());
|
||||
}
|
||||
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
|
||||
return keys;
|
||||
}
|
||||
@Override
|
||||
public Collection<String> getList()
|
||||
{
|
||||
final List<String> names = new ArrayList<String>();
|
||||
for (String key : getAllKeys())
|
||||
{
|
||||
IWarp warp = getObject(key);
|
||||
if (warp == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
warp.acquireReadLock();
|
||||
try
|
||||
{
|
||||
names.add(warp.getData().getName());
|
||||
}
|
||||
finally
|
||||
{
|
||||
warp.unlock();
|
||||
}
|
||||
}
|
||||
Collections.sort(names, String.CASE_INSENSITIVE_ORDER);
|
||||
return names;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException {
|
||||
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
|
||||
if (conf == null) {
|
||||
throw new WarpNotFoundException();
|
||||
}
|
||||
return conf.getLocation(null, server);
|
||||
}
|
||||
@Override
|
||||
public Location getWarp(final String name) throws Exception
|
||||
{
|
||||
IWarp warp = getObject(name);
|
||||
if (warp == null)
|
||||
{
|
||||
throw new WarpNotFoundException(_("warpNotExist"));
|
||||
}
|
||||
warp.acquireReadLock();
|
||||
try
|
||||
{
|
||||
return warp.getData().getLocation().getBukkitLocation();
|
||||
}
|
||||
finally
|
||||
{
|
||||
warp.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWarp(String name, Location loc) throws Exception {
|
||||
setWarp(null, name, loc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWarp(IUser user, String name, Location loc) throws Exception {
|
||||
String filename = StringUtil.sanitizeFileName(name);
|
||||
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
|
||||
if (conf == null) {
|
||||
File confFile = new File(warpsFolder, filename + ".yml");
|
||||
if (confFile.exists()) {
|
||||
throw new Exception(tl("similarWarpExist"));
|
||||
}
|
||||
conf = new EssentialsConf(confFile);
|
||||
warpPoints.put(new StringIgnoreCase(name), conf);
|
||||
}
|
||||
conf.setProperty(null, loc);
|
||||
conf.setProperty("name", name);
|
||||
if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString());
|
||||
try {
|
||||
conf.saveWithError();
|
||||
} catch (IOException ex) {
|
||||
throw new IOException(tl("invalidWarpName"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getLastOwner(String warp) throws WarpNotFoundException {
|
||||
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
|
||||
if (conf == null) {
|
||||
throw new WarpNotFoundException();
|
||||
}
|
||||
UUID uuid = null;
|
||||
try {
|
||||
uuid = UUID.fromString(conf.getString("lastowner"));
|
||||
}
|
||||
catch (Exception ex) {}
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeWarp(String name) throws Exception {
|
||||
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
|
||||
if (conf == null) {
|
||||
throw new Exception(tl("warpNotExist"));
|
||||
}
|
||||
if (!conf.getFile().delete()) {
|
||||
throw new Exception(tl("warpDeleteError"));
|
||||
}
|
||||
warpPoints.remove(new StringIgnoreCase(name));
|
||||
}
|
||||
@Override
|
||||
public void setWarp(final String name, final Location loc) throws Exception
|
||||
{
|
||||
setWarp(name, new com.earth2me.essentials.storage.Location(loc));
|
||||
}
|
||||
|
||||
public void setWarp(final String name, final com.earth2me.essentials.storage.Location loc) throws Exception
|
||||
{
|
||||
IWarp warp = getObject(name);
|
||||
if (warp == null)
|
||||
{
|
||||
warp = new WarpHolder(name, ess);
|
||||
}
|
||||
warp.acquireWriteLock();
|
||||
try
|
||||
{
|
||||
warp.getData().setLocation(loc);
|
||||
}
|
||||
finally
|
||||
{
|
||||
warp.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void reloadConfig() {
|
||||
warpPoints.clear();
|
||||
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")) {
|
||||
try {
|
||||
EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
|
||||
conf.load();
|
||||
String name = conf.getString("name");
|
||||
if (name != null) {
|
||||
warpPoints.put(new StringIgnoreCase(name), conf);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.log(Level.WARNING, tl("loadWarpError", filename), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void removeWarp(final String name) throws Exception
|
||||
{
|
||||
removeObject(name);
|
||||
}
|
||||
|
||||
//This is here for future 3.x api support. Not implemented here becasue storage is handled differently
|
||||
@Override
|
||||
public File getWarpFile(String name) throws InvalidNameException {
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
}
|
||||
@Override
|
||||
public File getWarpFile(String name) throws InvalidNameException
|
||||
{
|
||||
return getStorageFile(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return getList().size();
|
||||
}
|
||||
@Override
|
||||
public IWarp load(String name) throws Exception
|
||||
{
|
||||
final IWarp warp = new WarpHolder(name, ess);
|
||||
warp.onReload();
|
||||
return warp;
|
||||
}
|
||||
|
||||
private static class StringIgnoreCase {
|
||||
private final String string;
|
||||
|
||||
public StringIgnoreCase(String string) {
|
||||
this.string = string;
|
||||
}
|
||||
private static class StringIgnoreCase
|
||||
{
|
||||
private final String string;
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getString().toLowerCase(Locale.ENGLISH).hashCode();
|
||||
}
|
||||
public StringIgnoreCase(String string)
|
||||
{
|
||||
this.string = string;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof StringIgnoreCase) {
|
||||
return getString().equalsIgnoreCase(((StringIgnoreCase) o).getString());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
return getString().toLowerCase(Locale.ENGLISH).hashCode();
|
||||
}
|
||||
|
||||
public String getString() {
|
||||
return string;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o)
|
||||
{
|
||||
if (o instanceof StringIgnoreCase)
|
||||
{
|
||||
return getString().equalsIgnoreCase(((StringIgnoreCase)o).getString());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getString()
|
||||
{
|
||||
return string;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,156 +1,86 @@
|
||||
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;
|
||||
|
||||
import com.earth2me.essentials.api.IEssentials;
|
||||
import com.earth2me.essentials.api.IWorth;
|
||||
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
|
||||
import com.earth2me.essentials.storage.EnchantmentLevel;
|
||||
import java.io.File;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Locale;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.material.MaterialData;
|
||||
|
||||
|
||||
public class Worth implements IConf {
|
||||
private final EssentialsConf config;
|
||||
public class Worth extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Worth> implements IWorth
|
||||
{
|
||||
public Worth(final IEssentials ess)
|
||||
{
|
||||
super(ess, com.earth2me.essentials.settings.Worth.class);
|
||||
onReload(false);
|
||||
}
|
||||
|
||||
public Worth(File dataFolder) {
|
||||
config = new EssentialsConf(new File(dataFolder, "worth.yml"));
|
||||
config.setTemplateName("/worth.yml");
|
||||
config.load();
|
||||
}
|
||||
@Override
|
||||
public double getPrice(final ItemStack itemStack)
|
||||
{
|
||||
this.acquireReadLock();
|
||||
try
|
||||
{
|
||||
final Map<MaterialData, Double> prices = this.getData().getSell();
|
||||
if (prices == null || itemStack == null)
|
||||
{
|
||||
return Double.NaN;
|
||||
}
|
||||
final Double basePrice = prices.get(itemStack.getData());
|
||||
if (basePrice == null || Double.isNaN(basePrice))
|
||||
{
|
||||
return Double.NaN;
|
||||
}
|
||||
double multiplier = 1.0;
|
||||
if (itemStack.getType().getMaxDurability() > 0) {
|
||||
multiplier *= (double)itemStack.getDurability() / (double)itemStack.getType().getMaxDurability();
|
||||
}
|
||||
if (itemStack.getEnchantments() != null && !itemStack.getEnchantments().isEmpty())
|
||||
{
|
||||
final Map<EnchantmentLevel, Double> enchantmentMultipliers = this.getData().getEnchantmentMultiplier();
|
||||
if (enchantmentMultipliers != null)
|
||||
{
|
||||
for (Map.Entry<Enchantment, Integer> entry : itemStack.getEnchantments().entrySet())
|
||||
{
|
||||
final Double enchMult = enchantmentMultipliers.get(new EnchantmentLevel(entry.getKey(), entry.getValue()));
|
||||
if (enchMult != null)
|
||||
{
|
||||
multiplier *= enchMult;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return basePrice * multiplier;
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(IEssentials ess, ItemStack itemStack) {
|
||||
BigDecimal result;
|
||||
@Override
|
||||
public void setPrice(final ItemStack itemStack, final double price)
|
||||
{
|
||||
acquireWriteLock();
|
||||
try {
|
||||
if (getData().getSell() == null) {
|
||||
getData().setSell(new HashMap<MaterialData, Double>());
|
||||
}
|
||||
getData().getSell().put(itemStack.getData(), price);
|
||||
} finally {
|
||||
unlock();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
if (result.signum() < 0) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception {
|
||||
if (is == null || is.getType() == Material.AIR) {
|
||||
throw new Exception(tl("itemSellAir"));
|
||||
}
|
||||
|
||||
int amount = 0;
|
||||
|
||||
if (args.length > 1) {
|
||||
try {
|
||||
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
|
||||
} catch (NumberFormatException ex) {
|
||||
throw new NotEnoughArgumentsException(ex);
|
||||
}
|
||||
if (args[1].startsWith("-")) {
|
||||
amount = -amount;
|
||||
}
|
||||
}
|
||||
|
||||
boolean stack = args.length > 1 && args[1].endsWith("s");
|
||||
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()) {
|
||||
if (s == null || !s.isSimilar(is)) {
|
||||
continue;
|
||||
}
|
||||
max += s.getAmount();
|
||||
}
|
||||
|
||||
if (stack) {
|
||||
amount *= is.getType().getMaxStackSize();
|
||||
}
|
||||
if (amount < 1) {
|
||||
amount += max;
|
||||
}
|
||||
|
||||
if (requireStack) {
|
||||
amount -= amount % is.getType().getMaxStackSize();
|
||||
}
|
||||
if (amount > max || amount < 1) {
|
||||
if (!isBulkSell) {
|
||||
user.sendMessage(tl("itemNotEnough2"));
|
||||
user.sendMessage(tl("itemNotEnough3"));
|
||||
throw new Exception(tl("itemNotEnough1"));
|
||||
} else {
|
||||
return amount;
|
||||
}
|
||||
}
|
||||
|
||||
return amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(IEssentials ess, ItemStack itemStack, 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.
|
||||
path = path + "." + itemStack.getDurability();
|
||||
}
|
||||
|
||||
config.setProperty(path, price);
|
||||
config.save();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
config.load();
|
||||
}
|
||||
@Override
|
||||
public File getStorageFile() throws IOException
|
||||
{
|
||||
return new File(ess.getDataFolder(), "worth.yml");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public class ChargeException extends Exception
|
||||
{
|
||||
public ChargeException(final String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ChargeException(final String message, final Throwable throwable)
|
||||
{
|
||||
super(message, throwable);
|
||||
}
|
||||
}
|
||||
@@ -1,427 +0,0 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.EssentialsUserConf;
|
||||
import com.earth2me.essentials.Trade;
|
||||
import com.earth2me.essentials.User;
|
||||
import com.earth2me.essentials.utils.NumberUtil;
|
||||
import com.earth2me.essentials.utils.StringUtil;
|
||||
import com.google.common.base.Charsets;
|
||||
import net.ess3.api.IEssentials;
|
||||
import net.ess3.api.MaxMoneyException;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.io.File;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.MathContext;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* @param aEss the ess to set
|
||||
*/
|
||||
public static void setEss(IEssentials aEss) {
|
||||
ess = aEss;
|
||||
}
|
||||
|
||||
private static void createNPCFile(String name) {
|
||||
File folder = new File(ess.getDataFolder(), "userdata");
|
||||
name = StringUtil.safeString(name);
|
||||
if (!folder.exists()) {
|
||||
folder.mkdirs();
|
||||
}
|
||||
UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8));
|
||||
EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml"));
|
||||
npcConfig.load();
|
||||
npcConfig.setProperty("npc", true);
|
||||
npcConfig.setProperty("lastAccountName", name);
|
||||
npcConfig.setProperty("money", ess.getSettings().getStartingBalance());
|
||||
npcConfig.forceSave();
|
||||
ess.getUserMap().trackUUID(npcUUID, name, false);
|
||||
}
|
||||
|
||||
private static void deleteNPC(String name) {
|
||||
User user = ess.getUser(name);
|
||||
user.reset();
|
||||
}
|
||||
|
||||
private static User getUserByName(String name) {
|
||||
if (ess == null) {
|
||||
throw new RuntimeException(noCallBeforeLoad);
|
||||
}
|
||||
if (name == null) {
|
||||
throw new RuntimeException("Economy username cannot be null");
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the balance of a user
|
||||
*
|
||||
* @param name Name of the user
|
||||
*
|
||||
* @return balance
|
||||
*
|
||||
* @throws UserDoesNotExistException
|
||||
*/
|
||||
@Deprecated
|
||||
public static double getMoney(String name) throws UserDoesNotExistException {
|
||||
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);
|
||||
if (user == null) {
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
return user.getMoney();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the balance of a user
|
||||
*
|
||||
* @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
|
||||
public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException {
|
||||
try {
|
||||
setMoney(name, BigDecimal.valueOf(balance));
|
||||
} catch (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);
|
||||
if (user == null) {
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) {
|
||||
throw new NoLoanPermittedException();
|
||||
}
|
||||
if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) {
|
||||
throw new NoLoanPermittedException();
|
||||
}
|
||||
try {
|
||||
user.setMoney(balance);
|
||||
} catch (MaxMoneyException ex) {
|
||||
//TODO: Update API to show max balance errors
|
||||
}
|
||||
Trade.log("API", "Set", "API", name, new Trade(balance, ess), null, null, null, ess);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
|
||||
*/
|
||||
@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(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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substracts money from the balance of a user
|
||||
*
|
||||
* @param name Name of the user
|
||||
* @param amount The money you want to substract
|
||||
*
|
||||
* @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 subtract(String name, 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);
|
||||
}
|
||||
}
|
||||
|
||||
public static void substract(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 exists
|
||||
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
|
||||
*/
|
||||
@Deprecated
|
||||
public static void divide(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
|
||||
try {
|
||||
divide(name, BigDecimal.valueOf(amount));
|
||||
} catch (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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies the balance of a user by a 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
|
||||
public static void multiply(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException {
|
||||
try {
|
||||
multiply(name, BigDecimal.valueOf(amount));
|
||||
} catch (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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException {
|
||||
if (ess == null) {
|
||||
throw new RuntimeException(noCallBeforeLoad);
|
||||
}
|
||||
setMoney(name, ess.getSettings().getStartingBalance());
|
||||
Trade.log("API", "Reset", "API", name, 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 or an equal amount of money
|
||||
*
|
||||
* @throws UserDoesNotExistException If a user by that name does not exists
|
||||
*/
|
||||
@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 boolean hasEnough(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 money
|
||||
*
|
||||
* @throws UserDoesNotExistException If a user by that name does not exists
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean hasMore(String name, double amount) throws UserDoesNotExistException {
|
||||
try {
|
||||
return hasMore(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 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 not have
|
||||
*
|
||||
* @return true, if the user has less money
|
||||
*
|
||||
* @throws UserDoesNotExistException If a user by that name does not exists
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean hasLess(String name, double amount) throws UserDoesNotExistException {
|
||||
try {
|
||||
return hasLess(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 boolean hasLess(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException {
|
||||
return amount.compareTo(getMoneyExact(name)) > 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
|
||||
*/
|
||||
public static boolean isNegative(String name) throws UserDoesNotExistException {
|
||||
return getMoneyExact(name).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
|
||||
public static String format(double amount) {
|
||||
try {
|
||||
return format(BigDecimal.valueOf(amount));
|
||||
} catch (NumberFormatException e) {
|
||||
logger.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e);
|
||||
return "NaN";
|
||||
}
|
||||
}
|
||||
|
||||
public static String format(BigDecimal amount) {
|
||||
if (ess == null) {
|
||||
throw new RuntimeException(noCallBeforeLoad);
|
||||
}
|
||||
return NumberUtil.displayCurrency(amount, ess);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a player exists to avoid the UserDoesNotExistException
|
||||
*
|
||||
* @param name Name of the user
|
||||
*
|
||||
* @return true, if the user exists
|
||||
*/
|
||||
public static boolean playerExists(String name) {
|
||||
return getUserByName(name) != 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);
|
||||
if (user == null) {
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
return user.isNPC();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
if (user == null) {
|
||||
createNPCFile(name);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
if (user == null) {
|
||||
throw new UserDoesNotExistException(name);
|
||||
}
|
||||
deleteNPC(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public interface IBackup extends Runnable
|
||||
{
|
||||
public void startTask();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import java.util.Map;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
|
||||
public interface ICommandHandler extends IReload
|
||||
{
|
||||
Map<String, String> disabledCommands();
|
||||
|
||||
public void removePlugin(Plugin plugin);
|
||||
|
||||
public void addPlugin(Plugin plugin);
|
||||
|
||||
boolean handleCommand(CommandSender sender, Command command, String commandLabel, String[] args);
|
||||
|
||||
void showCommandError(CommandSender sender, String commandLabel, Throwable exception);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public interface IEconomy extends IReload
|
||||
{
|
||||
public double getMoney(String name) throws UserDoesNotExistException;
|
||||
|
||||
public void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException;
|
||||
|
||||
public void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException;
|
||||
|
||||
public String format(double amount);
|
||||
|
||||
public boolean playerExists(String name);
|
||||
|
||||
public boolean isNPC(String name) throws UserDoesNotExistException;
|
||||
|
||||
public boolean createNPC(String name);
|
||||
|
||||
public void removeNPC(String name) throws UserDoesNotExistException;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.listener.TntExplodeListener;
|
||||
import com.earth2me.essentials.register.payment.Methods;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
|
||||
public interface IEssentials extends Plugin
|
||||
{
|
||||
void addReloadListener(IReload listener);
|
||||
|
||||
IUser getUser(Player player);
|
||||
|
||||
IUser getUser(String playerName);
|
||||
|
||||
int broadcastMessage(IUser sender, String message);
|
||||
|
||||
II18n getI18n();
|
||||
|
||||
ISettings getSettings();
|
||||
|
||||
IGroups getGroups();
|
||||
|
||||
IJails getJails();
|
||||
|
||||
IKits getKits();
|
||||
|
||||
IWarps getWarps();
|
||||
|
||||
IWorth getWorth();
|
||||
|
||||
IItemDb getItemDb();
|
||||
|
||||
IUserMap getUserMap();
|
||||
|
||||
IBackup getBackup();
|
||||
|
||||
ICommandHandler getCommandHandler();
|
||||
|
||||
World getWorld(String name);
|
||||
|
||||
Methods getPaymentMethod();
|
||||
|
||||
int scheduleAsyncDelayedTask(Runnable run);
|
||||
|
||||
int scheduleSyncDelayedTask(Runnable run);
|
||||
|
||||
int scheduleSyncDelayedTask(Runnable run, long delay);
|
||||
|
||||
int scheduleSyncRepeatingTask(Runnable run, long delay, long period);
|
||||
|
||||
//IPermissionsHandler getPermissionsHandler();
|
||||
void reload();
|
||||
|
||||
TntExplodeListener getTNTListener();
|
||||
|
||||
void setGroups(IGroups groups);
|
||||
|
||||
void removeReloadListener(IReload groups);
|
||||
|
||||
IEconomy getEconomy();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public interface IEssentialsModule
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
|
||||
public interface IGroups
|
||||
{
|
||||
String getMainGroup(IUser player);
|
||||
|
||||
boolean inGroup(IUser player, String groupname);
|
||||
|
||||
double getHealCooldown(IUser player);
|
||||
|
||||
double getTeleportCooldown(IUser player);
|
||||
|
||||
double getTeleportDelay(IUser player);
|
||||
|
||||
String getPrefix(IUser player);
|
||||
|
||||
String getSuffix(IUser player);
|
||||
|
||||
int getHomeLimit(IUser player);
|
||||
|
||||
MessageFormat getChatFormat(IUser player);
|
||||
}
|
||||
@@ -3,11 +3,7 @@ package com.earth2me.essentials.api;
|
||||
import java.util.Locale;
|
||||
|
||||
|
||||
public interface II18n {
|
||||
/**
|
||||
* Gets the current locale setting
|
||||
*
|
||||
* @return the current locale, if not set it will return the default locale
|
||||
*/
|
||||
Locale getCurrentLocale();
|
||||
public interface II18n
|
||||
{
|
||||
Locale getCurrentLocale();
|
||||
}
|
||||
@@ -1,166 +1,13 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.CommandSource;
|
||||
import com.earth2me.essentials.User;
|
||||
import com.earth2me.essentials.utils.MaterialUtil;
|
||||
import com.earth2me.essentials.utils.NumberUtil;
|
||||
import com.earth2me.essentials.utils.StringUtil;
|
||||
import net.ess3.api.IEssentials;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public interface IItemDb extends IReload
|
||||
{
|
||||
ItemStack get(final String name, final IUser user) throws Exception;
|
||||
|
||||
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.
|
||||
*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 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(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;
|
||||
|
||||
/**
|
||||
* Serialise an ItemStack into a format that can be decoded by
|
||||
* {@link #get(String) get} and
|
||||
* {@link com.earth2me.essentials.MetaItemStack#parseStringMeta(CommandSource, boolean, String[], int, IEssentials)} MetaItemStack#parseStringMeta}.
|
||||
* Used to encode items for kits.
|
||||
*
|
||||
* @param is Stack to serialise
|
||||
* @return Serialised 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(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
|
||||
*/
|
||||
default Material getFromLegacy(String item) {
|
||||
final String[] split = item.split(":");
|
||||
|
||||
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();
|
||||
ItemStack get(final String name) throws Exception;
|
||||
}
|
||||
@@ -1,65 +1,18 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import net.ess3.api.IUser;
|
||||
import java.util.Collection;
|
||||
import org.bukkit.Location;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface IJails extends IReload
|
||||
{
|
||||
Location getJail(String jailName) throws Exception;
|
||||
|
||||
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;
|
||||
Collection<String> getList() throws Exception;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
void removeJail(String jail) throws Exception;
|
||||
|
||||
/**
|
||||
* Gets the number of jails
|
||||
*
|
||||
* @return the size of the list of jails
|
||||
*/
|
||||
int getCount();
|
||||
void sendToJail(IUser user, String jail) throws Exception;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception if the user is offline or jail does not exist
|
||||
*/
|
||||
void sendToJail(IUser user, String jail) 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;
|
||||
void setJail(String jailName, Location loc) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.settings.Kit;
|
||||
import java.util.Collection;
|
||||
|
||||
|
||||
public interface IKits extends IReload
|
||||
{
|
||||
Kit getKit(String kit) throws Exception;
|
||||
|
||||
void sendKit(IUser user, String kit) throws Exception;
|
||||
|
||||
void sendKit(IUser user, Kit kit) throws Exception;
|
||||
|
||||
Collection<String> getList() throws Exception;
|
||||
|
||||
boolean isEmpty();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.bukkit.permissions.PermissionDefault;
|
||||
|
||||
|
||||
public interface IPermission
|
||||
{
|
||||
String getPermission();
|
||||
|
||||
boolean isAuthorized(CommandSender sender);
|
||||
|
||||
Permission getBukkitPermission();
|
||||
|
||||
PermissionDefault getPermissionDefault();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public interface IReload {
|
||||
void onReload();
|
||||
public interface IReload
|
||||
{
|
||||
void onReload();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
|
||||
public interface IReplyTo
|
||||
{
|
||||
void setReplyTo(CommandSender user);
|
||||
|
||||
CommandSender getReplyTo();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.settings.Settings;
|
||||
import com.earth2me.essentials.storage.IStorageObjectHolder;
|
||||
|
||||
|
||||
public interface ISettings extends IStorageObjectHolder<Settings>
|
||||
{
|
||||
public String getLocale();
|
||||
|
||||
public boolean isDebug();
|
||||
|
||||
public void setDebug(boolean b);
|
||||
}
|
||||
@@ -1,133 +1,28 @@
|
||||
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 org.bukkit.entity.Entity;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
|
||||
|
||||
|
||||
public interface ITeleport {
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
public interface ITeleport
|
||||
{
|
||||
void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception;
|
||||
|
||||
@Deprecated
|
||||
void teleport(Location loc, Trade chargeFor) throws Exception;
|
||||
void back(Trade chargeFor) 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
|
||||
* @param cause - The reported teleportPlayer cause
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
void teleport(Location bed, Trade charge, TeleportCause teleportCause) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
void home(IUser player, String toLowerCase, Trade charge) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
void respawn(Trade charge, TeleportCause teleportCause) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
void back(IUser teleporter, Trade chargeFor) throws Exception;
|
||||
|
||||
/**
|
||||
* Teleport wrapper used to handle throwing user home after a jail sentence
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void back() throws Exception;
|
||||
void back() throws Exception;
|
||||
|
||||
public void warp(String name, Trade charge, TeleportCause teleportCause) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.storage.IStorageObjectHolder;
|
||||
import com.earth2me.essentials.user.CooldownException;
|
||||
import com.earth2me.essentials.user.UserData;
|
||||
import java.util.List;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
|
||||
public interface IUser extends Player, IStorageObjectHolder<UserData>, IReload, IReplyTo, Comparable<IUser>
|
||||
{
|
||||
Player getBase();
|
||||
|
||||
double getMoney();
|
||||
|
||||
void takeMoney(double value);
|
||||
|
||||
void takeMoney(double value, CommandSender initiator);
|
||||
|
||||
void giveMoney(double value);
|
||||
|
||||
void giveMoney(double value, CommandSender initiator);
|
||||
|
||||
void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException;
|
||||
|
||||
void giveItems(List<ItemStack> itemStacks, Boolean canSpew) throws ChargeException;
|
||||
|
||||
void setMoney(double value);
|
||||
|
||||
void payUser(final IUser reciever, final double value) throws Exception;
|
||||
|
||||
void setLastLocation();
|
||||
|
||||
Location getHome(String name) throws Exception;
|
||||
|
||||
Location getHome(Location loc);
|
||||
|
||||
boolean isHidden();
|
||||
|
||||
ITeleport getTeleport();
|
||||
|
||||
void checkCooldown(UserData.TimestampType cooldownType, double cooldown, boolean set, IPermission bypassPermission) throws CooldownException;
|
||||
|
||||
boolean toggleAfk();
|
||||
|
||||
void updateActivity(boolean broadcast);
|
||||
|
||||
void updateDisplayName();
|
||||
|
||||
boolean checkJailTimeout(long currentTime);
|
||||
|
||||
boolean checkMuteTimeout(long currentTime);
|
||||
|
||||
boolean checkBanTimeout(long currentTime);
|
||||
|
||||
long getTimestamp(UserData.TimestampType name);
|
||||
|
||||
void setTimestamp(UserData.TimestampType name, long value);
|
||||
|
||||
void setLastOnlineActivity(long currentTime);
|
||||
|
||||
void checkActivity();
|
||||
|
||||
long getLastOnlineActivity();
|
||||
|
||||
boolean isGodModeEnabled();
|
||||
|
||||
boolean isIgnoringPlayer(String name);
|
||||
|
||||
void setIgnoredPlayer(String name, boolean set);
|
||||
|
||||
Location getAfkPosition();
|
||||
|
||||
boolean toggleGodModeEnabled();
|
||||
|
||||
void dispose();
|
||||
|
||||
void updateCompass();
|
||||
|
||||
List<String> getHomes();
|
||||
|
||||
void addMail(String string);
|
||||
|
||||
boolean toggleMuted();
|
||||
|
||||
boolean toggleSocialSpy();
|
||||
|
||||
void requestTeleport(IUser user, boolean b);
|
||||
|
||||
boolean isTeleportRequestHere();
|
||||
|
||||
IUser getTeleportRequester();
|
||||
|
||||
boolean toggleTeleportEnabled();
|
||||
|
||||
long getTeleportRequestTime();
|
||||
|
||||
boolean gotMailInfo();
|
||||
|
||||
List<String> getMails();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
||||
public interface IUserMap extends IReload
|
||||
{
|
||||
boolean userExists(final String name);
|
||||
|
||||
IUser getUser(final Player player);
|
||||
|
||||
IUser getUser(final String playerName);
|
||||
|
||||
void removeUser(final String name) throws InvalidNameException;
|
||||
|
||||
Set<String> getAllUniqueUsers();
|
||||
|
||||
int getUniqueUsers();
|
||||
|
||||
File getUserFile(final String name) throws InvalidNameException;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import com.earth2me.essentials.settings.Warp;
|
||||
import com.earth2me.essentials.storage.IStorageObjectHolder;
|
||||
|
||||
|
||||
public interface IWarp extends IStorageObjectHolder<Warp>
|
||||
{
|
||||
}
|
||||
@@ -1,95 +1,21 @@
|
||||
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;
|
||||
import org.bukkit.Location;
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
Location getWarp(String warp) throws WarpNotFoundException, net.ess3.api.InvalidWorldException;
|
||||
public interface IWarps extends IReload
|
||||
{
|
||||
Location getWarp(String warp) throws Exception;
|
||||
|
||||
/**
|
||||
* Gets a list of warps
|
||||
*
|
||||
* @return - A {@link Collection} of warps
|
||||
*/
|
||||
Collection<String> getList();
|
||||
Collection<String> getList();
|
||||
|
||||
/**
|
||||
* Gets the number of warps
|
||||
*
|
||||
* @return the size of the list of warps
|
||||
*/
|
||||
int getCount();
|
||||
void removeWarp(String name) throws Exception;
|
||||
|
||||
/**
|
||||
* Delete a warp from the warp DB
|
||||
*
|
||||
* @param name - Name of warp
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void removeWarp(String name) throws Exception;
|
||||
void setWarp(String name, Location loc) throws Exception;
|
||||
|
||||
/**
|
||||
* Set a warp
|
||||
*
|
||||
* @param name - Name of warp
|
||||
* @param loc - Location of warp
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
void setWarp(String name, Location loc) throws Exception;
|
||||
public boolean isEmpty();
|
||||
|
||||
/**
|
||||
* 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 name - Name of warp
|
||||
*
|
||||
* @throws WarpNotFoundException
|
||||
*/
|
||||
UUID getLastOwner(String warp) throws WarpNotFoundException;
|
||||
/**
|
||||
* Check to see if the file is empty
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
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
|
||||
*/
|
||||
File getWarpFile(String name) throws net.ess3.api.InvalidNameException;
|
||||
public File getWarpFile(String name) throws InvalidNameException;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
|
||||
public interface IWorth extends IReload
|
||||
{
|
||||
double getPrice(ItemStack itemStack);
|
||||
|
||||
void setPrice(ItemStack itemStack, double price);
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
|
||||
public class InvalidNameException extends Exception {
|
||||
/**
|
||||
* NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the
|
||||
* InvalidNameException exception
|
||||
*/
|
||||
private static final long serialVersionUID = 1485321420293663139L;
|
||||
|
||||
public InvalidNameException(Throwable thrwbl) {
|
||||
super(thrwbl);
|
||||
}
|
||||
public class InvalidNameException extends Exception
|
||||
{
|
||||
public InvalidNameException(Throwable thrwbl)
|
||||
{
|
||||
super(thrwbl);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.earth2me.essentials.api;
|
||||
|
||||
import static com.earth2me.essentials.I18n.tl;
|
||||
|
||||
|
||||
public class InvalidWorldException extends Exception {
|
||||
private final String world;
|
||||
|
||||
public InvalidWorldException(final String world) {
|
||||
super(tl("invalidWorld"));
|
||||
this.world = world;
|
||||
}
|
||||
|
||||
public String getWorld() {
|
||||
return this.world;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 837 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user