From b7dfd5d9e34f9c6d48781a3065ee8d0547153373 Mon Sep 17 00:00:00 2001 From: okx-code Date: Mon, 13 Apr 2020 14:24:31 +0100 Subject: [PATCH] 3.7 add prestige-based requirements --- .gitignore | 26 +- CONTRIBUTING.md | 10 +- LICENSE.md | 42 +- README.md | 122 +- build.gradle | 140 +- gradle/wrapper/gradle-wrapper.properties | 12 +- gradlew | 376 ++--- gradlew.bat | 200 +-- lombok.config | 4 +- settings.gradle | 4 +- src/main/java/sh/okx/rankup/AutoRankup.java | 58 +- .../sh/okx/rankup/JoinUpdateNotifier.java | 62 +- src/main/java/sh/okx/rankup/Metrics.java | 1436 ++++++++--------- src/main/java/sh/okx/rankup/RankList.java | 256 +-- src/main/java/sh/okx/rankup/RankupHelper.java | 422 ++--- src/main/java/sh/okx/rankup/RankupPlugin.java | 1004 ++++++------ .../sh/okx/rankup/RankupRegisterEvent.java | 76 +- .../sh/okx/rankup/commands/InfoCommand.java | 260 +-- .../okx/rankup/commands/MaxRankupCommand.java | 90 +- .../okx/rankup/commands/PrestigeCommand.java | 146 +- .../okx/rankup/commands/PrestigesCommand.java | 100 +- .../sh/okx/rankup/commands/RanksCommand.java | 94 +- .../sh/okx/rankup/commands/RankupCommand.java | 162 +- src/main/java/sh/okx/rankup/gui/Gui.java | 278 ++-- .../java/sh/okx/rankup/gui/GuiListener.java | 80 +- .../sh/okx/rankup/hook/PermissionManager.java | 60 +- .../okx/rankup/hook/PermissionProvider.java | 18 +- .../rankup/hook/VaultPermissionProvider.java | 88 +- .../java/sh/okx/rankup/messages/Message.java | 80 +- .../okx/rankup/messages/MessageBuilder.java | 248 +-- .../rankup/messages/NullMessageBuilder.java | 70 +- .../java/sh/okx/rankup/messages/Variable.java | 36 +- .../okx/rankup/placeholders/Placeholders.java | 88 +- .../rankup/placeholders/RankupExpansion.java | 438 ++--- .../java/sh/okx/rankup/prestige/Prestige.java | 158 +- .../sh/okx/rankup/prestige/Prestiges.java | 44 +- src/main/java/sh/okx/rankup/ranks/Rank.java | 126 +- src/main/java/sh/okx/rankup/ranks/Rankup.java | 64 +- .../java/sh/okx/rankup/ranks/Rankups.java | 22 +- .../requirements/ListRankRequirements.java | 96 +- .../PrestigeListRankRequirements.java | 126 +- .../ranks/requirements/RankRequirements.java | 26 +- .../requirements/RankRequirementsFactory.java | 144 +- .../requirements/DeductibleRequirement.java | 42 +- .../requirements/ProgressiveRequirement.java | 68 +- .../okx/rankup/requirements/Requirement.java | 208 +-- .../requirements/RequirementRegistry.java | 98 +- .../XpLevelDeductibleRequirement.java | 52 +- .../requirement/BlockBreakRequirement.java | 64 +- .../requirement/CraftItemRequirement.java | 64 +- .../requirement/GroupRequirement.java | 60 +- .../ItemDeductibleRequirement.java | 98 +- .../requirement/ItemRequirement.java | 124 +- .../requirement/MobKillsRequirement.java | 64 +- .../MoneyDeductibleRequirement.java | 58 +- .../requirement/MoneyRequirement.java | 50 +- .../requirement/PermissionRequirement.java | 60 +- .../requirement/PlaceholderRequirement.java | 180 +-- .../requirement/PlayerKillsRequirement.java | 54 +- .../PlaytimeMinutesRequirement.java | 74 +- .../TokensDeductibleRequirement.java | 52 +- .../requirement/TotalMobKillsRequirement.java | 54 +- .../requirement/UseItemRequirement.java | 64 +- .../requirement/WorldRequirement.java | 58 +- .../requirement/XpLevelRequirement.java | 50 +- ...cedAchievementsAchievementRequirement.java | 76 +- .../AdvancedAchievementsTotalRequirement.java | 54 +- .../mcmmo/McMMOPowerLevelRequirement.java | 54 +- .../mcmmo/McMMOSkillRequirement.java | 52 +- .../requirement/mcmmo/McMMOSkillUtil.java | 182 +-- .../tokenmanager/TokensRequirement.java | 60 +- .../TownyKingNumberResidentsRequirement.java | 60 +- .../TownyKingNumberTownsRequirement.java | 60 +- .../towny/TownyKingRequirement.java | 50 +- .../TownyMayorNumberResidentsRequirement.java | 60 +- .../towny/TownyMayorRequirement.java | 50 +- .../towny/TownyResidentRequirement.java | 50 +- .../requirement/towny/TownyUtils.java | 142 +- .../VotingPluginVotesRequirement.java | 54 +- .../java/sh/okx/rankup/util/ItemUtil.java | 58 +- .../sh/okx/rankup/util/UpdateNotifier.java | 114 +- .../sh/okx/rankup/util/VersionChecker.java | 300 ++-- src/main/resources/LICENSE.txt | 42 +- src/main/resources/config.yml | 182 +-- src/main/resources/locale/en.yml | 204 +-- src/main/resources/locale/pt_br.yml | 212 +-- src/main/resources/locale/ru.yml | 208 +-- src/main/resources/locale/zh_cn.yml | 126 +- src/main/resources/plugin.yml | 128 +- src/main/resources/prestiges.yml | 36 +- src/main/resources/rankups.yml | 86 +- .../rankup/messages/MessageBuilderTest.java | 26 +- 92 files changed, 5908 insertions(+), 5906 deletions(-) diff --git a/.gitignore b/.gitignore index 11b2ff8..9c26a94 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,14 @@ -.gradle -build/ -.idea/ -*.iml - -# Ignore Gradle GUI config -gradle-app.setting - -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar - -out/ - +.gradle +build/ +.idea/ +*.iml + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +out/ + spigot/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fa5ea72..c0f054b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,5 @@ -## Style Guide - -Rankup using the Google Java Style guide apart from the following exceptions: - -- The column limit of 100 is more flexible +## Style Guide + +Rankup using the Google Java Style guide apart from the following exceptions: + +- The column limit of 100 is more flexible diff --git a/LICENSE.md b/LICENSE.md index 7d3e802..d567c0e 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,21 +1,21 @@ -The MIT License (MIT) - -Copyright (c) 2018-2020 Okx - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +The MIT License (MIT) + +Copyright (c) 2018-2020 Okx + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 09263c2..d720d7a 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,61 @@ -# Rankup3 - -## Installation - -Rankup can be compiled with the `gradle build` command. The compiled plugin jar will be in the `/build/libs` directory. - -## Translation - -If you would like to contribute to translating the plugin, you can fork it. -Locale names are in ISO-639-1 and are in the folder [`src/main/resources/locale`](https://github.com/okx-code/Rankup3/tree/master/src/main/resources/locale) - -When a locale is added, it should be saved [here](https://github.com/okx-code/Rankup3/blob/master/src/main/java/sh/okx/rankup/Rankup.java#L242), ie through adding a line such as `saveLocale("es");`. However, I can do it if you forget. - -You can use the [English](https://github.com/okx-code/Rankup3/blob/locale/src/main/resources/locale/en.yml) locale to help translate. - -Locales should be added or modified with a pull request, but if you wish to contribute often I can give you push access to this branch. - -Here is a blank template for new locales: - -```yaml -rankup: - requirements-not-met: - no-rankup: - success-public: - success-private: - confirmation: - title: - must-prestige: - list: - complete: - current: - incomplete: - header: "" - footer: "" - cooldown: - singular: - plural: -prestige: - requirements-not-met: - no-prestige: - - success-public: - success-private: - - confirmation: - title: - - list: - complete: - current: - incomplete: - header: "" - footer: "" - cooldown: - singular: - plural: - -not-high-enough: -not-in-ladder: -invalid-rankup: -``` +# Rankup3 + +## Installation + +Rankup can be compiled with the `gradle build` command. The compiled plugin jar will be in the `/build/libs` directory. + +## Translation + +If you would like to contribute to translating the plugin, you can fork it. +Locale names are in ISO-639-1 and are in the folder [`src/main/resources/locale`](https://github.com/okx-code/Rankup3/tree/master/src/main/resources/locale) + +When a locale is added, it should be saved [here](https://github.com/okx-code/Rankup3/blob/master/src/main/java/sh/okx/rankup/Rankup.java#L242), ie through adding a line such as `saveLocale("es");`. However, I can do it if you forget. + +You can use the [English](https://github.com/okx-code/Rankup3/blob/locale/src/main/resources/locale/en.yml) locale to help translate. + +Locales should be added or modified with a pull request, but if you wish to contribute often I can give you push access to this branch. + +Here is a blank template for new locales: + +```yaml +rankup: + requirements-not-met: + no-rankup: + success-public: + success-private: + confirmation: + title: + must-prestige: + list: + complete: + current: + incomplete: + header: "" + footer: "" + cooldown: + singular: + plural: +prestige: + requirements-not-met: + no-prestige: + + success-public: + success-private: + + confirmation: + title: + + list: + complete: + current: + incomplete: + header: "" + footer: "" + cooldown: + singular: + plural: + +not-high-enough: +not-in-ladder: +invalid-rankup: +``` diff --git a/build.gradle b/build.gradle index fcd1d70..39ed037 100644 --- a/build.gradle +++ b/build.gradle @@ -1,71 +1,71 @@ -plugins { - id 'java' - id "io.freefair.lombok" version "4.1.6" -} - -group 'sh.okx' -version '3.7-beta' - -repositories { - mavenCentral() - mavenLocal() - maven { - url 'http://nexus.hc.to/content/repositories/pub_releases' - } - maven { - url 'https://hub.spigotmc.org/nexus/content/groups/public/' - } - maven { - url 'http://repo.extendedclip.com/content/repositories/placeholderapi/' - } - maven { - url 'https://raw.github.com/PyvesB/AdvancedAchievements/mvn-repo/' - } - // for plugins without repos, namely mcmmo, votingplugin, and towny - maven { - url 'https://jitpack.io' - } -} - -dependencies { - testImplementation group: 'junit', name: 'junit', version: '4.12' - compileOnly 'org.jetbrains:annotations:16.0.2' - implementation 'org.spigotmc:spigot:1.15.2-R0.1-SNAPSHOT' - implementation('com.github.Realizedd:TokenManager:3.2.4') { - transitive = false - } - - implementation('net.milkbowl.vault:VaultAPI:1.7') { - exclude group: 'org.bukkit' - } - implementation 'me.clip:placeholderapi:2.9.2' - implementation 'com.hm.achievement:advanced-achievements-api:1.1.0' - implementation('com.github.mcMMO-Dev:mcMMO:601297') { - exclude group: 'com.sk89q.worldguard' - } - implementation 'com.github.Ben12345rocks:VotingPlugin:5.18.2' - implementation 'com.github.LlmDl:Towny:25fc18a' -} - -// automatically copy the version to plugin.yml -processResources { - // do this again whenever version changes - inputs.property 'version', project.version - - // copy plugin.yml and replace version - from(sourceSets.main.resources.srcDirs) { - include 'plugin.yml' - expand 'version': project.version - } - - // copy everything else - from(sourceSets.main.resources.srcDirs) { - exclude 'plugin.yml' - } -} - -task spigot(type: Jar) { - from sourceSets.main.runtimeClasspath - destinationDirectory = file("./spigot/plugins/") - archiveFileName = "Rankup.jar" +plugins { + id 'java' + id "io.freefair.lombok" version "4.1.6" +} + +group 'sh.okx' +version '3.7-beta' + +repositories { + mavenCentral() + mavenLocal() + maven { + url 'http://nexus.hc.to/content/repositories/pub_releases' + } + maven { + url 'https://hub.spigotmc.org/nexus/content/groups/public/' + } + maven { + url 'http://repo.extendedclip.com/content/repositories/placeholderapi/' + } + maven { + url 'https://raw.github.com/PyvesB/AdvancedAchievements/mvn-repo/' + } + // for plugins without repos, namely mcmmo, votingplugin, and towny + maven { + url 'https://jitpack.io' + } +} + +dependencies { + testImplementation group: 'junit', name: 'junit', version: '4.12' + compileOnly 'org.jetbrains:annotations:16.0.2' + implementation 'org.spigotmc:spigot:1.15.2-R0.1-SNAPSHOT' + implementation('com.github.Realizedd:TokenManager:3.2.4') { + transitive = false + } + + implementation('net.milkbowl.vault:VaultAPI:1.7') { + exclude group: 'org.bukkit' + } + implementation 'me.clip:placeholderapi:2.9.2' + implementation 'com.hm.achievement:advanced-achievements-api:1.1.0' + implementation('com.github.mcMMO-Dev:mcMMO:601297') { + exclude group: 'com.sk89q.worldguard' + } + implementation 'com.github.Ben12345rocks:VotingPlugin:5.18.2' + implementation 'com.github.LlmDl:Towny:25fc18a' +} + +// automatically copy the version to plugin.yml +processResources { + // do this again whenever version changes + inputs.property 'version', project.version + + // copy plugin.yml and replace version + from(sourceSets.main.resources.srcDirs) { + include 'plugin.yml' + expand 'version': project.version + } + + // copy everything else + from(sourceSets.main.resources.srcDirs) { + exclude 'plugin.yml' + } +} + +task spigot(type: Jar) { + from sourceSets.main.runtimeClasspath + destinationDirectory = file("./spigot/plugins/") + archiveFileName = "Rankup.jar" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 820c074..4c9e569 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sun Apr 05 14:05:23 BST 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStorePath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME +#Sun Apr 05 14:05:23 BST 2020 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index b0d6d0a..cba68cc 100755 --- a/gradlew +++ b/gradlew @@ -1,188 +1,188 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 9991c50..15e1ee3 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,100 +1,100 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem http://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lombok.config b/lombok.config index 6aa51d7..cf350fc 100644 --- a/lombok.config +++ b/lombok.config @@ -1,2 +1,2 @@ -# This file is generated by the 'io.freefair.lombok' Gradle plugin -config.stopBubbling = true +# This file is generated by the 'io.freefair.lombok' Gradle plugin +config.stopBubbling = true diff --git a/settings.gradle b/settings.gradle index 423c743..b04a0ed 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,2 @@ -rootProject.name = 'Rankup' - +rootProject.name = 'Rankup' + diff --git a/src/main/java/sh/okx/rankup/AutoRankup.java b/src/main/java/sh/okx/rankup/AutoRankup.java index 1c7e7fe..2c88dbd 100644 --- a/src/main/java/sh/okx/rankup/AutoRankup.java +++ b/src/main/java/sh/okx/rankup/AutoRankup.java @@ -1,29 +1,29 @@ -package sh.okx.rankup; - -import lombok.RequiredArgsConstructor; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -@RequiredArgsConstructor -public class AutoRankup extends BukkitRunnable { - private final RankupPlugin rankup; - - @Override - public void run() { - if (rankup.error()) { - return; - } - - RankupHelper helper = rankup.getHelper(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.hasPermission("rankup.auto")) { - if (helper.checkRankup(player, false)) { - helper.rankup(player); - } else if (rankup.getPrestiges() != null && helper.checkPrestige(player, false)) { - helper.prestige(player); - } - } - } - } -} +package sh.okx.rankup; + +import lombok.RequiredArgsConstructor; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +@RequiredArgsConstructor +public class AutoRankup extends BukkitRunnable { + private final RankupPlugin rankup; + + @Override + public void run() { + if (rankup.error()) { + return; + } + + RankupHelper helper = rankup.getHelper(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.hasPermission("rankup.auto")) { + if (helper.checkRankup(player, false)) { + helper.rankup(player); + } else if (rankup.getPrestiges() != null && helper.checkPrestige(player, false)) { + helper.prestige(player); + } + } + } + } +} diff --git a/src/main/java/sh/okx/rankup/JoinUpdateNotifier.java b/src/main/java/sh/okx/rankup/JoinUpdateNotifier.java index 73c1c0d..c1b4a93 100644 --- a/src/main/java/sh/okx/rankup/JoinUpdateNotifier.java +++ b/src/main/java/sh/okx/rankup/JoinUpdateNotifier.java @@ -1,31 +1,31 @@ -package sh.okx.rankup; - -import java.util.function.Supplier; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import sh.okx.rankup.util.UpdateNotifier; - -public class JoinUpdateNotifier implements Listener { - private final UpdateNotifier notifier; - private final Supplier enabledSupplier; - private final String permission; - - public JoinUpdateNotifier(UpdateNotifier notifier, - Supplier enabledSupplier, String permission) { - this.notifier = notifier; - this.enabledSupplier = enabledSupplier; - this.permission = permission; - } - - @EventHandler - public void on(PlayerJoinEvent e) { - if (enabledSupplier.get()) { - Player player = e.getPlayer(); - if (player.hasPermission(permission)) { - notifier.notify(player, true); - } - } - } -} +package sh.okx.rankup; + +import java.util.function.Supplier; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import sh.okx.rankup.util.UpdateNotifier; + +public class JoinUpdateNotifier implements Listener { + private final UpdateNotifier notifier; + private final Supplier enabledSupplier; + private final String permission; + + public JoinUpdateNotifier(UpdateNotifier notifier, + Supplier enabledSupplier, String permission) { + this.notifier = notifier; + this.enabledSupplier = enabledSupplier; + this.permission = permission; + } + + @EventHandler + public void on(PlayerJoinEvent e) { + if (enabledSupplier.get()) { + Player player = e.getPlayer(); + if (player.hasPermission(permission)) { + notifier.notify(player, true); + } + } + } +} diff --git a/src/main/java/sh/okx/rankup/Metrics.java b/src/main/java/sh/okx/rankup/Metrics.java index eb42ff3..c260714 100644 --- a/src/main/java/sh/okx/rankup/Metrics.java +++ b/src/main/java/sh/okx/rankup/Metrics.java @@ -1,718 +1,718 @@ -package sh.okx.rankup; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -public class Metrics { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final Plugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - enabled = config.getBoolean("enabled", true); - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - if (enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.add("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch (ClassNotFoundException e) { - // minecraft version 1.14+ - if (logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); - } - continue; // continue looping since we cannot do any other thing. - } - } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - } catch (NoSuchFieldException ignored) { } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data.toString()); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - InputStream inputStream = connection.getInputStream(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuilder builder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - bufferedReader.close(); - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); - chart.addProperty("chartId", chartId); - try { - JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.add("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JsonObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.addProperty(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.add(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); - categoryValues.add(entry.getValue()); - values.add(entry.getKey(), categoryValues); - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.add(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - -} +package sh.okx.rankup; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + continue; // continue looping since we cannot do any other thing. + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + bufferedReader.close(); + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(entry.getValue()); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + +} diff --git a/src/main/java/sh/okx/rankup/RankList.java b/src/main/java/sh/okx/rankup/RankList.java index 9544f30..fef7192 100644 --- a/src/main/java/sh/okx/rankup/RankList.java +++ b/src/main/java/sh/okx/rankup/RankList.java @@ -1,128 +1,128 @@ -package sh.okx.rankup; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import lombok.Getter; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import sh.okx.rankup.hook.PermissionProvider; -import sh.okx.rankup.ranks.Rank; - -public class RankList { - @Getter - protected final FileConfiguration config; - protected final Set ranks = new HashSet<>(); - - public RankList(FileConfiguration config, Function deserializer) { - this.config = config; - for (Map.Entry entry : config.getValues(false).entrySet()) { - ConfigurationSection rankSection = (ConfigurationSection) entry.getValue(); - validateSection(rankSection); - T apply = deserializer.apply(rankSection); - if (apply != null) { - ranks.add(apply); - } - } - List ordered = getOrderedList(); - Set provisionalRanks = new HashSet<>(ordered); - this.ranks.clear(); - this.ranks.addAll(provisionalRanks); - } - - protected void validateSection(ConfigurationSection section) { - String name = "'" + section.getName() + "'"; - /*if (section.getConfigurationSection("requirements") != null) { - throw new IllegalArgumentException( - "Rankup/prestige section " + name + " is using the old requirements system.\n" + - "Instead of a configuration section, it is now a list of strings.\n" + - "For example, instead of \"requirements: money: 1000\" you should use \"requirements: - 'money 1000'\"."); - }*/ - Set keys = section.getKeys(false); - if (keys.size() == 1 && keys.iterator().next().equalsIgnoreCase("rank")) { - throw new IllegalArgumentException( - "Having a final rank (for example: \"Z: rank: 'Z'\") from 3.4.2 or earlier should no longer be used.\n" + - "It is safe to just delete the final rank " + name + ""); - } else if (!section.contains("requirements")) { - throw new IllegalArgumentException("Rank " + name + " does not have any requirements."); - } - } - - public T getFirst() { - OUTER: - for (T rank : ranks) { - // see if anything ranks up to this - for (T rank0 : ranks) { - if (rank0.getNext().equals(rank.getRank())) { - continue OUTER; - } - } - // nothing ranks up to this - return rank; - } - throw new IllegalArgumentException("Could not find a first rank. First ranks must not have anything that ranks up to them."); - } - - public List getOrderedList() { - List list = new ArrayList<>(); - T t = getFirst(); - while (t != null) { - for (T existing : list) { - if (existing.equals(t)) { - throw new IllegalArgumentException("Infinite rankup loop detected at rank " + t.getRank() + " to " + t.getNext() - + "\nMake sure no there are no rankups to previous ranks or to the same rank"); - } - } - list.add(t); - t = next(t); - } - return list; - } - - public T getByName(String name) { - if (name == null) { - return null; - } - for (T rank : ranks) { - if (name.equalsIgnoreCase(rank.getRank())) { - return rank; - } - } - return null; - } - - public T getByPlayer(Player player) { - List list = getOrderedList(); - Collections.reverse(list); - for (T t : list) { - if (t.isIn(player)) { - return t; - } - } - return null; - } - - public String getLast() { - List list = getOrderedList(); - return list.get(list.size() - 1).getNext(); - } - - public boolean isLast(PermissionProvider perms, Player player) { - String last = getLast(); - return perms.inGroup(player.getUniqueId(), last); - } - - public T next(T rank) { - for (T nextRank : ranks) { - if (rank.getNext() != null && rank.getNext().equalsIgnoreCase(nextRank.getRank())) { - return nextRank; - } - } - return null; - } -} +package sh.okx.rankup; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import lombok.Getter; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import sh.okx.rankup.hook.PermissionProvider; +import sh.okx.rankup.ranks.Rank; + +public class RankList { + @Getter + protected final FileConfiguration config; + protected final Set ranks = new HashSet<>(); + + public RankList(FileConfiguration config, Function deserializer) { + this.config = config; + for (Map.Entry entry : config.getValues(false).entrySet()) { + ConfigurationSection rankSection = (ConfigurationSection) entry.getValue(); + validateSection(rankSection); + T apply = deserializer.apply(rankSection); + if (apply != null) { + ranks.add(apply); + } + } + List ordered = getOrderedList(); + Set provisionalRanks = new HashSet<>(ordered); + this.ranks.clear(); + this.ranks.addAll(provisionalRanks); + } + + protected void validateSection(ConfigurationSection section) { + String name = "'" + section.getName() + "'"; + /*if (section.getConfigurationSection("requirements") != null) { + throw new IllegalArgumentException( + "Rankup/prestige section " + name + " is using the old requirements system.\n" + + "Instead of a configuration section, it is now a list of strings.\n" + + "For example, instead of \"requirements: money: 1000\" you should use \"requirements: - 'money 1000'\"."); + }*/ + Set keys = section.getKeys(false); + if (keys.size() == 1 && keys.iterator().next().equalsIgnoreCase("rank")) { + throw new IllegalArgumentException( + "Having a final rank (for example: \"Z: rank: 'Z'\") from 3.4.2 or earlier should no longer be used.\n" + + "It is safe to just delete the final rank " + name + ""); + } else if (!section.contains("requirements")) { + throw new IllegalArgumentException("Rank " + name + " does not have any requirements."); + } + } + + public T getFirst() { + OUTER: + for (T rank : ranks) { + // see if anything ranks up to this + for (T rank0 : ranks) { + if (rank0.getNext().equals(rank.getRank())) { + continue OUTER; + } + } + // nothing ranks up to this + return rank; + } + throw new IllegalArgumentException("Could not find a first rank. First ranks must not have anything that ranks up to them."); + } + + public List getOrderedList() { + List list = new ArrayList<>(); + T t = getFirst(); + while (t != null) { + for (T existing : list) { + if (existing.equals(t)) { + throw new IllegalArgumentException("Infinite rankup loop detected at rank " + t.getRank() + " to " + t.getNext() + + "\nMake sure no there are no rankups to previous ranks or to the same rank"); + } + } + list.add(t); + t = next(t); + } + return list; + } + + public T getByName(String name) { + if (name == null) { + return null; + } + for (T rank : ranks) { + if (name.equalsIgnoreCase(rank.getRank())) { + return rank; + } + } + return null; + } + + public T getByPlayer(Player player) { + List list = getOrderedList(); + Collections.reverse(list); + for (T t : list) { + if (t.isIn(player)) { + return t; + } + } + return null; + } + + public String getLast() { + List list = getOrderedList(); + return list.get(list.size() - 1).getNext(); + } + + public boolean isLast(PermissionProvider perms, Player player) { + String last = getLast(); + return perms.inGroup(player.getUniqueId(), last); + } + + public T next(T rank) { + for (T nextRank : ranks) { + if (rank.getNext() != null && rank.getNext().equalsIgnoreCase(nextRank.getRank())) { + return nextRank; + } + } + return null; + } +} diff --git a/src/main/java/sh/okx/rankup/RankupHelper.java b/src/main/java/sh/okx/rankup/RankupHelper.java index 40c372b..737264e 100644 --- a/src/main/java/sh/okx/rankup/RankupHelper.java +++ b/src/main/java/sh/okx/rankup/RankupHelper.java @@ -1,211 +1,211 @@ -package sh.okx.rankup; - -import java.util.HashMap; -import java.util.Map; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import sh.okx.rankup.hook.PermissionProvider; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.messages.Variable; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; - -/** - * Actually performs the ranking up and prestiging for the plugin and also manages the cooldowns - * between ranking up. - */ -public class RankupHelper { - - private final RankupPlugin plugin; - private final ConfigurationSection config; - private final PermissionProvider permissions; - /** - * Players who cannot rankup/prestige for a certain amount of time. - */ - private Map cooldowns = new HashMap<>(); - - public RankupHelper(RankupPlugin plugin) { - this.plugin = plugin; - this.config = plugin.getConfig(); - this.permissions = plugin.getPermissions(); - } - - public void doRankup(Player player, Rank rank) { - rank.runCommands(player); - - if (rank.getRank() != null) { - permissions.removeGroup(player.getUniqueId(), rank.getRank()); - } - permissions.addGroup(player.getUniqueId(), rank.getNext()); - } - - public void sendRankupMessages(Player player, Rank rank) { - plugin.getMessage(rank, Message.SUCCESS_PUBLIC) - .failIfEmpty() - .replaceRanks(player, rank, rank.getNext()) - .broadcast(); - plugin.getMessage(rank, Message.SUCCESS_PRIVATE) - .failIfEmpty() - .replaceRanks(player, rank, rank.getNext()) - .send(player); - } - - public void doPrestige(Player player, Prestige prestige) { - prestige.runCommands(player); - - permissions.removeGroup(player.getUniqueId(), prestige.getFrom()); - permissions.addGroup(player.getUniqueId(), prestige.getTo()); - - if (prestige.getRank() != null) { - permissions.removeGroup(player.getUniqueId(), prestige.getRank()); - } - permissions.addGroup(player.getUniqueId(), prestige.getNext()); - } - - public void sendPrestigeMessages(Player player, Prestige prestige) { - plugin.getMessage(prestige, Message.PRESTIGE_SUCCESS_PUBLIC) - .failIfEmpty() - .replaceRanks(player, prestige, prestige.getNext()) - .replaceFromTo(prestige) - .broadcast(); - plugin.getMessage(prestige, Message.PRESTIGE_SUCCESS_PRIVATE) - .failIfEmpty() - .replaceRanks(player, prestige, prestige.getNext()) - .replaceFromTo(prestige) - .send(player); - } - - private boolean checkCooldown(Player player, Rank rank) { - if (cooldowns.containsKey(player)) { - long time = System.currentTimeMillis() - cooldowns.get(player); - // if time passed is less than the cooldown - long cooldownSeconds = config.getInt("cooldown"); - long timeLeft = (cooldownSeconds * 1000) - time; - if (timeLeft > 0) { - long secondsLeft = (long) Math.ceil(timeLeft / 1000f); - plugin - .getMessage(rank, secondsLeft > 1 ? Message.COOLDOWN_PLURAL : Message.COOLDOWN_SINGULAR) - .failIfEmpty() - .replaceRanks(player, rank.getRank()) - .replaceFromTo(rank) - .replace(Variable.SECONDS, cooldownSeconds) - .replace(Variable.SECONDS_LEFT, secondsLeft) - .send(player); - return true; - } - // cooldown has expired so remove it - cooldowns.remove(player); - } - return false; - } - - private void applyCooldown(Player player) { - if (config.getInt("cooldown") > 0) { - cooldowns.put(player, System.currentTimeMillis()); - } - } - - public void rankup(Player player) { - if (!checkRankup(player)) { - return; - } - - Rank rank = plugin.getRankups().getByPlayer(player); - rank.applyRequirements(player); - applyCooldown(player); - - doRankup(player, rank); - sendRankupMessages(player, rank); - } - - public boolean checkRankup(Player player) { - return checkRankup(player, true); - } - - /** - * Checks if a player can rankup, and if they can't, sends the player a message and returns false - * - * @param player the player to check if they can rankup - * @return true if the player can rankup, false otherwise - */ - public boolean checkRankup(Player player, boolean message) { - Rankups rankups = plugin.getRankups(); - Rank rank = rankups.getByPlayer(player); - if (rankups.isLast(permissions, player)) { - Prestiges prestiges = plugin.getPrestiges(); - plugin.getMessage(prestiges == null || prestiges.isLast(permissions, player) ? Message.NO_RANKUP : Message.MUST_PRESTIGE) - .failIf(!message) - .replaceRanks(player, rankups.getLast()) - .send(player); - return false; - } else if (rank == null) { // check if in ladder - plugin.getMessage(Message.NOT_IN_LADDER) - .failIf(!message) - .replace(Variable.PLAYER, player.getName()) - .send(player); - return false; - } else if (!rank.hasRequirements(player)) { // check if they can afford it - if (message) { - plugin.replaceMoneyRequirements(plugin.getMessage(rank, Message.REQUIREMENTS_NOT_MET) - .replaceRanks(player, rank, rank.getNext()), player, rank) - .send(player); - } - return false; - } else if (message && checkCooldown(player, rank)) { - return false; - } - - return true; - } - - public void prestige(Player player) { - if (!checkPrestige(player)) { - return; - } - - Prestige prestige = plugin.getPrestiges().getByPlayer(player); - prestige.applyRequirements(player); - - applyCooldown(player); - doPrestige(player, prestige); - sendPrestigeMessages(player, prestige); - } - - public boolean checkPrestige(Player player) { - return checkPrestige(player, true); - } - - public boolean checkPrestige(Player player, boolean message) { - Prestiges prestiges = plugin.getPrestiges(); - Prestige prestige = prestiges.getByPlayer(player); - if (prestige == null || !prestige.isEligable(player)) { // check if in ladder - plugin.getMessage(Message.NOT_HIGH_ENOUGH) - .failIf(!message) - .replace(Variable.PLAYER, player.getName()) - .send(player); - return false; - } else if (prestiges - .isLast(plugin.getPermissions(), player)) { // check if they are at the highest rank - plugin.getMessage(prestige, Message.PRESTIGE_NO_PRESTIGE) - .failIf(!message) - .replaceRanks(player, prestige.getRank()) - .replaceFromTo(prestige) - .send(player); - return false; - } else if (!prestige.hasRequirements(player)) { // check if they can afford it - plugin.replaceMoneyRequirements( - plugin.getMessage(prestige, Message.PRESTIGE_REQUIREMENTS_NOT_MET) - .failIf(!message) - .replaceRanks(player, prestige, prestiges.next(prestige).getRank()), player, prestige) - .replaceFromTo(prestige) - .send(player); - return false; - } else if (checkCooldown(player, prestige)) { - return false; - } - - return true; - } -} +package sh.okx.rankup; + +import java.util.HashMap; +import java.util.Map; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import sh.okx.rankup.hook.PermissionProvider; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.messages.Variable; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; + +/** + * Actually performs the ranking up and prestiging for the plugin and also manages the cooldowns + * between ranking up. + */ +public class RankupHelper { + + private final RankupPlugin plugin; + private final ConfigurationSection config; + private final PermissionProvider permissions; + /** + * Players who cannot rankup/prestige for a certain amount of time. + */ + private Map cooldowns = new HashMap<>(); + + public RankupHelper(RankupPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getConfig(); + this.permissions = plugin.getPermissions(); + } + + public void doRankup(Player player, Rank rank) { + rank.runCommands(player); + + if (rank.getRank() != null) { + permissions.removeGroup(player.getUniqueId(), rank.getRank()); + } + permissions.addGroup(player.getUniqueId(), rank.getNext()); + } + + public void sendRankupMessages(Player player, Rank rank) { + plugin.getMessage(rank, Message.SUCCESS_PUBLIC) + .failIfEmpty() + .replaceRanks(player, rank, rank.getNext()) + .broadcast(); + plugin.getMessage(rank, Message.SUCCESS_PRIVATE) + .failIfEmpty() + .replaceRanks(player, rank, rank.getNext()) + .send(player); + } + + public void doPrestige(Player player, Prestige prestige) { + prestige.runCommands(player); + + permissions.removeGroup(player.getUniqueId(), prestige.getFrom()); + permissions.addGroup(player.getUniqueId(), prestige.getTo()); + + if (prestige.getRank() != null) { + permissions.removeGroup(player.getUniqueId(), prestige.getRank()); + } + permissions.addGroup(player.getUniqueId(), prestige.getNext()); + } + + public void sendPrestigeMessages(Player player, Prestige prestige) { + plugin.getMessage(prestige, Message.PRESTIGE_SUCCESS_PUBLIC) + .failIfEmpty() + .replaceRanks(player, prestige, prestige.getNext()) + .replaceFromTo(prestige) + .broadcast(); + plugin.getMessage(prestige, Message.PRESTIGE_SUCCESS_PRIVATE) + .failIfEmpty() + .replaceRanks(player, prestige, prestige.getNext()) + .replaceFromTo(prestige) + .send(player); + } + + private boolean checkCooldown(Player player, Rank rank) { + if (cooldowns.containsKey(player)) { + long time = System.currentTimeMillis() - cooldowns.get(player); + // if time passed is less than the cooldown + long cooldownSeconds = config.getInt("cooldown"); + long timeLeft = (cooldownSeconds * 1000) - time; + if (timeLeft > 0) { + long secondsLeft = (long) Math.ceil(timeLeft / 1000f); + plugin + .getMessage(rank, secondsLeft > 1 ? Message.COOLDOWN_PLURAL : Message.COOLDOWN_SINGULAR) + .failIfEmpty() + .replaceRanks(player, rank.getRank()) + .replaceFromTo(rank) + .replace(Variable.SECONDS, cooldownSeconds) + .replace(Variable.SECONDS_LEFT, secondsLeft) + .send(player); + return true; + } + // cooldown has expired so remove it + cooldowns.remove(player); + } + return false; + } + + private void applyCooldown(Player player) { + if (config.getInt("cooldown") > 0) { + cooldowns.put(player, System.currentTimeMillis()); + } + } + + public void rankup(Player player) { + if (!checkRankup(player)) { + return; + } + + Rank rank = plugin.getRankups().getByPlayer(player); + rank.applyRequirements(player); + applyCooldown(player); + + doRankup(player, rank); + sendRankupMessages(player, rank); + } + + public boolean checkRankup(Player player) { + return checkRankup(player, true); + } + + /** + * Checks if a player can rankup, and if they can't, sends the player a message and returns false + * + * @param player the player to check if they can rankup + * @return true if the player can rankup, false otherwise + */ + public boolean checkRankup(Player player, boolean message) { + Rankups rankups = plugin.getRankups(); + Rank rank = rankups.getByPlayer(player); + if (rankups.isLast(permissions, player)) { + Prestiges prestiges = plugin.getPrestiges(); + plugin.getMessage(prestiges == null || prestiges.isLast(permissions, player) ? Message.NO_RANKUP : Message.MUST_PRESTIGE) + .failIf(!message) + .replaceRanks(player, rankups.getLast()) + .send(player); + return false; + } else if (rank == null) { // check if in ladder + plugin.getMessage(Message.NOT_IN_LADDER) + .failIf(!message) + .replace(Variable.PLAYER, player.getName()) + .send(player); + return false; + } else if (!rank.hasRequirements(player)) { // check if they can afford it + if (message) { + plugin.replaceMoneyRequirements(plugin.getMessage(rank, Message.REQUIREMENTS_NOT_MET) + .replaceRanks(player, rank, rank.getNext()), player, rank) + .send(player); + } + return false; + } else if (message && checkCooldown(player, rank)) { + return false; + } + + return true; + } + + public void prestige(Player player) { + if (!checkPrestige(player)) { + return; + } + + Prestige prestige = plugin.getPrestiges().getByPlayer(player); + prestige.applyRequirements(player); + + applyCooldown(player); + doPrestige(player, prestige); + sendPrestigeMessages(player, prestige); + } + + public boolean checkPrestige(Player player) { + return checkPrestige(player, true); + } + + public boolean checkPrestige(Player player, boolean message) { + Prestiges prestiges = plugin.getPrestiges(); + Prestige prestige = prestiges.getByPlayer(player); + if (prestige == null || !prestige.isEligable(player)) { // check if in ladder + plugin.getMessage(Message.NOT_HIGH_ENOUGH) + .failIf(!message) + .replace(Variable.PLAYER, player.getName()) + .send(player); + return false; + } else if (prestiges + .isLast(plugin.getPermissions(), player)) { // check if they are at the highest rank + plugin.getMessage(prestige, Message.PRESTIGE_NO_PRESTIGE) + .failIf(!message) + .replaceRanks(player, prestige.getRank()) + .replaceFromTo(prestige) + .send(player); + return false; + } else if (!prestige.hasRequirements(player)) { // check if they can afford it + plugin.replaceMoneyRequirements( + plugin.getMessage(prestige, Message.PRESTIGE_REQUIREMENTS_NOT_MET) + .failIf(!message) + .replaceRanks(player, prestige, prestiges.next(prestige).getRank()), player, prestige) + .replaceFromTo(prestige) + .send(player); + return false; + } else if (checkCooldown(player, prestige)) { + return false; + } + + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/RankupPlugin.java b/src/main/java/sh/okx/rankup/RankupPlugin.java index b2c400b..800b35f 100644 --- a/src/main/java/sh/okx/rankup/RankupPlugin.java +++ b/src/main/java/sh/okx/rankup/RankupPlugin.java @@ -1,502 +1,502 @@ -package sh.okx.rankup; - -import java.io.File; -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; -import lombok.Getter; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.InventoryView; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; -import sh.okx.rankup.commands.InfoCommand; -import sh.okx.rankup.commands.MaxRankupCommand; -import sh.okx.rankup.commands.PrestigeCommand; -import sh.okx.rankup.commands.PrestigesCommand; -import sh.okx.rankup.commands.RanksCommand; -import sh.okx.rankup.commands.RankupCommand; -import sh.okx.rankup.gui.Gui; -import sh.okx.rankup.gui.GuiListener; -import sh.okx.rankup.hook.PermissionManager; -import sh.okx.rankup.hook.PermissionProvider; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.messages.MessageBuilder; -import sh.okx.rankup.messages.NullMessageBuilder; -import sh.okx.rankup.messages.Variable; -import sh.okx.rankup.placeholders.Placeholders; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.RequirementRegistry; -import sh.okx.rankup.requirements.XpLevelDeductibleRequirement; -import sh.okx.rankup.requirements.requirement.BlockBreakRequirement; -import sh.okx.rankup.requirements.requirement.CraftItemRequirement; -import sh.okx.rankup.requirements.requirement.GroupRequirement; -import sh.okx.rankup.requirements.requirement.ItemDeductibleRequirement; -import sh.okx.rankup.requirements.requirement.ItemRequirement; -import sh.okx.rankup.requirements.requirement.MobKillsRequirement; -import sh.okx.rankup.requirements.requirement.MoneyDeductibleRequirement; -import sh.okx.rankup.requirements.requirement.MoneyRequirement; -import sh.okx.rankup.requirements.requirement.PermissionRequirement; -import sh.okx.rankup.requirements.requirement.PlaceholderRequirement; -import sh.okx.rankup.requirements.requirement.PlayerKillsRequirement; -import sh.okx.rankup.requirements.requirement.PlaytimeMinutesRequirement; -import sh.okx.rankup.requirements.requirement.TokensDeductibleRequirement; -import sh.okx.rankup.requirements.requirement.TotalMobKillsRequirement; -import sh.okx.rankup.requirements.requirement.UseItemRequirement; -import sh.okx.rankup.requirements.requirement.WorldRequirement; -import sh.okx.rankup.requirements.requirement.XpLevelRequirement; -import sh.okx.rankup.requirements.requirement.advancedachievements.AdvancedAchievementsAchievementRequirement; -import sh.okx.rankup.requirements.requirement.advancedachievements.AdvancedAchievementsTotalRequirement; -import sh.okx.rankup.requirements.requirement.mcmmo.McMMOPowerLevelRequirement; -import sh.okx.rankup.requirements.requirement.mcmmo.McMMOSkillRequirement; -import sh.okx.rankup.requirements.requirement.tokenmanager.TokensRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyKingNumberResidentsRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyKingNumberTownsRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyKingRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyMayorNumberResidentsRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyMayorRequirement; -import sh.okx.rankup.requirements.requirement.towny.TownyResidentRequirement; -import sh.okx.rankup.requirements.requirement.votingplugin.VotingPluginVotesRequirement; -import sh.okx.rankup.util.UpdateNotifier; -import sh.okx.rankup.util.VersionChecker; - -public class RankupPlugin extends JavaPlugin { - - @Getter - private PermissionProvider permissions; - @Getter - private Economy economy; - /** - * The registry for listing the requirements to /rankup. - */ - @Getter - private RequirementRegistry requirements; - @Getter - private FileConfiguration messages; - @Getter - private FileConfiguration config; - @Getter - private Rankups rankups; - @Getter - private Prestiges prestiges; - @Getter - private Placeholders placeholders; - @Getter - private RankupHelper helper; - private AutoRankup autoRankup; - private String errorMessage; - private UpdateNotifier notifier; - - @Override - public void onEnable() { - notifier = new UpdateNotifier(new VersionChecker(this)); - - reload(true); - - Metrics metrics = new Metrics(this); - metrics.addCustomChart(new Metrics.SimplePie("confirmation", - () -> config.getString("confirmation-type", "unknown"))); - metrics.addCustomChart(new Metrics.AdvancedPie("requirements", () -> { - Map map = new HashMap<>(); - addAll(map, rankups); - if (prestiges != null) { - addAll(map, prestiges); - } - return map; - })); - metrics.addCustomChart(new Metrics.SimplePie("prestige", - () -> config.getBoolean("prestige") ? "enabled" : "disabled")); - - if (config.getBoolean("ranks")) { - getCommand("ranks").setExecutor(new RanksCommand(this)); - } - if (config.getBoolean("prestige")) { - getCommand("prestige").setExecutor(new PrestigeCommand(this)); - if (config.getBoolean("prestiges")) { - getCommand("prestiges").setExecutor(new PrestigesCommand(this)); - } - } - if (config.getBoolean("max-rankup.enabled")) { - getCommand("maxrankup").setExecutor(new MaxRankupCommand(this)); - } - - getCommand("rankup").setExecutor(new RankupCommand(this)); - getCommand("rankup3").setExecutor(new InfoCommand(this, notifier)); - getServer().getPluginManager().registerEvents(new GuiListener(this), this); - getServer().getPluginManager().registerEvents( - new JoinUpdateNotifier(notifier, () -> getConfig().getBoolean("notify-update"), "rankup.notify"), this); - - placeholders = new Placeholders(this); - placeholders.register(); - } - - - @Override - public void onDisable() { - closeInventories(); - if (placeholders != null) { - placeholders.unregister(); - } - } - - public void reload(boolean init) { - errorMessage = null; - - PermissionManager permissionManager = new PermissionManager(this); - - permissions = permissionManager.findPermissionProvider(); - if (permissions == null) { - errorMessage = "No permission plugin found"; - } - setupEconomy(); - - closeInventories(); - loadConfigs(init); - - if (autoRankup != null) { - autoRankup.cancel(); - } - long time = config.getInt("autorankup-interval") * 60 * 20; - if (time > 0) { - autoRankup = new AutoRankup(this); - autoRankup.runTaskTimer(this, time, time); - } - - if (config.getInt("version") < 6) { - getLogger().severe("You are using an outdated config!"); - getLogger().severe("This means that some things might not work!"); - getLogger().severe("To update, please rename ALL your config files (or the folder they are in),"); - getLogger().severe("and run /pru reload to generate a new config file."); - getLogger().severe("If that does not work, restart your server."); - getLogger().severe("You may then copy in your config values manually from the old config."); - getLogger().severe("Check the changelog on the Rankup spigot page to see the changes."); - getLogger().severe("https://www.spigotmc.org/resources/rankup.17933/updates"); - } - - helper = new RankupHelper(this); - } - - public boolean error() { - return error(null); - } - - /** - * Notify the player of an error if there is one - * - * @return true if there was an error and action was taken - */ - public boolean error(CommandSender sender) { - if (errorMessage == null) { - return false; - } - - if (sender instanceof Player) { - sender.sendMessage( - ChatColor.RED + "Could not load Rankup, check console for more information."); - } else { - getLogger().severe("Failed to load Rankup"); - } - for (String line : errorMessage.split("\n")) { - getLogger().severe(line); - } - getLogger().severe("More information can be found in the console log at startup"); - return true; - } - - private void addAll(Map map, RankList ranks) { - for (Rank rank : ranks.ranks) { - for (Requirement requirement : rank.getRequirements().getRequirements(null)) { - String name = requirement.getName(); - map.put(name, map.getOrDefault(name, 0) + 1); - } - } - } - - /** - * Closes all rankup inventories on disable so players cannot grab items from the inventory on a - * plugin reload. - */ - private void closeInventories() { - for (Player player : Bukkit.getOnlinePlayers()) { - InventoryView view = player.getOpenInventory(); - if (view.getType() == InventoryType.CHEST - && view.getTopInventory().getHolder() instanceof Gui) { - player.closeInventory(); - } - } - } - - private void loadConfigs(boolean init) { - saveLocales(); - - config = loadConfig("config.yml"); - String locale = config.getString("locale", "en"); - File localeFile = new File(new File(getDataFolder(), "locale"), locale + ".yml"); - messages = YamlConfiguration.loadConfiguration(localeFile); - - if (init) { - Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { - refreshRanks(); - error(); - }); - } else { - refreshRanks(); - } - } - - public void refreshRanks() { - try { - registerRequirements(); - Bukkit.getPluginManager().callEvent(new RankupRegisterEvent(this)); - - if (config.getBoolean("prestige")) { - prestiges = new Prestiges(this, loadConfig("prestiges.yml")); -// prestiges.getOrderedList(); - } else { - prestiges = null; - } - - rankups = new Rankups(this, loadConfig("rankups.yml")); - // check rankups are not in an infinite loop -// rankups.getOrderedList(); - - - - } catch (Exception e) { - this.errorMessage = e.getClass().getName() + ": " + e.getMessage(); - e.printStackTrace(); - } - } - - private void saveLocales() { - saveLocale("en"); - saveLocale("pt_br"); - saveLocale("ru"); - saveLocale("zh_cn"); - saveLocale("fr"); - } - - private void saveLocale(String locale) { - String name = "locale/" + locale + ".yml"; - File file = new File(getDataFolder(), name); - if (!file.exists()) { - saveResource(name, false); - } - } - - private FileConfiguration loadConfig(String name) { - File file = new File(getDataFolder(), name); - if (!file.exists()) { - saveResource(name, false); - } - return YamlConfiguration.loadConfiguration(file); - } - - private void registerRequirements() { - requirements = new RequirementRegistry(); - requirements.addRequirements( - new XpLevelRequirement(this, "xp-levelh"), - new XpLevelDeductibleRequirement(this, "xp-level"), - new PlaytimeMinutesRequirement(this), - new GroupRequirement(this), - new PermissionRequirement(this), - new PlaceholderRequirement(this), - new WorldRequirement(this), - new BlockBreakRequirement(this), - new PlayerKillsRequirement(this), - new MobKillsRequirement(this), - new ItemRequirement(this, "itemh"), - new ItemDeductibleRequirement(this, "item"), - new UseItemRequirement(this), - new TotalMobKillsRequirement(this), - new CraftItemRequirement(this)); - if (economy != null) { - requirements.addRequirements( - new MoneyRequirement(this, "moneyh"), - new MoneyDeductibleRequirement(this, "money")); - } - - PluginManager pluginManager = Bukkit.getPluginManager(); - if (pluginManager.isPluginEnabled("mcMMO")) { - requirements.addRequirements( - new McMMOSkillRequirement(this), - new McMMOPowerLevelRequirement(this)); - } - if (pluginManager.isPluginEnabled("AdvancedAchievements")) { - requirements.addRequirements( - new AdvancedAchievementsAchievementRequirement(this), - new AdvancedAchievementsTotalRequirement(this)); - } - if (pluginManager.isPluginEnabled("VotingPlugin")) { - requirements.addRequirements( - new VotingPluginVotesRequirement(this)); - } - if (Bukkit.getPluginManager().isPluginEnabled("Towny")) { - requirements.addRequirements( - new TownyResidentRequirement(this), - new TownyMayorRequirement(this), - new TownyMayorNumberResidentsRequirement(this), - new TownyKingRequirement(this), - new TownyKingNumberResidentsRequirement(this), - new TownyKingNumberTownsRequirement(this)); - } - if (Bukkit.getPluginManager().isPluginEnabled("TokenManager")) { - requirements.addRequirements( - new TokensRequirement(this, "tokenmanager-tokensh"), - new TokensDeductibleRequirement(this, "tokenmanager-tokens")); - } - } - private void setupEconomy() { - RegisteredServiceProvider rsp = getServer().getServicesManager() - .getRegistration(Economy.class); - if (rsp != null) { - economy = rsp.getProvider(); - } else { - getLogger().warning("No economy found. The 'money' requirement will be disabled."); - } - } - - public String formatMoney(double money) { - List shortened = config.getStringList("shorten"); - String suffix = ""; - - for (int i = shortened.size(); i > 0; i--) { - double value = Math.pow(10, 3 * i); - if (money >= value) { - money /= value; - suffix = shortened.get(i - 1); - break; - } - } - - return placeholders.getMoneyFormat().format(money) + suffix; - } - - public ConfigurationSection getSection(Rank rank, String path) { - ConfigurationSection rankSection = rank.getSection(); - if (rankSection == null || !rankSection.isConfigurationSection(path)) { - return this.messages.getConfigurationSection(path); - } - return rankSection.getConfigurationSection(path); - } - - public MessageBuilder getMessage(Rank rank, Message message) { - ConfigurationSection messages = rank.getSection(); - if (messages == null || !messages.isSet(message.getName())) { - messages = this.messages; - } - return MessageBuilder.of(messages, message); - } - - public MessageBuilder getMessage(Message message) { - return MessageBuilder.of(messages, message); - } - - public MessageBuilder replaceMoneyRequirements(MessageBuilder builder, CommandSender sender, - Rank rank) { - if (builder instanceof NullMessageBuilder) { - return builder; - } - - Requirement money = rank.getRequirement(sender instanceof Player ? (Player) sender : null, "money"); - if (money != null) { - Double amount = null; - if (sender instanceof Player && rank.isIn((Player) sender)) { - if (economy != null) { - amount = money.getRemaining((Player) sender); - } - } else { - amount = money.getValueDouble(); - } - if (amount != null && economy != null) { - builder.replace(Variable.MONEY_NEEDED, formatMoney(amount)); - builder.replace(Variable.MONEY, formatMoney(money.getValueDouble())); - } - } - if (sender instanceof Player) { - replaceRequirements(builder, (Player) sender, rank); - } - return builder; - } - - public MessageBuilder replaceRequirements(MessageBuilder builder, Player player, Rank rank) { - DecimalFormat simpleFormat = placeholders.getSimpleFormat(); - DecimalFormat percentFormat = placeholders.getPercentFormat(); - for (Requirement requirement : rank.getRequirements().getRequirements(player)) { - try { - replaceRequirements(builder, Variable.AMOUNT, requirement, - () -> simpleFormat.format(requirement.getTotal(player))); - if (rank.isIn(player)) { - replaceRequirements(builder, Variable.AMOUNT_NEEDED, requirement, - () -> simpleFormat.format(requirement.getRemaining(player))); - replaceRequirements(builder, Variable.PERCENT_LEFT, requirement, - () -> percentFormat.format(Math.max(0, - (requirement.getRemaining(player) / requirement.getTotal(player)) * 100))); - replaceRequirements(builder, Variable.PERCENT_DONE, requirement, - () -> percentFormat.format(Math.min(100, - (1 - (requirement.getRemaining(player) / requirement.getTotal(player))) * 100))); - replaceRequirements(builder, Variable.AMOUNT_DONE, requirement, - () -> simpleFormat - .format(requirement.getTotal(player) - requirement.getRemaining(player))); - } - } catch (NumberFormatException ignored) { - } - } - return builder; - } - - private void replaceRequirements(MessageBuilder builder, Variable variable, - Requirement requirement, Supplier value) { - Object get; - try { - get = value.get(); - builder.replace(variable + " " + requirement.getFullName(), value.get()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public MessageBuilder getMessage(CommandSender player, Message message, Rank oldRank, - String rankName) { - String oldRankName; - if (oldRank instanceof Prestige && oldRank.getRank() == null) { - oldRankName = ((Prestige) oldRank).getFrom(); - } else { - oldRankName = oldRank.getRank(); - } - - return replaceMoneyRequirements(getMessage(oldRank, message) - .replaceRanks(player, rankName) - .replace(Variable.OLD_RANK, oldRankName), player, oldRank) - .replaceFromTo(oldRank); - } - - public void sendHeaderFooter(CommandSender sender, Rank rank, Message type) { - MessageBuilder builder; - if (rank == null) { - builder = getMessage(type) - .failIfEmpty() - .replace(Variable.PLAYER, sender.getName()); - } else { - builder = getMessage(rank, type) - .failIfEmpty() - .replaceRanks(sender, rank.getRank()) - .replaceFromTo(rank); - } - builder.send(sender); - } -} +package sh.okx.rankup; + +import java.io.File; +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import lombok.Getter; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.InventoryView; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import sh.okx.rankup.commands.InfoCommand; +import sh.okx.rankup.commands.MaxRankupCommand; +import sh.okx.rankup.commands.PrestigeCommand; +import sh.okx.rankup.commands.PrestigesCommand; +import sh.okx.rankup.commands.RanksCommand; +import sh.okx.rankup.commands.RankupCommand; +import sh.okx.rankup.gui.Gui; +import sh.okx.rankup.gui.GuiListener; +import sh.okx.rankup.hook.PermissionManager; +import sh.okx.rankup.hook.PermissionProvider; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.messages.MessageBuilder; +import sh.okx.rankup.messages.NullMessageBuilder; +import sh.okx.rankup.messages.Variable; +import sh.okx.rankup.placeholders.Placeholders; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.RequirementRegistry; +import sh.okx.rankup.requirements.XpLevelDeductibleRequirement; +import sh.okx.rankup.requirements.requirement.BlockBreakRequirement; +import sh.okx.rankup.requirements.requirement.CraftItemRequirement; +import sh.okx.rankup.requirements.requirement.GroupRequirement; +import sh.okx.rankup.requirements.requirement.ItemDeductibleRequirement; +import sh.okx.rankup.requirements.requirement.ItemRequirement; +import sh.okx.rankup.requirements.requirement.MobKillsRequirement; +import sh.okx.rankup.requirements.requirement.MoneyDeductibleRequirement; +import sh.okx.rankup.requirements.requirement.MoneyRequirement; +import sh.okx.rankup.requirements.requirement.PermissionRequirement; +import sh.okx.rankup.requirements.requirement.PlaceholderRequirement; +import sh.okx.rankup.requirements.requirement.PlayerKillsRequirement; +import sh.okx.rankup.requirements.requirement.PlaytimeMinutesRequirement; +import sh.okx.rankup.requirements.requirement.TokensDeductibleRequirement; +import sh.okx.rankup.requirements.requirement.TotalMobKillsRequirement; +import sh.okx.rankup.requirements.requirement.UseItemRequirement; +import sh.okx.rankup.requirements.requirement.WorldRequirement; +import sh.okx.rankup.requirements.requirement.XpLevelRequirement; +import sh.okx.rankup.requirements.requirement.advancedachievements.AdvancedAchievementsAchievementRequirement; +import sh.okx.rankup.requirements.requirement.advancedachievements.AdvancedAchievementsTotalRequirement; +import sh.okx.rankup.requirements.requirement.mcmmo.McMMOPowerLevelRequirement; +import sh.okx.rankup.requirements.requirement.mcmmo.McMMOSkillRequirement; +import sh.okx.rankup.requirements.requirement.tokenmanager.TokensRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyKingNumberResidentsRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyKingNumberTownsRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyKingRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyMayorNumberResidentsRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyMayorRequirement; +import sh.okx.rankup.requirements.requirement.towny.TownyResidentRequirement; +import sh.okx.rankup.requirements.requirement.votingplugin.VotingPluginVotesRequirement; +import sh.okx.rankup.util.UpdateNotifier; +import sh.okx.rankup.util.VersionChecker; + +public class RankupPlugin extends JavaPlugin { + + @Getter + private PermissionProvider permissions; + @Getter + private Economy economy; + /** + * The registry for listing the requirements to /rankup. + */ + @Getter + private RequirementRegistry requirements; + @Getter + private FileConfiguration messages; + @Getter + private FileConfiguration config; + @Getter + private Rankups rankups; + @Getter + private Prestiges prestiges; + @Getter + private Placeholders placeholders; + @Getter + private RankupHelper helper; + private AutoRankup autoRankup; + private String errorMessage; + private UpdateNotifier notifier; + + @Override + public void onEnable() { + notifier = new UpdateNotifier(new VersionChecker(this)); + + reload(true); + + Metrics metrics = new Metrics(this); + metrics.addCustomChart(new Metrics.SimplePie("confirmation", + () -> config.getString("confirmation-type", "unknown"))); + metrics.addCustomChart(new Metrics.AdvancedPie("requirements", () -> { + Map map = new HashMap<>(); + addAll(map, rankups); + if (prestiges != null) { + addAll(map, prestiges); + } + return map; + })); + metrics.addCustomChart(new Metrics.SimplePie("prestige", + () -> config.getBoolean("prestige") ? "enabled" : "disabled")); + + if (config.getBoolean("ranks")) { + getCommand("ranks").setExecutor(new RanksCommand(this)); + } + if (config.getBoolean("prestige")) { + getCommand("prestige").setExecutor(new PrestigeCommand(this)); + if (config.getBoolean("prestiges")) { + getCommand("prestiges").setExecutor(new PrestigesCommand(this)); + } + } + if (config.getBoolean("max-rankup.enabled")) { + getCommand("maxrankup").setExecutor(new MaxRankupCommand(this)); + } + + getCommand("rankup").setExecutor(new RankupCommand(this)); + getCommand("rankup3").setExecutor(new InfoCommand(this, notifier)); + getServer().getPluginManager().registerEvents(new GuiListener(this), this); + getServer().getPluginManager().registerEvents( + new JoinUpdateNotifier(notifier, () -> getConfig().getBoolean("notify-update"), "rankup.notify"), this); + + placeholders = new Placeholders(this); + placeholders.register(); + } + + + @Override + public void onDisable() { + closeInventories(); + if (placeholders != null) { + placeholders.unregister(); + } + } + + public void reload(boolean init) { + errorMessage = null; + + PermissionManager permissionManager = new PermissionManager(this); + + permissions = permissionManager.findPermissionProvider(); + if (permissions == null) { + errorMessage = "No permission plugin found"; + } + setupEconomy(); + + closeInventories(); + loadConfigs(init); + + if (autoRankup != null) { + autoRankup.cancel(); + } + long time = config.getInt("autorankup-interval") * 60 * 20; + if (time > 0) { + autoRankup = new AutoRankup(this); + autoRankup.runTaskTimer(this, time, time); + } + + if (config.getInt("version") < 6) { + getLogger().severe("You are using an outdated config!"); + getLogger().severe("This means that some things might not work!"); + getLogger().severe("To update, please rename ALL your config files (or the folder they are in),"); + getLogger().severe("and run /pru reload to generate a new config file."); + getLogger().severe("If that does not work, restart your server."); + getLogger().severe("You may then copy in your config values manually from the old config."); + getLogger().severe("Check the changelog on the Rankup spigot page to see the changes."); + getLogger().severe("https://www.spigotmc.org/resources/rankup.17933/updates"); + } + + helper = new RankupHelper(this); + } + + public boolean error() { + return error(null); + } + + /** + * Notify the player of an error if there is one + * + * @return true if there was an error and action was taken + */ + public boolean error(CommandSender sender) { + if (errorMessage == null) { + return false; + } + + if (sender instanceof Player) { + sender.sendMessage( + ChatColor.RED + "Could not load Rankup, check console for more information."); + } else { + getLogger().severe("Failed to load Rankup"); + } + for (String line : errorMessage.split("\n")) { + getLogger().severe(line); + } + getLogger().severe("More information can be found in the console log at startup"); + return true; + } + + private void addAll(Map map, RankList ranks) { + for (Rank rank : ranks.ranks) { + for (Requirement requirement : rank.getRequirements().getRequirements(null)) { + String name = requirement.getName(); + map.put(name, map.getOrDefault(name, 0) + 1); + } + } + } + + /** + * Closes all rankup inventories on disable so players cannot grab items from the inventory on a + * plugin reload. + */ + private void closeInventories() { + for (Player player : Bukkit.getOnlinePlayers()) { + InventoryView view = player.getOpenInventory(); + if (view.getType() == InventoryType.CHEST + && view.getTopInventory().getHolder() instanceof Gui) { + player.closeInventory(); + } + } + } + + private void loadConfigs(boolean init) { + saveLocales(); + + config = loadConfig("config.yml"); + String locale = config.getString("locale", "en"); + File localeFile = new File(new File(getDataFolder(), "locale"), locale + ".yml"); + messages = YamlConfiguration.loadConfiguration(localeFile); + + if (init) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { + refreshRanks(); + error(); + }); + } else { + refreshRanks(); + } + } + + public void refreshRanks() { + try { + registerRequirements(); + Bukkit.getPluginManager().callEvent(new RankupRegisterEvent(this)); + + if (config.getBoolean("prestige")) { + prestiges = new Prestiges(this, loadConfig("prestiges.yml")); +// prestiges.getOrderedList(); + } else { + prestiges = null; + } + + rankups = new Rankups(this, loadConfig("rankups.yml")); + // check rankups are not in an infinite loop +// rankups.getOrderedList(); + + + + } catch (Exception e) { + this.errorMessage = e.getClass().getName() + ": " + e.getMessage(); + e.printStackTrace(); + } + } + + private void saveLocales() { + saveLocale("en"); + saveLocale("pt_br"); + saveLocale("ru"); + saveLocale("zh_cn"); + saveLocale("fr"); + } + + private void saveLocale(String locale) { + String name = "locale/" + locale + ".yml"; + File file = new File(getDataFolder(), name); + if (!file.exists()) { + saveResource(name, false); + } + } + + private FileConfiguration loadConfig(String name) { + File file = new File(getDataFolder(), name); + if (!file.exists()) { + saveResource(name, false); + } + return YamlConfiguration.loadConfiguration(file); + } + + private void registerRequirements() { + requirements = new RequirementRegistry(); + requirements.addRequirements( + new XpLevelRequirement(this, "xp-levelh"), + new XpLevelDeductibleRequirement(this, "xp-level"), + new PlaytimeMinutesRequirement(this), + new GroupRequirement(this), + new PermissionRequirement(this), + new PlaceholderRequirement(this), + new WorldRequirement(this), + new BlockBreakRequirement(this), + new PlayerKillsRequirement(this), + new MobKillsRequirement(this), + new ItemRequirement(this, "itemh"), + new ItemDeductibleRequirement(this, "item"), + new UseItemRequirement(this), + new TotalMobKillsRequirement(this), + new CraftItemRequirement(this)); + if (economy != null) { + requirements.addRequirements( + new MoneyRequirement(this, "moneyh"), + new MoneyDeductibleRequirement(this, "money")); + } + + PluginManager pluginManager = Bukkit.getPluginManager(); + if (pluginManager.isPluginEnabled("mcMMO")) { + requirements.addRequirements( + new McMMOSkillRequirement(this), + new McMMOPowerLevelRequirement(this)); + } + if (pluginManager.isPluginEnabled("AdvancedAchievements")) { + requirements.addRequirements( + new AdvancedAchievementsAchievementRequirement(this), + new AdvancedAchievementsTotalRequirement(this)); + } + if (pluginManager.isPluginEnabled("VotingPlugin")) { + requirements.addRequirements( + new VotingPluginVotesRequirement(this)); + } + if (Bukkit.getPluginManager().isPluginEnabled("Towny")) { + requirements.addRequirements( + new TownyResidentRequirement(this), + new TownyMayorRequirement(this), + new TownyMayorNumberResidentsRequirement(this), + new TownyKingRequirement(this), + new TownyKingNumberResidentsRequirement(this), + new TownyKingNumberTownsRequirement(this)); + } + if (Bukkit.getPluginManager().isPluginEnabled("TokenManager")) { + requirements.addRequirements( + new TokensRequirement(this, "tokenmanager-tokensh"), + new TokensDeductibleRequirement(this, "tokenmanager-tokens")); + } + } + private void setupEconomy() { + RegisteredServiceProvider rsp = getServer().getServicesManager() + .getRegistration(Economy.class); + if (rsp != null) { + economy = rsp.getProvider(); + } else { + getLogger().warning("No economy found. The 'money' requirement will be disabled."); + } + } + + public String formatMoney(double money) { + List shortened = config.getStringList("shorten"); + String suffix = ""; + + for (int i = shortened.size(); i > 0; i--) { + double value = Math.pow(10, 3 * i); + if (money >= value) { + money /= value; + suffix = shortened.get(i - 1); + break; + } + } + + return placeholders.getMoneyFormat().format(money) + suffix; + } + + public ConfigurationSection getSection(Rank rank, String path) { + ConfigurationSection rankSection = rank.getSection(); + if (rankSection == null || !rankSection.isConfigurationSection(path)) { + return this.messages.getConfigurationSection(path); + } + return rankSection.getConfigurationSection(path); + } + + public MessageBuilder getMessage(Rank rank, Message message) { + ConfigurationSection messages = rank.getSection(); + if (messages == null || !messages.isSet(message.getName())) { + messages = this.messages; + } + return MessageBuilder.of(messages, message); + } + + public MessageBuilder getMessage(Message message) { + return MessageBuilder.of(messages, message); + } + + public MessageBuilder replaceMoneyRequirements(MessageBuilder builder, CommandSender sender, + Rank rank) { + if (builder instanceof NullMessageBuilder) { + return builder; + } + + Requirement money = rank.getRequirement(sender instanceof Player ? (Player) sender : null, "money"); + if (money != null) { + Double amount = null; + if (sender instanceof Player && rank.isIn((Player) sender)) { + if (economy != null) { + amount = money.getRemaining((Player) sender); + } + } else { + amount = money.getValueDouble(); + } + if (amount != null && economy != null) { + builder.replace(Variable.MONEY_NEEDED, formatMoney(amount)); + builder.replace(Variable.MONEY, formatMoney(money.getValueDouble())); + } + } + if (sender instanceof Player) { + replaceRequirements(builder, (Player) sender, rank); + } + return builder; + } + + public MessageBuilder replaceRequirements(MessageBuilder builder, Player player, Rank rank) { + DecimalFormat simpleFormat = placeholders.getSimpleFormat(); + DecimalFormat percentFormat = placeholders.getPercentFormat(); + for (Requirement requirement : rank.getRequirements().getRequirements(player)) { + try { + replaceRequirements(builder, Variable.AMOUNT, requirement, + () -> simpleFormat.format(requirement.getTotal(player))); + if (rank.isIn(player)) { + replaceRequirements(builder, Variable.AMOUNT_NEEDED, requirement, + () -> simpleFormat.format(requirement.getRemaining(player))); + replaceRequirements(builder, Variable.PERCENT_LEFT, requirement, + () -> percentFormat.format(Math.max(0, + (requirement.getRemaining(player) / requirement.getTotal(player)) * 100))); + replaceRequirements(builder, Variable.PERCENT_DONE, requirement, + () -> percentFormat.format(Math.min(100, + (1 - (requirement.getRemaining(player) / requirement.getTotal(player))) * 100))); + replaceRequirements(builder, Variable.AMOUNT_DONE, requirement, + () -> simpleFormat + .format(requirement.getTotal(player) - requirement.getRemaining(player))); + } + } catch (NumberFormatException ignored) { + } + } + return builder; + } + + private void replaceRequirements(MessageBuilder builder, Variable variable, + Requirement requirement, Supplier value) { + Object get; + try { + get = value.get(); + builder.replace(variable + " " + requirement.getFullName(), value.get()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public MessageBuilder getMessage(CommandSender player, Message message, Rank oldRank, + String rankName) { + String oldRankName; + if (oldRank instanceof Prestige && oldRank.getRank() == null) { + oldRankName = ((Prestige) oldRank).getFrom(); + } else { + oldRankName = oldRank.getRank(); + } + + return replaceMoneyRequirements(getMessage(oldRank, message) + .replaceRanks(player, rankName) + .replace(Variable.OLD_RANK, oldRankName), player, oldRank) + .replaceFromTo(oldRank); + } + + public void sendHeaderFooter(CommandSender sender, Rank rank, Message type) { + MessageBuilder builder; + if (rank == null) { + builder = getMessage(type) + .failIfEmpty() + .replace(Variable.PLAYER, sender.getName()); + } else { + builder = getMessage(rank, type) + .failIfEmpty() + .replaceRanks(sender, rank.getRank()) + .replaceFromTo(rank); + } + builder.send(sender); + } +} diff --git a/src/main/java/sh/okx/rankup/RankupRegisterEvent.java b/src/main/java/sh/okx/rankup/RankupRegisterEvent.java index 383b616..fb8be5c 100644 --- a/src/main/java/sh/okx/rankup/RankupRegisterEvent.java +++ b/src/main/java/sh/okx/rankup/RankupRegisterEvent.java @@ -1,38 +1,38 @@ -package sh.okx.rankup; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.RequirementRegistry; - -/** - * Called immediately before rankups and prestiges are registered, - * and immediately after the built-in requirements are registered. - * This is used to register custom requirements. - * This is called when the plugin is enabled, and when it is reloaded from a command. - */ -@RequiredArgsConstructor -public class RankupRegisterEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - @Getter - private final RankupPlugin plugin; - - public static HandlerList getHandlerList() { - return handlers; - } - - public RequirementRegistry getRequirementRegistry() { - return plugin.getRequirements(); - } - - public void addRequirement(Requirement requirement) { - plugin.getRequirements().addRequirement(requirement); - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package sh.okx.rankup; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.RequirementRegistry; + +/** + * Called immediately before rankups and prestiges are registered, + * and immediately after the built-in requirements are registered. + * This is used to register custom requirements. + * This is called when the plugin is enabled, and when it is reloaded from a command. + */ +@RequiredArgsConstructor +public class RankupRegisterEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + @Getter + private final RankupPlugin plugin; + + public static HandlerList getHandlerList() { + return handlers; + } + + public RequirementRegistry getRequirementRegistry() { + return plugin.getRequirements(); + } + + public void addRequirement(Requirement requirement) { + plugin.getRequirements().addRequirement(requirement); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/InfoCommand.java b/src/main/java/sh/okx/rankup/commands/InfoCommand.java index a9e47c0..5a1f7f7 100644 --- a/src/main/java/sh/okx/rankup/commands/InfoCommand.java +++ b/src/main/java/sh/okx/rankup/commands/InfoCommand.java @@ -1,130 +1,130 @@ -package sh.okx.rankup.commands; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.plugin.PluginDescriptionFile; -import sh.okx.rankup.RankupPlugin; - -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; -import sh.okx.rankup.util.UpdateNotifier; - -public class InfoCommand implements CommandExecutor { - private final RankupPlugin plugin; - - private final UpdateNotifier notifier; - - public InfoCommand(RankupPlugin plugin, UpdateNotifier notifier) { - this.plugin = plugin; - this.notifier = notifier; - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (args.length > 0) { - if (args[0].equalsIgnoreCase("reload") && sender.hasPermission("rankup.reload")) { - plugin.reload(false); - if (!plugin.error(sender)) { - sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "Rankup " + ChatColor.YELLOW + "Reloaded configuration files."); - } - return true; - } else if (args[0].equalsIgnoreCase("forcerankup") && sender.hasPermission("rankup.force")) { - if (args.length < 2) { - sender.sendMessage(ChatColor.YELLOW + "Usage: /" + label + " forcerankup "); - return true; - } - - Player player = Bukkit.getPlayer(args[1]); - if (player == null) { - sender.sendMessage(ChatColor.YELLOW + "Player not found."); - return true; - } - - Rankups rankups = plugin.getRankups(); - if (rankups.isLast(plugin.getPermissions(), player)) { - sender.sendMessage(ChatColor.YELLOW + "That player is at the last rank."); - return true; - } - - Rank rank = rankups.getByPlayer(player); - if (rank == null) { - sender.sendMessage(ChatColor.YELLOW + "That player is not in any rankup groups."); - return true; - } - - plugin.getHelper().doRankup(player, rank); - plugin.getHelper().sendRankupMessages(player, rank); - sender.sendMessage(ChatColor.GREEN + "Successfully forced " - + ChatColor.GOLD + player.getName() - + ChatColor.GREEN + " to rankup from " + ChatColor.GOLD + rank.getRank() - + ChatColor.GREEN + " to " + ChatColor.GOLD + rank.getNext()); - return true; - } else if (args[0].equalsIgnoreCase("forceprestige") && sender.hasPermission("rankup.force")) { - if (plugin.getPrestiges() == null) { - sender.sendMessage(ChatColor.RED + "Prestige is disabled."); - return true; - } - - if (args.length < 2) { - sender.sendMessage(ChatColor.YELLOW + "Usage: /" + label + " forceprestige "); - return true; - } - - Player player = Bukkit.getPlayer(args[1]); - if (player == null) { - sender.sendMessage(ChatColor.YELLOW + "Player not found."); - return true; - } - - Prestiges prestiges = plugin.getPrestiges(); - if (prestiges.isLast(plugin.getPermissions(), player)) { - sender.sendMessage(ChatColor.YELLOW + "That player is at the last prestige."); - return true; - } - - Prestige prestige = prestiges.getByPlayer(player); - if (prestige == null) { - sender.sendMessage(ChatColor.YELLOW + "That player is not in any prestige groups."); - return true; - } - - plugin.getHelper().doPrestige(player, prestige); - plugin.getHelper().sendPrestigeMessages(player, prestige); - sender.sendMessage(ChatColor.GREEN + "Successfully forced " - + ChatColor.GOLD + player.getName() - + ChatColor.GREEN + " to prestige " - + ChatColor.GOLD + prestige.getRank() - + ChatColor.GREEN + " from " + ChatColor.GOLD + prestige.getFrom() - + ChatColor.GREEN + " to " + ChatColor.GOLD + prestige.getTo()); - return true; - } - } - - PluginDescriptionFile description = plugin.getDescription(); - String version = description.getVersion(); - sender.sendMessage( - ChatColor.GREEN + "" + ChatColor.BOLD + description.getName() + " " + version + - ChatColor.YELLOW + " by " + ChatColor.BLUE + ChatColor.BOLD + String.join(", ", description.getAuthors())); - if (sender.hasPermission("rankup.reload")) { - sender.sendMessage(ChatColor.GREEN + "/" + label + " reload " + ChatColor.YELLOW + "Reloads configuration files."); - sender.sendMessage(ChatColor.GREEN + "/" + label + " forcerankup " + ChatColor.YELLOW + "Force a player to rankup, bypassing requirements."); - if (plugin.getPrestiges() != null) { - sender.sendMessage( - ChatColor.GREEN + "/" + label + " forceprestige " + ChatColor.YELLOW - + "Force a player to prestige, bypassing requirements."); - } - } - - if (sender.hasPermission("rankup.checkversion")) { - notifier.notify(sender, false); - } - - return true; - } -} +package sh.okx.rankup.commands; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginDescriptionFile; +import sh.okx.rankup.RankupPlugin; + +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; +import sh.okx.rankup.util.UpdateNotifier; + +public class InfoCommand implements CommandExecutor { + private final RankupPlugin plugin; + + private final UpdateNotifier notifier; + + public InfoCommand(RankupPlugin plugin, UpdateNotifier notifier) { + this.plugin = plugin; + this.notifier = notifier; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (args.length > 0) { + if (args[0].equalsIgnoreCase("reload") && sender.hasPermission("rankup.reload")) { + plugin.reload(false); + if (!plugin.error(sender)) { + sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "Rankup " + ChatColor.YELLOW + "Reloaded configuration files."); + } + return true; + } else if (args[0].equalsIgnoreCase("forcerankup") && sender.hasPermission("rankup.force")) { + if (args.length < 2) { + sender.sendMessage(ChatColor.YELLOW + "Usage: /" + label + " forcerankup "); + return true; + } + + Player player = Bukkit.getPlayer(args[1]); + if (player == null) { + sender.sendMessage(ChatColor.YELLOW + "Player not found."); + return true; + } + + Rankups rankups = plugin.getRankups(); + if (rankups.isLast(plugin.getPermissions(), player)) { + sender.sendMessage(ChatColor.YELLOW + "That player is at the last rank."); + return true; + } + + Rank rank = rankups.getByPlayer(player); + if (rank == null) { + sender.sendMessage(ChatColor.YELLOW + "That player is not in any rankup groups."); + return true; + } + + plugin.getHelper().doRankup(player, rank); + plugin.getHelper().sendRankupMessages(player, rank); + sender.sendMessage(ChatColor.GREEN + "Successfully forced " + + ChatColor.GOLD + player.getName() + + ChatColor.GREEN + " to rankup from " + ChatColor.GOLD + rank.getRank() + + ChatColor.GREEN + " to " + ChatColor.GOLD + rank.getNext()); + return true; + } else if (args[0].equalsIgnoreCase("forceprestige") && sender.hasPermission("rankup.force")) { + if (plugin.getPrestiges() == null) { + sender.sendMessage(ChatColor.RED + "Prestige is disabled."); + return true; + } + + if (args.length < 2) { + sender.sendMessage(ChatColor.YELLOW + "Usage: /" + label + " forceprestige "); + return true; + } + + Player player = Bukkit.getPlayer(args[1]); + if (player == null) { + sender.sendMessage(ChatColor.YELLOW + "Player not found."); + return true; + } + + Prestiges prestiges = plugin.getPrestiges(); + if (prestiges.isLast(plugin.getPermissions(), player)) { + sender.sendMessage(ChatColor.YELLOW + "That player is at the last prestige."); + return true; + } + + Prestige prestige = prestiges.getByPlayer(player); + if (prestige == null) { + sender.sendMessage(ChatColor.YELLOW + "That player is not in any prestige groups."); + return true; + } + + plugin.getHelper().doPrestige(player, prestige); + plugin.getHelper().sendPrestigeMessages(player, prestige); + sender.sendMessage(ChatColor.GREEN + "Successfully forced " + + ChatColor.GOLD + player.getName() + + ChatColor.GREEN + " to prestige " + + ChatColor.GOLD + prestige.getRank() + + ChatColor.GREEN + " from " + ChatColor.GOLD + prestige.getFrom() + + ChatColor.GREEN + " to " + ChatColor.GOLD + prestige.getTo()); + return true; + } + } + + PluginDescriptionFile description = plugin.getDescription(); + String version = description.getVersion(); + sender.sendMessage( + ChatColor.GREEN + "" + ChatColor.BOLD + description.getName() + " " + version + + ChatColor.YELLOW + " by " + ChatColor.BLUE + ChatColor.BOLD + String.join(", ", description.getAuthors())); + if (sender.hasPermission("rankup.reload")) { + sender.sendMessage(ChatColor.GREEN + "/" + label + " reload " + ChatColor.YELLOW + "Reloads configuration files."); + sender.sendMessage(ChatColor.GREEN + "/" + label + " forcerankup " + ChatColor.YELLOW + "Force a player to rankup, bypassing requirements."); + if (plugin.getPrestiges() != null) { + sender.sendMessage( + ChatColor.GREEN + "/" + label + " forceprestige " + ChatColor.YELLOW + + "Force a player to prestige, bypassing requirements."); + } + } + + if (sender.hasPermission("rankup.checkversion")) { + notifier.notify(sender, false); + } + + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/MaxRankupCommand.java b/src/main/java/sh/okx/rankup/commands/MaxRankupCommand.java index f989d26..1ed77af 100644 --- a/src/main/java/sh/okx/rankup/commands/MaxRankupCommand.java +++ b/src/main/java/sh/okx/rankup/commands/MaxRankupCommand.java @@ -1,45 +1,45 @@ -package sh.okx.rankup.commands; - -import lombok.RequiredArgsConstructor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.RankupHelper; -import sh.okx.rankup.ranks.Rank; - -@RequiredArgsConstructor -public class MaxRankupCommand implements CommandExecutor { - private final RankupPlugin plugin; - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (!(sender instanceof Player)) { - return false; - } - RankupHelper helper = plugin.getHelper(); - - Player player = (Player) sender; - - if (!helper.checkRankup(player)) { - return true; - } - - do { - Rank rank = plugin.getRankups().getByPlayer(player); - rank.applyRequirements(player); - - helper.doRankup(player, rank); - - // if the individual-messages setting is disabled, only send the "well done you ranked up" - // messages if they can't rank up any more. - if (plugin.getConfig().getBoolean("max-rankup.individual-messages") - || !helper.checkRankup(player, false)) { - helper.sendRankupMessages(player, rank); - } - } while (helper.checkRankup(player, false)); - - return true; - } -} +package sh.okx.rankup.commands; + +import lombok.RequiredArgsConstructor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.RankupHelper; +import sh.okx.rankup.ranks.Rank; + +@RequiredArgsConstructor +public class MaxRankupCommand implements CommandExecutor { + private final RankupPlugin plugin; + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (!(sender instanceof Player)) { + return false; + } + RankupHelper helper = plugin.getHelper(); + + Player player = (Player) sender; + + if (!helper.checkRankup(player)) { + return true; + } + + do { + Rank rank = plugin.getRankups().getByPlayer(player); + rank.applyRequirements(player); + + helper.doRankup(player, rank); + + // if the individual-messages setting is disabled, only send the "well done you ranked up" + // messages if they can't rank up any more. + if (plugin.getConfig().getBoolean("max-rankup.individual-messages") + || !helper.checkRankup(player, false)) { + helper.sendRankupMessages(player, rank); + } + } while (helper.checkRankup(player, false)); + + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/PrestigeCommand.java b/src/main/java/sh/okx/rankup/commands/PrestigeCommand.java index ff51cc0..ddf607d 100644 --- a/src/main/java/sh/okx/rankup/commands/PrestigeCommand.java +++ b/src/main/java/sh/okx/rankup/commands/PrestigeCommand.java @@ -1,73 +1,73 @@ -package sh.okx.rankup.commands; - -import lombok.RequiredArgsConstructor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.gui.Gui; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; - -import java.util.Map; -import java.util.WeakHashMap; - -@RequiredArgsConstructor -public class PrestigeCommand implements CommandExecutor { - private final Map confirming = new WeakHashMap<>(); - private final RankupPlugin plugin; - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (plugin.error(sender)) { - return true; - } - - // check if player - if (!(sender instanceof Player)) { - return false; - } - Player player = (Player) sender; - - Prestiges prestiges = plugin.getPrestiges(); - Prestige prestige = prestiges.getByPlayer(player); - if (!plugin.getHelper().checkPrestige(player)) { - return true; - } - - FileConfiguration config = plugin.getConfig(); - String confirmationType = config.getString("confirmation-type").toLowerCase(); - if (confirmationType.equals("text") && confirming.containsKey(player)) { - long time = System.currentTimeMillis() - confirming.remove(player); - if (time < config.getInt("text.timeout") * 1000) { - plugin.getHelper().prestige(player); - return true; - } - } - - switch (confirmationType) { - case "text": - confirming.put(player, System.currentTimeMillis()); - Prestige next = prestiges.next(prestige); - String nextRank = next == null ? prestiges.getLast() : next.getRank(); - - plugin.replaceMoneyRequirements(plugin.getMessage(prestige, Message.PRESTIGE_CONFIRMATION) - .replaceRanks(player, prestige, nextRank), player, prestige) - .replaceFromTo(prestige) - .send(player); - break; - case "gui": - Gui.of(player, prestige, prestige.getNext(), plugin).open(player); - break; - case "none": - plugin.getHelper().prestige(player); - break; - default: - throw new IllegalArgumentException("Invalid confirmation type " + confirmationType); - } - return true; - } -} +package sh.okx.rankup.commands; + +import lombok.RequiredArgsConstructor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.gui.Gui; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; + +import java.util.Map; +import java.util.WeakHashMap; + +@RequiredArgsConstructor +public class PrestigeCommand implements CommandExecutor { + private final Map confirming = new WeakHashMap<>(); + private final RankupPlugin plugin; + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (plugin.error(sender)) { + return true; + } + + // check if player + if (!(sender instanceof Player)) { + return false; + } + Player player = (Player) sender; + + Prestiges prestiges = plugin.getPrestiges(); + Prestige prestige = prestiges.getByPlayer(player); + if (!plugin.getHelper().checkPrestige(player)) { + return true; + } + + FileConfiguration config = plugin.getConfig(); + String confirmationType = config.getString("confirmation-type").toLowerCase(); + if (confirmationType.equals("text") && confirming.containsKey(player)) { + long time = System.currentTimeMillis() - confirming.remove(player); + if (time < config.getInt("text.timeout") * 1000) { + plugin.getHelper().prestige(player); + return true; + } + } + + switch (confirmationType) { + case "text": + confirming.put(player, System.currentTimeMillis()); + Prestige next = prestiges.next(prestige); + String nextRank = next == null ? prestiges.getLast() : next.getRank(); + + plugin.replaceMoneyRequirements(plugin.getMessage(prestige, Message.PRESTIGE_CONFIRMATION) + .replaceRanks(player, prestige, nextRank), player, prestige) + .replaceFromTo(prestige) + .send(player); + break; + case "gui": + Gui.of(player, prestige, prestige.getNext(), plugin).open(player); + break; + case "none": + plugin.getHelper().prestige(player); + break; + default: + throw new IllegalArgumentException("Invalid confirmation type " + confirmationType); + } + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/PrestigesCommand.java b/src/main/java/sh/okx/rankup/commands/PrestigesCommand.java index 83eede6..5af691d 100644 --- a/src/main/java/sh/okx/rankup/commands/PrestigesCommand.java +++ b/src/main/java/sh/okx/rankup/commands/PrestigesCommand.java @@ -1,50 +1,50 @@ -package sh.okx.rankup.commands; - -import lombok.RequiredArgsConstructor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; - -@RequiredArgsConstructor -public class PrestigesCommand implements CommandExecutor { - private final RankupPlugin plugin; - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (plugin.error(sender)) { - return true; - } - - Prestiges prestiges = plugin.getPrestiges(); - Prestige playerRank = null; - if (sender instanceof Player) { - playerRank = prestiges.getByPlayer((Player) sender); - } - - plugin.sendHeaderFooter(sender, playerRank, Message.PRESTIGES_HEADER); - - Message message = playerRank == null ? Message.PRESTIGES_INCOMPLETE : Message.PRESTIGES_COMPLETE; - Prestige prestige = prestiges.getFirst(); - String nextRank; - do { - nextRank = prestige.getNext(); - if (prestige.equals(playerRank)) { - plugin.getMessage(sender, Message.PRESTIGES_CURRENT, prestige, nextRank) - .send(sender); - message = Message.PRESTIGES_INCOMPLETE; - } else { - plugin.getMessage(sender, message, prestige, nextRank) - .replaceFirstPrestige(prestige, prestiges, prestige.getFrom()) - .send(sender); - } - } while((prestige = prestiges.getByName(nextRank)) != null); - - plugin.sendHeaderFooter(sender, playerRank, Message.PRESTIGES_FOOTER); - return true; - } -} +package sh.okx.rankup.commands; + +import lombok.RequiredArgsConstructor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; + +@RequiredArgsConstructor +public class PrestigesCommand implements CommandExecutor { + private final RankupPlugin plugin; + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (plugin.error(sender)) { + return true; + } + + Prestiges prestiges = plugin.getPrestiges(); + Prestige playerRank = null; + if (sender instanceof Player) { + playerRank = prestiges.getByPlayer((Player) sender); + } + + plugin.sendHeaderFooter(sender, playerRank, Message.PRESTIGES_HEADER); + + Message message = playerRank == null ? Message.PRESTIGES_INCOMPLETE : Message.PRESTIGES_COMPLETE; + Prestige prestige = prestiges.getFirst(); + String nextRank; + do { + nextRank = prestige.getNext(); + if (prestige.equals(playerRank)) { + plugin.getMessage(sender, Message.PRESTIGES_CURRENT, prestige, nextRank) + .send(sender); + message = Message.PRESTIGES_INCOMPLETE; + } else { + plugin.getMessage(sender, message, prestige, nextRank) + .replaceFirstPrestige(prestige, prestiges, prestige.getFrom()) + .send(sender); + } + } while((prestige = prestiges.getByName(nextRank)) != null); + + plugin.sendHeaderFooter(sender, playerRank, Message.PRESTIGES_FOOTER); + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/RanksCommand.java b/src/main/java/sh/okx/rankup/commands/RanksCommand.java index 4e6ae7d..57ff3b3 100644 --- a/src/main/java/sh/okx/rankup/commands/RanksCommand.java +++ b/src/main/java/sh/okx/rankup/commands/RanksCommand.java @@ -1,47 +1,47 @@ -package sh.okx.rankup.commands; - -import lombok.RequiredArgsConstructor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; - -@RequiredArgsConstructor -public class RanksCommand implements CommandExecutor { - private final RankupPlugin plugin; - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (plugin.error(sender)) { - return true; - } - - Rankups rankups = plugin.getRankups(); - Rank playerRank = null; - if (sender instanceof Player) { - playerRank = rankups.getByPlayer((Player) sender); - } - - plugin.sendHeaderFooter(sender, playerRank, Message.RANKS_HEADER); - - Message message = !(sender instanceof Player && rankups.isLast(plugin.getPermissions(), (Player) sender)) - && playerRank == null ? Message.RANKS_INCOMPLETE : Message.RANKS_COMPLETE; - Rank rank = rankups.getFirst(); - while (rank != null) { - String name = rank.getNext(); - if (rank.equals(playerRank)) { - plugin.getMessage(sender, Message.RANKS_CURRENT, rank, name).send(sender); - message = Message.RANKS_INCOMPLETE; - } else { - plugin.getMessage(sender, message, rank, name).send(sender); - } - rank = rankups.getByName(name); - } - plugin.sendHeaderFooter(sender, playerRank, Message.RANKS_FOOTER); - return true; - } -} +package sh.okx.rankup.commands; + +import lombok.RequiredArgsConstructor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; + +@RequiredArgsConstructor +public class RanksCommand implements CommandExecutor { + private final RankupPlugin plugin; + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (plugin.error(sender)) { + return true; + } + + Rankups rankups = plugin.getRankups(); + Rank playerRank = null; + if (sender instanceof Player) { + playerRank = rankups.getByPlayer((Player) sender); + } + + plugin.sendHeaderFooter(sender, playerRank, Message.RANKS_HEADER); + + Message message = !(sender instanceof Player && rankups.isLast(plugin.getPermissions(), (Player) sender)) + && playerRank == null ? Message.RANKS_INCOMPLETE : Message.RANKS_COMPLETE; + Rank rank = rankups.getFirst(); + while (rank != null) { + String name = rank.getNext(); + if (rank.equals(playerRank)) { + plugin.getMessage(sender, Message.RANKS_CURRENT, rank, name).send(sender); + message = Message.RANKS_INCOMPLETE; + } else { + plugin.getMessage(sender, message, rank, name).send(sender); + } + rank = rankups.getByName(name); + } + plugin.sendHeaderFooter(sender, playerRank, Message.RANKS_FOOTER); + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/commands/RankupCommand.java b/src/main/java/sh/okx/rankup/commands/RankupCommand.java index f04018f..7c59699 100644 --- a/src/main/java/sh/okx/rankup/commands/RankupCommand.java +++ b/src/main/java/sh/okx/rankup/commands/RankupCommand.java @@ -1,81 +1,81 @@ -package sh.okx.rankup.commands; - -import lombok.RequiredArgsConstructor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.gui.Gui; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; - -import java.util.Map; -import java.util.WeakHashMap; - -@RequiredArgsConstructor -public class RankupCommand implements CommandExecutor { - // weak hash maps so players going offline are automatically removed. - // otherwise there is a potential (albeit small) memory leak. - private final Map confirming = new WeakHashMap<>(); - private final RankupPlugin plugin; - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (plugin.error(sender)) { - return true; - } - - // check if player - if (!(sender instanceof Player)) { - return false; - } - Player player = (Player) sender; - - Rankups rankups = plugin.getRankups(); - Rank rank = rankups.getByPlayer(player); - if (!plugin.getHelper().checkRankup(player)) { - return true; - } - /*Rank next = rankups.next(rank); - if (next == null) { - plugin.getLogger().severe("Rankup from " + rank.getRank() + " to " + rank.getNext() + - " is defined but " + rank.getNext() + " does not exist."); - plugin.getMessage(Message.INVALID_RANKUP).failIfEmpty().send(player); - return true; - }*/ - String next = rank.getNext(); - - FileConfiguration config = plugin.getConfig(); - String confirmationType = config.getString("confirmation-type").toLowerCase(); - - // if they are on text confirming, rank them up - if (confirmationType.equals("text") && confirming.containsKey(player)) { - long time = System.currentTimeMillis() - confirming.remove(player); - if (time < config.getInt("text.timeout") * 1000) { - plugin.getHelper().rankup(player); - return true; - } - } - - switch (confirmationType) { - case "text": - confirming.put(player, System.currentTimeMillis()); - plugin.replaceMoneyRequirements(plugin.getMessage(rank, Message.CONFIRMATION) - .replaceRanks(player, rank, next), player, rank) - .send(player); - break; - case "gui": - Gui.of(player, rank, next, plugin).open(player); - break; - case "none": - plugin.getHelper().rankup(player); - break; - default: - throw new IllegalArgumentException("Invalid confirmation type " + confirmationType); - } - return true; - } -} +package sh.okx.rankup.commands; + +import lombok.RequiredArgsConstructor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.gui.Gui; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; + +import java.util.Map; +import java.util.WeakHashMap; + +@RequiredArgsConstructor +public class RankupCommand implements CommandExecutor { + // weak hash maps so players going offline are automatically removed. + // otherwise there is a potential (albeit small) memory leak. + private final Map confirming = new WeakHashMap<>(); + private final RankupPlugin plugin; + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (plugin.error(sender)) { + return true; + } + + // check if player + if (!(sender instanceof Player)) { + return false; + } + Player player = (Player) sender; + + Rankups rankups = plugin.getRankups(); + Rank rank = rankups.getByPlayer(player); + if (!plugin.getHelper().checkRankup(player)) { + return true; + } + /*Rank next = rankups.next(rank); + if (next == null) { + plugin.getLogger().severe("Rankup from " + rank.getRank() + " to " + rank.getNext() + + " is defined but " + rank.getNext() + " does not exist."); + plugin.getMessage(Message.INVALID_RANKUP).failIfEmpty().send(player); + return true; + }*/ + String next = rank.getNext(); + + FileConfiguration config = plugin.getConfig(); + String confirmationType = config.getString("confirmation-type").toLowerCase(); + + // if they are on text confirming, rank them up + if (confirmationType.equals("text") && confirming.containsKey(player)) { + long time = System.currentTimeMillis() - confirming.remove(player); + if (time < config.getInt("text.timeout") * 1000) { + plugin.getHelper().rankup(player); + return true; + } + } + + switch (confirmationType) { + case "text": + confirming.put(player, System.currentTimeMillis()); + plugin.replaceMoneyRequirements(plugin.getMessage(rank, Message.CONFIRMATION) + .replaceRanks(player, rank, next), player, rank) + .send(player); + break; + case "gui": + Gui.of(player, rank, next, plugin).open(player); + break; + case "none": + plugin.getHelper().rankup(player); + break; + default: + throw new IllegalArgumentException("Invalid confirmation type " + confirmationType); + } + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/gui/Gui.java b/src/main/java/sh/okx/rankup/gui/Gui.java index fe1cac1..e28d650 100644 --- a/src/main/java/sh/okx/rankup/gui/Gui.java +++ b/src/main/java/sh/okx/rankup/gui/Gui.java @@ -1,139 +1,139 @@ -package sh.okx.rankup.gui; - -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.messages.Message; -import sh.okx.rankup.messages.MessageBuilder; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.ranks.Rank; - -import java.util.Arrays; -import java.util.Objects; -import java.util.stream.Collectors; -import sh.okx.rankup.util.ItemUtil; - -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public class Gui implements InventoryHolder { - @Getter - private Inventory inventory; - @Getter - private ItemStack rankup; - @Getter - private ItemStack cancel; - @Getter - private boolean prestige; - - public static Gui of(Player player, Rank oldRank, String rank, RankupPlugin plugin) { - Gui gui = new Gui(); - gui.prestige = oldRank instanceof Prestige; - - String type = gui.prestige ? "prestige" : "rankup"; - String basePath = type + ".gui"; - ConfigurationSection config = plugin.getSection(oldRank, basePath); - ItemStack[] items = new ItemStack[config.getInt("rows", 1) * 9]; - - ItemStack fill = getItem(plugin, plugin.getSection(oldRank, basePath + ".fill"), player, oldRank, rank); - ItemStack cancel = getItem(plugin, plugin.getSection(oldRank, basePath + ".cancel"), player, oldRank, rank); - ItemStack rankup = getItem(plugin, plugin.getSection(oldRank, basePath + ".rankup"), player, oldRank, rank); - - addItem(items, plugin.getSection(oldRank, basePath + ".rankup"), rankup); - addItem(items, plugin.getSection(oldRank, basePath + ".cancel"), cancel); - addItem(items, plugin.getSection(oldRank, basePath + ".fill"), fill); - - gui.rankup = rankup; - gui.cancel = cancel; - - Inventory inventory = Bukkit.createInventory(gui, items.length, - plugin.replaceMoneyRequirements( - plugin.getMessage(oldRank, gui.prestige ? Message.PRESTIGE_TITLE : Message.TITLE) - .replaceRanks(player, oldRank, rank) - .replaceFromTo(oldRank), player, oldRank).toString()); - inventory.setContents(items); - gui.inventory = inventory; - return gui; - } - - @SuppressWarnings("deprecation") - private static ItemStack getItem(RankupPlugin plugin, ConfigurationSection section, Player player, Rank oldRank, String rank) { - String materialName = section.getString("material").toUpperCase(); - - ItemStack item; - if (ItemUtil.isServerFlattened()) { - Material material = Material.valueOf(materialName); - item = new ItemStack(material); - } else { - // handle default material correctly on older vesions - if (materialName.equals("BLACK_STAINED_GLASS_PANE")) { - materialName = "STAINED_GLASS_PANE:15"; - } - - String[] parts = materialName.split(":"); - Material material = Material.valueOf(parts[0]); - - short type = parts.length > 1 ? Short.parseShort(parts[1]) : 0; - item = new ItemStack(material, 1, type); - } - - if (item.getType() == Material.AIR && section.getName().equalsIgnoreCase("fill")) { - return item; - } - - ItemMeta meta = item.getItemMeta(); - if (section.contains("lore")) { - meta.setLore(Arrays.stream(format(plugin, section.getString("lore"), player, oldRank, rank).split("\n")) - .map(string -> ChatColor.RESET + string) - .collect(Collectors.toList())); - } - if (section.contains("name")) { - meta.setDisplayName(ChatColor.RESET + format(plugin, section.getString("name"), player, oldRank, rank)); - } - item.setItemMeta(meta); - - return item; - } - - private static String format(RankupPlugin plugin, String message, Player player, Rank oldRank, String rank) { - return plugin.replaceMoneyRequirements(new MessageBuilder(ChatColor.translateAlternateColorCodes('&', message)) - .replaceRanks(player, oldRank, rank), player, oldRank) - .toString(); - } - - private static void addItem(ItemStack[] items, ConfigurationSection section, ItemStack item) { - Objects.requireNonNull(section, "GUI configuration section not found"); - if (section.getName().equalsIgnoreCase("fill")) { - for (int i = 0; i < items.length; i++) { - if (items[i] == null) { - items[i] = item; - } - } - return; - } - - String[] locations = section.getString("index").split(" "); - for (String location : locations) { - String[] parts = location.split("-"); - if (parts.length == 1) { - items[Integer.parseInt(parts[0])] = item; - } else { - for (int i = Integer.parseInt(parts[0]); i <= Integer.parseInt(parts[1]); i++) { - items[i] = item; - } - } - } - } - - public void open(Player player) { - player.openInventory(inventory); - } -} +package sh.okx.rankup.gui; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.messages.Message; +import sh.okx.rankup.messages.MessageBuilder; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.ranks.Rank; + +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; +import sh.okx.rankup.util.ItemUtil; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class Gui implements InventoryHolder { + @Getter + private Inventory inventory; + @Getter + private ItemStack rankup; + @Getter + private ItemStack cancel; + @Getter + private boolean prestige; + + public static Gui of(Player player, Rank oldRank, String rank, RankupPlugin plugin) { + Gui gui = new Gui(); + gui.prestige = oldRank instanceof Prestige; + + String type = gui.prestige ? "prestige" : "rankup"; + String basePath = type + ".gui"; + ConfigurationSection config = plugin.getSection(oldRank, basePath); + ItemStack[] items = new ItemStack[config.getInt("rows", 1) * 9]; + + ItemStack fill = getItem(plugin, plugin.getSection(oldRank, basePath + ".fill"), player, oldRank, rank); + ItemStack cancel = getItem(plugin, plugin.getSection(oldRank, basePath + ".cancel"), player, oldRank, rank); + ItemStack rankup = getItem(plugin, plugin.getSection(oldRank, basePath + ".rankup"), player, oldRank, rank); + + addItem(items, plugin.getSection(oldRank, basePath + ".rankup"), rankup); + addItem(items, plugin.getSection(oldRank, basePath + ".cancel"), cancel); + addItem(items, plugin.getSection(oldRank, basePath + ".fill"), fill); + + gui.rankup = rankup; + gui.cancel = cancel; + + Inventory inventory = Bukkit.createInventory(gui, items.length, + plugin.replaceMoneyRequirements( + plugin.getMessage(oldRank, gui.prestige ? Message.PRESTIGE_TITLE : Message.TITLE) + .replaceRanks(player, oldRank, rank) + .replaceFromTo(oldRank), player, oldRank).toString()); + inventory.setContents(items); + gui.inventory = inventory; + return gui; + } + + @SuppressWarnings("deprecation") + private static ItemStack getItem(RankupPlugin plugin, ConfigurationSection section, Player player, Rank oldRank, String rank) { + String materialName = section.getString("material").toUpperCase(); + + ItemStack item; + if (ItemUtil.isServerFlattened()) { + Material material = Material.valueOf(materialName); + item = new ItemStack(material); + } else { + // handle default material correctly on older vesions + if (materialName.equals("BLACK_STAINED_GLASS_PANE")) { + materialName = "STAINED_GLASS_PANE:15"; + } + + String[] parts = materialName.split(":"); + Material material = Material.valueOf(parts[0]); + + short type = parts.length > 1 ? Short.parseShort(parts[1]) : 0; + item = new ItemStack(material, 1, type); + } + + if (item.getType() == Material.AIR && section.getName().equalsIgnoreCase("fill")) { + return item; + } + + ItemMeta meta = item.getItemMeta(); + if (section.contains("lore")) { + meta.setLore(Arrays.stream(format(plugin, section.getString("lore"), player, oldRank, rank).split("\n")) + .map(string -> ChatColor.RESET + string) + .collect(Collectors.toList())); + } + if (section.contains("name")) { + meta.setDisplayName(ChatColor.RESET + format(plugin, section.getString("name"), player, oldRank, rank)); + } + item.setItemMeta(meta); + + return item; + } + + private static String format(RankupPlugin plugin, String message, Player player, Rank oldRank, String rank) { + return plugin.replaceMoneyRequirements(new MessageBuilder(ChatColor.translateAlternateColorCodes('&', message)) + .replaceRanks(player, oldRank, rank), player, oldRank) + .toString(); + } + + private static void addItem(ItemStack[] items, ConfigurationSection section, ItemStack item) { + Objects.requireNonNull(section, "GUI configuration section not found"); + if (section.getName().equalsIgnoreCase("fill")) { + for (int i = 0; i < items.length; i++) { + if (items[i] == null) { + items[i] = item; + } + } + return; + } + + String[] locations = section.getString("index").split(" "); + for (String location : locations) { + String[] parts = location.split("-"); + if (parts.length == 1) { + items[Integer.parseInt(parts[0])] = item; + } else { + for (int i = Integer.parseInt(parts[0]); i <= Integer.parseInt(parts[1]); i++) { + items[i] = item; + } + } + } + } + + public void open(Player player) { + player.openInventory(inventory); + } +} diff --git a/src/main/java/sh/okx/rankup/gui/GuiListener.java b/src/main/java/sh/okx/rankup/gui/GuiListener.java index d14f540..7a1a01d 100644 --- a/src/main/java/sh/okx/rankup/gui/GuiListener.java +++ b/src/main/java/sh/okx/rankup/gui/GuiListener.java @@ -1,40 +1,40 @@ -package sh.okx.rankup.gui; - -import lombok.RequiredArgsConstructor; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import sh.okx.rankup.RankupPlugin; - -@RequiredArgsConstructor -public class GuiListener implements Listener { - private final RankupPlugin plugin; - - @EventHandler - public void on(InventoryClickEvent e) { - Inventory inventory = e.getInventory(); - if (inventory == null - || !(inventory.getHolder() instanceof Gui) - || !inventory.equals(e.getClickedInventory())) { - return; - } - e.setCancelled(true); - - Player player = (Player) e.getWhoClicked(); - Gui gui = (Gui) inventory.getHolder(); - - if (gui.getRankup().isSimilar(e.getCurrentItem())) { - Bukkit.getScheduler().runTask(plugin, player::closeInventory); - if (gui.isPrestige()) { - plugin.getHelper().prestige(player); - } else { - plugin.getHelper().rankup(player); - } - } else if (gui.getCancel().isSimilar(e.getCurrentItem())) { - Bukkit.getScheduler().runTask(plugin, player::closeInventory); - } - } -} +package sh.okx.rankup.gui; + +import lombok.RequiredArgsConstructor; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import sh.okx.rankup.RankupPlugin; + +@RequiredArgsConstructor +public class GuiListener implements Listener { + private final RankupPlugin plugin; + + @EventHandler + public void on(InventoryClickEvent e) { + Inventory inventory = e.getInventory(); + if (inventory == null + || !(inventory.getHolder() instanceof Gui) + || !inventory.equals(e.getClickedInventory())) { + return; + } + e.setCancelled(true); + + Player player = (Player) e.getWhoClicked(); + Gui gui = (Gui) inventory.getHolder(); + + if (gui.getRankup().isSimilar(e.getCurrentItem())) { + Bukkit.getScheduler().runTask(plugin, player::closeInventory); + if (gui.isPrestige()) { + plugin.getHelper().prestige(player); + } else { + plugin.getHelper().rankup(player); + } + } else if (gui.getCancel().isSimilar(e.getCurrentItem())) { + Bukkit.getScheduler().runTask(plugin, player::closeInventory); + } + } +} diff --git a/src/main/java/sh/okx/rankup/hook/PermissionManager.java b/src/main/java/sh/okx/rankup/hook/PermissionManager.java index 0f1e46b..5a3653c 100644 --- a/src/main/java/sh/okx/rankup/hook/PermissionManager.java +++ b/src/main/java/sh/okx/rankup/hook/PermissionManager.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.hook; - -import net.milkbowl.vault.permission.Permission; -import org.bukkit.plugin.RegisteredServiceProvider; -import sh.okx.rankup.RankupPlugin; - -public class PermissionManager { - private final RankupPlugin plugin; - - public PermissionManager(RankupPlugin plugin) { - this.plugin = plugin; - } - - public PermissionProvider findPermissionProvider() { - return getVaultPermissionProvider(); - } - - private PermissionProvider getVaultPermissionProvider() { - RegisteredServiceProvider rsp = plugin.getServer().getServicesManager() - .getRegistration(Permission.class); - if (rsp == null) { - return null; - } - Permission provider = rsp.getProvider(); - if (!provider.hasGroupSupport()) { - return null; - } - return new VaultPermissionProvider(provider); - } -} +package sh.okx.rankup.hook; + +import net.milkbowl.vault.permission.Permission; +import org.bukkit.plugin.RegisteredServiceProvider; +import sh.okx.rankup.RankupPlugin; + +public class PermissionManager { + private final RankupPlugin plugin; + + public PermissionManager(RankupPlugin plugin) { + this.plugin = plugin; + } + + public PermissionProvider findPermissionProvider() { + return getVaultPermissionProvider(); + } + + private PermissionProvider getVaultPermissionProvider() { + RegisteredServiceProvider rsp = plugin.getServer().getServicesManager() + .getRegistration(Permission.class); + if (rsp == null) { + return null; + } + Permission provider = rsp.getProvider(); + if (!provider.hasGroupSupport()) { + return null; + } + return new VaultPermissionProvider(provider); + } +} diff --git a/src/main/java/sh/okx/rankup/hook/PermissionProvider.java b/src/main/java/sh/okx/rankup/hook/PermissionProvider.java index 53b941d..1a3a215 100644 --- a/src/main/java/sh/okx/rankup/hook/PermissionProvider.java +++ b/src/main/java/sh/okx/rankup/hook/PermissionProvider.java @@ -1,9 +1,9 @@ -package sh.okx.rankup.hook; - -import java.util.UUID; - -public interface PermissionProvider { - boolean inGroup(UUID uuid, String group); - void addGroup(UUID uuid, String group); - void removeGroup(UUID uuid, String group); -} +package sh.okx.rankup.hook; + +import java.util.UUID; + +public interface PermissionProvider { + boolean inGroup(UUID uuid, String group); + void addGroup(UUID uuid, String group); + void removeGroup(UUID uuid, String group); +} diff --git a/src/main/java/sh/okx/rankup/hook/VaultPermissionProvider.java b/src/main/java/sh/okx/rankup/hook/VaultPermissionProvider.java index d229e8d..8bc9eec 100644 --- a/src/main/java/sh/okx/rankup/hook/VaultPermissionProvider.java +++ b/src/main/java/sh/okx/rankup/hook/VaultPermissionProvider.java @@ -1,44 +1,44 @@ -package sh.okx.rankup.hook; - -import java.util.Objects; -import java.util.UUID; -import net.milkbowl.vault.permission.Permission; -import org.bukkit.Bukkit; - -public class VaultPermissionProvider implements PermissionProvider { - private final Permission permission; - - public VaultPermissionProvider(Permission permission) { - this.permission = permission; - } - - @Override - public boolean inGroup(UUID uuid, String group) { - Objects.requireNonNull(uuid); - Objects.requireNonNull(group); - - String[] playerGroups = permission.getPlayerGroups(null, Bukkit.getOfflinePlayer(uuid)); - for (String playerGroup : playerGroups) { - if (group.equalsIgnoreCase(playerGroup)) { - return true; - } - } - return false; - } - - @Override - public void addGroup(UUID uuid, String group) { - Objects.requireNonNull(uuid); - Objects.requireNonNull(group); - - permission.playerAddGroup(null, Bukkit.getOfflinePlayer(uuid), group); - } - - @Override - public void removeGroup(UUID uuid, String group) { - Objects.requireNonNull(uuid); - Objects.requireNonNull(group); - - permission.playerRemoveGroup(null, Bukkit.getOfflinePlayer(uuid), group); - } -} +package sh.okx.rankup.hook; + +import java.util.Objects; +import java.util.UUID; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; + +public class VaultPermissionProvider implements PermissionProvider { + private final Permission permission; + + public VaultPermissionProvider(Permission permission) { + this.permission = permission; + } + + @Override + public boolean inGroup(UUID uuid, String group) { + Objects.requireNonNull(uuid); + Objects.requireNonNull(group); + + String[] playerGroups = permission.getPlayerGroups(null, Bukkit.getOfflinePlayer(uuid)); + for (String playerGroup : playerGroups) { + if (group.equalsIgnoreCase(playerGroup)) { + return true; + } + } + return false; + } + + @Override + public void addGroup(UUID uuid, String group) { + Objects.requireNonNull(uuid); + Objects.requireNonNull(group); + + permission.playerAddGroup(null, Bukkit.getOfflinePlayer(uuid), group); + } + + @Override + public void removeGroup(UUID uuid, String group) { + Objects.requireNonNull(uuid); + Objects.requireNonNull(group); + + permission.playerRemoveGroup(null, Bukkit.getOfflinePlayer(uuid), group); + } +} diff --git a/src/main/java/sh/okx/rankup/messages/Message.java b/src/main/java/sh/okx/rankup/messages/Message.java index 91b1190..dc61eaa 100644 --- a/src/main/java/sh/okx/rankup/messages/Message.java +++ b/src/main/java/sh/okx/rankup/messages/Message.java @@ -1,41 +1,41 @@ -package sh.okx.rankup.messages; - -import lombok.Getter; - -public enum Message { - NOT_IN_LADDER("not-in-ladder"), - REQUIREMENTS_NOT_MET("rankup.requirements-not-met"), - NO_RANKUP("rankup.no-rankup"), - SUCCESS_PUBLIC("rankup.success-public"), - SUCCESS_PRIVATE("rankup.success-private"), - CONFIRMATION("rankup.confirmation"), - TITLE("rankup.gui.title"), - RANKS_HEADER("rankup.list.header"), - RANKS_FOOTER("rankup.list.footer"), - RANKS_COMPLETE("rankup.list.complete"), - RANKS_CURRENT("rankup.list.current"), - RANKS_INCOMPLETE("rankup.list.incomplete"), - PRESTIGE_REQUIREMENTS_NOT_MET("prestige.requirements-not-met"), - PRESTIGE_NO_PRESTIGE("prestige.no-prestige"), - PRESTIGES_HEADER("prestige.list.header"), - PRESTIGES_FOOTER("prestige.list.footer"), - PRESTIGES_COMPLETE("prestige.list.complete"), - PRESTIGES_CURRENT("prestige.list.current"), - PRESTIGES_INCOMPLETE("prestige.list.incomplete"), - PRESTIGE_TITLE("prestige.gui.title"), - COOLDOWN_SINGULAR("rankup.cooldown.singular"), - COOLDOWN_PLURAL("rankup.cooldown.plural"), - MUST_PRESTIGE("rankup.must-prestige"), - NOT_HIGH_ENOUGH("not-high-enough"), - PRESTIGE_SUCCESS_PUBLIC("prestige.success-public"), - PRESTIGE_SUCCESS_PRIVATE("prestige.success-private"), - PRESTIGE_CONFIRMATION("prestige.confirmation"), - INVALID_RANKUP("invalid-rankup"); - - @Getter - private final String name; - - Message(String name) { - this.name = name; - } +package sh.okx.rankup.messages; + +import lombok.Getter; + +public enum Message { + NOT_IN_LADDER("not-in-ladder"), + REQUIREMENTS_NOT_MET("rankup.requirements-not-met"), + NO_RANKUP("rankup.no-rankup"), + SUCCESS_PUBLIC("rankup.success-public"), + SUCCESS_PRIVATE("rankup.success-private"), + CONFIRMATION("rankup.confirmation"), + TITLE("rankup.gui.title"), + RANKS_HEADER("rankup.list.header"), + RANKS_FOOTER("rankup.list.footer"), + RANKS_COMPLETE("rankup.list.complete"), + RANKS_CURRENT("rankup.list.current"), + RANKS_INCOMPLETE("rankup.list.incomplete"), + PRESTIGE_REQUIREMENTS_NOT_MET("prestige.requirements-not-met"), + PRESTIGE_NO_PRESTIGE("prestige.no-prestige"), + PRESTIGES_HEADER("prestige.list.header"), + PRESTIGES_FOOTER("prestige.list.footer"), + PRESTIGES_COMPLETE("prestige.list.complete"), + PRESTIGES_CURRENT("prestige.list.current"), + PRESTIGES_INCOMPLETE("prestige.list.incomplete"), + PRESTIGE_TITLE("prestige.gui.title"), + COOLDOWN_SINGULAR("rankup.cooldown.singular"), + COOLDOWN_PLURAL("rankup.cooldown.plural"), + MUST_PRESTIGE("rankup.must-prestige"), + NOT_HIGH_ENOUGH("not-high-enough"), + PRESTIGE_SUCCESS_PUBLIC("prestige.success-public"), + PRESTIGE_SUCCESS_PRIVATE("prestige.success-private"), + PRESTIGE_CONFIRMATION("prestige.confirmation"), + INVALID_RANKUP("invalid-rankup"); + + @Getter + private final String name; + + Message(String name) { + this.name = name; + } } \ No newline at end of file diff --git a/src/main/java/sh/okx/rankup/messages/MessageBuilder.java b/src/main/java/sh/okx/rankup/messages/MessageBuilder.java index 8444a00..4bf8f6f 100644 --- a/src/main/java/sh/okx/rankup/messages/MessageBuilder.java +++ b/src/main/java/sh/okx/rankup/messages/MessageBuilder.java @@ -1,124 +1,124 @@ -package sh.okx.rankup.messages; - -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.ranks.Rank; - -import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class MessageBuilder { - private String message; - - public MessageBuilder(String message) { - this.message = message; - } - - public static MessageBuilder of(ConfigurationSection config, Message message) { - return MessageBuilder.of(config, message.getName()); - } - - private static MessageBuilder of(ConfigurationSection config, String message) { - String string = config.getString(message); - Objects.requireNonNull(string, "Configuration message '" + message + "' not found!"); - return new MessageBuilder(ChatColor.translateAlternateColorCodes('&', string)); - } - - public MessageBuilder replace(Variable variable, Object value) { - return replace(variable.name(), value); - } - - public MessageBuilder replace(String name, Object value) { - Pattern pattern = Pattern.compile("\\{" + name + "}", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(message); - this.message = matcher.replaceAll(String.valueOf(value)); - return this; - } - - public MessageBuilder replaceFirstPrestige(Rank rank, Prestiges prestiges, String with) { - if (prestiges != null && prestiges.getFirst().equals(rank)) { - replace(Variable.OLD_RANK, with); - } - return this; - } - - public MessageBuilder replaceRanks(CommandSender player, String rankName) { - replace(Variable.PLAYER, player.getName()); - replaceRanks(rankName); - return this; - } - - public MessageBuilder replaceRanks(CommandSender player, Rank oldRank, String rankName) { - replace(Variable.PLAYER, player.getName()); - replaceRanks(oldRank, rankName); - return this; - } - - public MessageBuilder replaceRanks(String rankName) { - replace(Variable.RANK, rankName); - return this; - } - - public MessageBuilder replaceRanks(Rank oldRank, String rankName) { - replaceRanks(rankName); - replace(Variable.OLD_RANK, oldRank.getRank()); - return this; - } - - public MessageBuilder replaceFromTo(Rank rank) { - if (rank instanceof Prestige) { - Prestige prestige = (Prestige) rank; - replace(Variable.FROM, prestige.getFrom()); - replace(Variable.TO, prestige.getTo()); - } - return this; - } - - /** - * Fails the MessageBuilder if the message is empty. - * if this fails, all subsequent calls to that MessageBuilder will do nothing - * @return a NullMessageBuilder if the message is empty, itself otherwise - */ - public MessageBuilder failIfEmpty() { - return failIf(message.isEmpty()); - } - - public MessageBuilder failIf(boolean value) { - if (value) { - return new NullMessageBuilder(); - } else { - return this; - } - } - - public void send(CommandSender sender) { - String msg = message; - if (sender instanceof Player && Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - msg = PlaceholderAPI.setPlaceholders((Player) sender, msg); - } - sender.sendMessage(msg); - } - - /** - * Sends the message to all players - * ie, calls MessageBuilder#send(Player) for all players online, and sends the message in the console. - */ - public void broadcast() { - for (Player player : Bukkit.getOnlinePlayers()) { - send(player); - } - send(Bukkit.getConsoleSender()); - } - - @Override - public String toString() { - return message; - } -} +package sh.okx.rankup.messages; + +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.ranks.Rank; + +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MessageBuilder { + private String message; + + public MessageBuilder(String message) { + this.message = message; + } + + public static MessageBuilder of(ConfigurationSection config, Message message) { + return MessageBuilder.of(config, message.getName()); + } + + private static MessageBuilder of(ConfigurationSection config, String message) { + String string = config.getString(message); + Objects.requireNonNull(string, "Configuration message '" + message + "' not found!"); + return new MessageBuilder(ChatColor.translateAlternateColorCodes('&', string)); + } + + public MessageBuilder replace(Variable variable, Object value) { + return replace(variable.name(), value); + } + + public MessageBuilder replace(String name, Object value) { + Pattern pattern = Pattern.compile("\\{" + name + "}", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(message); + this.message = matcher.replaceAll(String.valueOf(value)); + return this; + } + + public MessageBuilder replaceFirstPrestige(Rank rank, Prestiges prestiges, String with) { + if (prestiges != null && prestiges.getFirst().equals(rank)) { + replace(Variable.OLD_RANK, with); + } + return this; + } + + public MessageBuilder replaceRanks(CommandSender player, String rankName) { + replace(Variable.PLAYER, player.getName()); + replaceRanks(rankName); + return this; + } + + public MessageBuilder replaceRanks(CommandSender player, Rank oldRank, String rankName) { + replace(Variable.PLAYER, player.getName()); + replaceRanks(oldRank, rankName); + return this; + } + + public MessageBuilder replaceRanks(String rankName) { + replace(Variable.RANK, rankName); + return this; + } + + public MessageBuilder replaceRanks(Rank oldRank, String rankName) { + replaceRanks(rankName); + replace(Variable.OLD_RANK, oldRank.getRank()); + return this; + } + + public MessageBuilder replaceFromTo(Rank rank) { + if (rank instanceof Prestige) { + Prestige prestige = (Prestige) rank; + replace(Variable.FROM, prestige.getFrom()); + replace(Variable.TO, prestige.getTo()); + } + return this; + } + + /** + * Fails the MessageBuilder if the message is empty. + * if this fails, all subsequent calls to that MessageBuilder will do nothing + * @return a NullMessageBuilder if the message is empty, itself otherwise + */ + public MessageBuilder failIfEmpty() { + return failIf(message.isEmpty()); + } + + public MessageBuilder failIf(boolean value) { + if (value) { + return new NullMessageBuilder(); + } else { + return this; + } + } + + public void send(CommandSender sender) { + String msg = message; + if (sender instanceof Player && Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + msg = PlaceholderAPI.setPlaceholders((Player) sender, msg); + } + sender.sendMessage(msg); + } + + /** + * Sends the message to all players + * ie, calls MessageBuilder#send(Player) for all players online, and sends the message in the console. + */ + public void broadcast() { + for (Player player : Bukkit.getOnlinePlayers()) { + send(player); + } + send(Bukkit.getConsoleSender()); + } + + @Override + public String toString() { + return message; + } +} diff --git a/src/main/java/sh/okx/rankup/messages/NullMessageBuilder.java b/src/main/java/sh/okx/rankup/messages/NullMessageBuilder.java index 1c1668c..373402f 100644 --- a/src/main/java/sh/okx/rankup/messages/NullMessageBuilder.java +++ b/src/main/java/sh/okx/rankup/messages/NullMessageBuilder.java @@ -1,35 +1,35 @@ -package sh.okx.rankup.messages; - -import org.bukkit.command.CommandSender; - -/** - * A no-op implementation of MessageBuilder - */ -public class NullMessageBuilder extends MessageBuilder { - NullMessageBuilder() { - super(null); - } - - @Override - public MessageBuilder failIf(boolean value) { - return this; - } - - @Override - public MessageBuilder replace(Variable variable, Object value) { - return this; - } - - @Override - public void send(CommandSender sender) { - } - - @Override - public void broadcast() { - } - - @Override - public String toString() { - return null; - } -} +package sh.okx.rankup.messages; + +import org.bukkit.command.CommandSender; + +/** + * A no-op implementation of MessageBuilder + */ +public class NullMessageBuilder extends MessageBuilder { + NullMessageBuilder() { + super(null); + } + + @Override + public MessageBuilder failIf(boolean value) { + return this; + } + + @Override + public MessageBuilder replace(Variable variable, Object value) { + return this; + } + + @Override + public void send(CommandSender sender) { + } + + @Override + public void broadcast() { + } + + @Override + public String toString() { + return null; + } +} diff --git a/src/main/java/sh/okx/rankup/messages/Variable.java b/src/main/java/sh/okx/rankup/messages/Variable.java index c989076..0fed4ce 100644 --- a/src/main/java/sh/okx/rankup/messages/Variable.java +++ b/src/main/java/sh/okx/rankup/messages/Variable.java @@ -1,18 +1,18 @@ -package sh.okx.rankup.messages; - -public enum Variable { - PLAYER, - OLD_RANK, - RANK, - FROM, - TO, - MONEY, - MONEY_NEEDED, - AMOUNT, - AMOUNT_NEEDED, - AMOUNT_DONE, - PERCENT_DONE, - PERCENT_LEFT, - SECONDS, - SECONDS_LEFT -} +package sh.okx.rankup.messages; + +public enum Variable { + PLAYER, + OLD_RANK, + RANK, + FROM, + TO, + MONEY, + MONEY_NEEDED, + AMOUNT, + AMOUNT_NEEDED, + AMOUNT_DONE, + PERCENT_DONE, + PERCENT_LEFT, + SECONDS, + SECONDS_LEFT +} diff --git a/src/main/java/sh/okx/rankup/placeholders/Placeholders.java b/src/main/java/sh/okx/rankup/placeholders/Placeholders.java index a91a7c5..3ef7127 100644 --- a/src/main/java/sh/okx/rankup/placeholders/Placeholders.java +++ b/src/main/java/sh/okx/rankup/placeholders/Placeholders.java @@ -1,44 +1,44 @@ -package sh.okx.rankup.placeholders; - -import lombok.Getter; -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.Bukkit; -import sh.okx.rankup.RankupPlugin; - -import java.text.DecimalFormat; - -public class Placeholders { - private final RankupPlugin plugin; - @Getter - private final DecimalFormat moneyFormat; - @Getter - private final DecimalFormat percentFormat; - @Getter - private final DecimalFormat simpleFormat; - @Getter - private RankupExpansion expansion; - private boolean registered; - - public Placeholders(RankupPlugin plugin) { - this.plugin = plugin; - this.moneyFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.money-format")); - this.percentFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.percent-format")); - this.simpleFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.simple-format")); - } - - public void register() { - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - expansion = new RankupExpansion(plugin, this); - expansion.register(); - registered = true; - } else { - registered = false; - } - } - - public void unregister() { - if (registered) { - PlaceholderAPI.unregisterPlaceholderHook("rankup"); - } - } -} +package sh.okx.rankup.placeholders; + +import lombok.Getter; +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.Bukkit; +import sh.okx.rankup.RankupPlugin; + +import java.text.DecimalFormat; + +public class Placeholders { + private final RankupPlugin plugin; + @Getter + private final DecimalFormat moneyFormat; + @Getter + private final DecimalFormat percentFormat; + @Getter + private final DecimalFormat simpleFormat; + @Getter + private RankupExpansion expansion; + private boolean registered; + + public Placeholders(RankupPlugin plugin) { + this.plugin = plugin; + this.moneyFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.money-format")); + this.percentFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.percent-format")); + this.simpleFormat = new DecimalFormat(plugin.getConfig().getString("placeholders.simple-format")); + } + + public void register() { + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + expansion = new RankupExpansion(plugin, this); + expansion.register(); + registered = true; + } else { + registered = false; + } + } + + public void unregister() { + if (registered) { + PlaceholderAPI.unregisterPlaceholderHook("rankup"); + } + } +} diff --git a/src/main/java/sh/okx/rankup/placeholders/RankupExpansion.java b/src/main/java/sh/okx/rankup/placeholders/RankupExpansion.java index ce49058..7996773 100644 --- a/src/main/java/sh/okx/rankup/placeholders/RankupExpansion.java +++ b/src/main/java/sh/okx/rankup/placeholders/RankupExpansion.java @@ -1,219 +1,219 @@ -package sh.okx.rankup.placeholders; - -import lombok.RequiredArgsConstructor; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.Rankups; -import sh.okx.rankup.requirements.Requirement; - -import java.util.Objects; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@RequiredArgsConstructor -public class RankupExpansion extends PlaceholderExpansion { - private static final Pattern PATTERN = Pattern.compile("(.*)#(.*)"); - - private final RankupPlugin plugin; - private final Placeholders placeholders; - - @Override - public String onPlaceholderRequest(Player player, String params) { - if (player == null) { - return ""; - } - params = params.toLowerCase(); - - Rankups rankups = plugin.getRankups(); - Rank rank = rankups.getByPlayer(player); - - Prestiges prestiges = plugin.getPrestiges(); - Prestige prestige = null; - if (prestiges != null) { - prestige = prestiges.getByPlayer(player); - } - - if (params.startsWith("requirement_")) { - String[] parts = params.split("_", 3); - return getPlaceholderRequirement(player, rank, - replacePattern(parts[1]), parts.length > 2 ? parts[2] : ""); - } else if (params.startsWith("rank_requirement_")) { - String[] parts = params.split("_", 5); - return getPlaceholderRequirement(player, rankups.getByName(parts[2]), - replacePattern(parts[3]), parts.length > 4 ? parts[4] : ""); -// return placeholders.getSimpleFormat().format(orElse(rankups.getByName(parts[2]).getRequirement(parts[3]), Requirement::getValueDouble, 0)); - } else if (params.startsWith("rank_money_")) { - String[] parts = params.split("_", 4); - double amount = Objects.requireNonNull(rankups.getByName(parts[2]), "Rankup " + parts[2] + " does not exist").getRequirement(player, "money").getValueDouble(); - if (parts.length > 3 && parts[3].equalsIgnoreCase("left")) { - amount = amount - plugin.getEconomy().getBalance(player); - } - return plugin.formatMoney(Math.max(0, amount)); - } - - switch (params) { - case "current_prestige": - requirePrestiging(prestiges, params); - if (prestiges.isLast(plugin.getPermissions(), player)) { - return prestiges.getLast(); - } else if (prestige == null || prestige.getRank() == null) { - return getPlaceholder("no-prestige"); - } else { - return prestige.getRank(); - } - case "next_prestige": - requirePrestiging(prestiges, params); - if (prestiges.isLast(plugin.getPermissions(), player)) { - return getPlaceholder("highest-rank"); - } - return orElse(prestige, Prestige::getNext, prestiges.getFirst().getNext()); - case "prestige_money": - requirePrestiging(prestiges, params); - return String.valueOf(simplify(orElse(prestige, r -> r.isIn(player) ? r.getRequirement(player, "money").getValueDouble() : 0, 0))); - case "prestige_money_formatted": - requirePrestiging(prestiges, params); - return plugin.formatMoney(orElse(prestige, r -> r.isIn(player) ? r.getRequirement(player, "money").getValueDouble() : 0, 0D)); - case "current_rank": - if (rankups.isLast(plugin.getPermissions(), player)) { - return rankups.getLast(); - } else if (rank == null) { - return getPlaceholder("not-in-ladder"); - } else { - return rank.getRank(); - } - case "next_rank": - if (rankups.isLast(plugin.getPermissions(), player)) { - return getPlaceholder("highest-rank"); - } - return orElsePlaceholder(rank, r -> orElsePlaceholder(rank, Rank::getNext, "highest-rank"), "not-in-ladder"); - case "money": - return String.valueOf(getMoney(player, rank)); - case "money_formatted": - return plugin.formatMoney(getMoney(player, rank).doubleValue()); - case "money_left": - return String.valueOf(Math.max(0, orElse(rank, r -> simplify(plugin.getEconomy().getBalance(player) - r.getRequirement(player, "money").getValueDouble()), 0).doubleValue())); - case "money_left_formatted": - return plugin.formatMoney(Math.max(0D, orElse(rank, r -> plugin.getEconomy().getBalance(player) - r.getRequirement(player, "money").getValueDouble(), 0D))); - case "percent_left": - return String.valueOf(Math.max(0D, orElse(rank, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); - case "percent_left_formatted": - return placeholders.getPercentFormat().format(Math.max(0D, orElse(rank, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); - case "percent_done": - return String.valueOf(Math.min(100D, orElse(rank, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); - case "percent_done_formatted": - return placeholders.getPercentFormat().format(Math.min(100D, orElse(rank, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); - case "prestige_percent_left_formatted": - return placeholders.getPercentFormat().format(Math.max(0D, orElse(prestige, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); - case "prestige_percent_done_formatted": - return placeholders.getPercentFormat().format(Math.min(100D, orElse(prestige, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); - default: - return null; - } - } - - private Number getMoney(Player player, Rank rank) { - return orElse(rank, r -> simplify(r.getRequirement(player, "money").getValueDouble()), 0); - } - - private void requirePrestiging(Prestiges prestiges, String params) { - Objects.requireNonNull(prestiges, "Using %rankup_" + params + "% prestige placeholder but prestiging is disabled."); - } - - private String getPlaceholderRequirement(Player player, Rank rank, String requirementName, String params) { - if (rank == null) { - return ""; - } - Requirement requirement = rank.getRequirement(player, requirementName); - switch (params) { - case "": - return orElse(requirement, Requirement::getValueString, "0"); - case "left": - return placeholders.getSimpleFormat().format(orElse(requirement, r -> r.getRemaining(player), 0)); - case "done": - return placeholders.getSimpleFormat().format(orElse(requirement, r -> r.getValueDouble() - r.getRemaining(player), 0)); - case "percent_left": - return placeholders.getPercentFormat().format(orElse(requirement, r -> (r.getRemaining(player) / r.getValueDouble()) * 100, 0)); - case "percent_done": - return placeholders.getPercentFormat().format(orElse(requirement, r -> (1 - (r.getRemaining(player) / r.getValueDouble())) * 100, 100)); - default: - return null; - } - } - - private Number simplify(Number number) { - if (number instanceof Float) { - return (float) number % 1 == 0 ? number.intValue() : number; - } else if (number instanceof Double) { - return (double) number % 1 == 0 ? number.longValue() : number; - } else { - return number; - } - } - - private String orElsePlaceholder(T t, Function value, Object fallback) { - if (t == null) { - return getPlaceholder(String.valueOf(fallback)); - } - - try { - return String.valueOf(value.apply(t)); - } catch (NullPointerException ex) { - return getPlaceholder(String.valueOf(fallback)); - } - } - - private R orElse(T t, Function value, R fallback) { - if (t == null) { - return fallback; - } - - try { - return value.apply(t); - } catch (NullPointerException ex) { - return fallback; - } - } - - private String replacePattern(String string) { - Matcher matcher = PATTERN.matcher(string); - if (matcher.matches()) { - return matcher.group(1) + "#" + matcher.group(2).replace("-", "_"); - } else { - return string; - } - } - - private String getPlaceholder(String name) { - return plugin.getConfig().getString("placeholders." + name); - } - - @Override - public String getIdentifier() { - return "rankup"; - } - - @Override - public String getAuthor() { - return String.join(", ", plugin.getDescription().getAuthors()); - } - - @Override - public String getVersion() { - return plugin.getDescription().getVersion(); - } - - @Override - public boolean persist() { - return true; - } - - @Override - public boolean canRegister() { - return true; - } -} +package sh.okx.rankup.placeholders; + +import lombok.RequiredArgsConstructor; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.Rankups; +import sh.okx.rankup.requirements.Requirement; + +import java.util.Objects; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@RequiredArgsConstructor +public class RankupExpansion extends PlaceholderExpansion { + private static final Pattern PATTERN = Pattern.compile("(.*)#(.*)"); + + private final RankupPlugin plugin; + private final Placeholders placeholders; + + @Override + public String onPlaceholderRequest(Player player, String params) { + if (player == null) { + return ""; + } + params = params.toLowerCase(); + + Rankups rankups = plugin.getRankups(); + Rank rank = rankups.getByPlayer(player); + + Prestiges prestiges = plugin.getPrestiges(); + Prestige prestige = null; + if (prestiges != null) { + prestige = prestiges.getByPlayer(player); + } + + if (params.startsWith("requirement_")) { + String[] parts = params.split("_", 3); + return getPlaceholderRequirement(player, rank, + replacePattern(parts[1]), parts.length > 2 ? parts[2] : ""); + } else if (params.startsWith("rank_requirement_")) { + String[] parts = params.split("_", 5); + return getPlaceholderRequirement(player, rankups.getByName(parts[2]), + replacePattern(parts[3]), parts.length > 4 ? parts[4] : ""); +// return placeholders.getSimpleFormat().format(orElse(rankups.getByName(parts[2]).getRequirement(parts[3]), Requirement::getValueDouble, 0)); + } else if (params.startsWith("rank_money_")) { + String[] parts = params.split("_", 4); + double amount = Objects.requireNonNull(rankups.getByName(parts[2]), "Rankup " + parts[2] + " does not exist").getRequirement(player, "money").getValueDouble(); + if (parts.length > 3 && parts[3].equalsIgnoreCase("left")) { + amount = amount - plugin.getEconomy().getBalance(player); + } + return plugin.formatMoney(Math.max(0, amount)); + } + + switch (params) { + case "current_prestige": + requirePrestiging(prestiges, params); + if (prestiges.isLast(plugin.getPermissions(), player)) { + return prestiges.getLast(); + } else if (prestige == null || prestige.getRank() == null) { + return getPlaceholder("no-prestige"); + } else { + return prestige.getRank(); + } + case "next_prestige": + requirePrestiging(prestiges, params); + if (prestiges.isLast(plugin.getPermissions(), player)) { + return getPlaceholder("highest-rank"); + } + return orElse(prestige, Prestige::getNext, prestiges.getFirst().getNext()); + case "prestige_money": + requirePrestiging(prestiges, params); + return String.valueOf(simplify(orElse(prestige, r -> r.isIn(player) ? r.getRequirement(player, "money").getValueDouble() : 0, 0))); + case "prestige_money_formatted": + requirePrestiging(prestiges, params); + return plugin.formatMoney(orElse(prestige, r -> r.isIn(player) ? r.getRequirement(player, "money").getValueDouble() : 0, 0D)); + case "current_rank": + if (rankups.isLast(plugin.getPermissions(), player)) { + return rankups.getLast(); + } else if (rank == null) { + return getPlaceholder("not-in-ladder"); + } else { + return rank.getRank(); + } + case "next_rank": + if (rankups.isLast(plugin.getPermissions(), player)) { + return getPlaceholder("highest-rank"); + } + return orElsePlaceholder(rank, r -> orElsePlaceholder(rank, Rank::getNext, "highest-rank"), "not-in-ladder"); + case "money": + return String.valueOf(getMoney(player, rank)); + case "money_formatted": + return plugin.formatMoney(getMoney(player, rank).doubleValue()); + case "money_left": + return String.valueOf(Math.max(0, orElse(rank, r -> simplify(plugin.getEconomy().getBalance(player) - r.getRequirement(player, "money").getValueDouble()), 0).doubleValue())); + case "money_left_formatted": + return plugin.formatMoney(Math.max(0D, orElse(rank, r -> plugin.getEconomy().getBalance(player) - r.getRequirement(player, "money").getValueDouble(), 0D))); + case "percent_left": + return String.valueOf(Math.max(0D, orElse(rank, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); + case "percent_left_formatted": + return placeholders.getPercentFormat().format(Math.max(0D, orElse(rank, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); + case "percent_done": + return String.valueOf(Math.min(100D, orElse(rank, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); + case "percent_done_formatted": + return placeholders.getPercentFormat().format(Math.min(100D, orElse(rank, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); + case "prestige_percent_left_formatted": + return placeholders.getPercentFormat().format(Math.max(0D, orElse(prestige, r -> (1 - (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble())) * 100, 0).doubleValue())); + case "prestige_percent_done_formatted": + return placeholders.getPercentFormat().format(Math.min(100D, orElse(prestige, r -> (plugin.getEconomy().getBalance(player) / r.getRequirement(player, "money").getValueDouble()) * 100, 0).doubleValue())); + default: + return null; + } + } + + private Number getMoney(Player player, Rank rank) { + return orElse(rank, r -> simplify(r.getRequirement(player, "money").getValueDouble()), 0); + } + + private void requirePrestiging(Prestiges prestiges, String params) { + Objects.requireNonNull(prestiges, "Using %rankup_" + params + "% prestige placeholder but prestiging is disabled."); + } + + private String getPlaceholderRequirement(Player player, Rank rank, String requirementName, String params) { + if (rank == null) { + return ""; + } + Requirement requirement = rank.getRequirement(player, requirementName); + switch (params) { + case "": + return orElse(requirement, Requirement::getValueString, "0"); + case "left": + return placeholders.getSimpleFormat().format(orElse(requirement, r -> r.getRemaining(player), 0)); + case "done": + return placeholders.getSimpleFormat().format(orElse(requirement, r -> r.getValueDouble() - r.getRemaining(player), 0)); + case "percent_left": + return placeholders.getPercentFormat().format(orElse(requirement, r -> (r.getRemaining(player) / r.getValueDouble()) * 100, 0)); + case "percent_done": + return placeholders.getPercentFormat().format(orElse(requirement, r -> (1 - (r.getRemaining(player) / r.getValueDouble())) * 100, 100)); + default: + return null; + } + } + + private Number simplify(Number number) { + if (number instanceof Float) { + return (float) number % 1 == 0 ? number.intValue() : number; + } else if (number instanceof Double) { + return (double) number % 1 == 0 ? number.longValue() : number; + } else { + return number; + } + } + + private String orElsePlaceholder(T t, Function value, Object fallback) { + if (t == null) { + return getPlaceholder(String.valueOf(fallback)); + } + + try { + return String.valueOf(value.apply(t)); + } catch (NullPointerException ex) { + return getPlaceholder(String.valueOf(fallback)); + } + } + + private R orElse(T t, Function value, R fallback) { + if (t == null) { + return fallback; + } + + try { + return value.apply(t); + } catch (NullPointerException ex) { + return fallback; + } + } + + private String replacePattern(String string) { + Matcher matcher = PATTERN.matcher(string); + if (matcher.matches()) { + return matcher.group(1) + "#" + matcher.group(2).replace("-", "_"); + } else { + return string; + } + } + + private String getPlaceholder(String name) { + return plugin.getConfig().getString("placeholders." + name); + } + + @Override + public String getIdentifier() { + return "rankup"; + } + + @Override + public String getAuthor() { + return String.join(", ", plugin.getDescription().getAuthors()); + } + + @Override + public String getVersion() { + return plugin.getDescription().getVersion(); + } + + @Override + public boolean persist() { + return true; + } + + @Override + public boolean canRegister() { + return true; + } +} diff --git a/src/main/java/sh/okx/rankup/prestige/Prestige.java b/src/main/java/sh/okx/rankup/prestige/Prestige.java index 204e0af..a8401fa 100644 --- a/src/main/java/sh/okx/rankup/prestige/Prestige.java +++ b/src/main/java/sh/okx/rankup/prestige/Prestige.java @@ -1,79 +1,79 @@ -package sh.okx.rankup.prestige; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.ToString; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.ranks.Rank; -import sh.okx.rankup.ranks.requirements.ListRankRequirements; -import sh.okx.rankup.ranks.requirements.RankRequirements; -import sh.okx.rankup.requirements.Requirement; - -import java.util.List; -import java.util.Set; - -@EqualsAndHashCode(callSuper = true) -@ToString(callSuper = true) -public class Prestige extends Rank { - @Getter - private final String from; - @Getter - private final String to; - - private Prestige(ConfigurationSection section, RankupPlugin plugin, String next, String rank, RankRequirements requirements, List commands, String from, String to) { - super(section, plugin, next, rank, requirements, commands); - this.from = from; - this.to = to; - } - - public static Prestige deserialize(RankupPlugin plugin, ConfigurationSection section) { - List requirementsList = section.getStringList("requirements"); - Set requirements = plugin.getRequirements().getRequirements(requirementsList); - - return new Prestige(section, plugin, - section.getString("next"), - section.getString("rank"), - new ListRankRequirements(requirements), - section.getStringList("commands"), - section.getString("from"), - section.getString("to")); - } - - @Override - public boolean isIn(Player player) { - // first prestige does not have a rank - boolean inFrom = plugin.getPermissions().inGroup(player.getUniqueId(), from); - if (rank == null && inFrom) { - // not in any other prestiges - for (Prestige prestige : plugin.getPrestiges().getOrderedList()) { - if (prestige != this && prestige.isIn(player)) { - return false; - } - } - return true; - } - - if (rank == null) { - return false; - } - - // subsequent prestiges - boolean inRank = plugin.getPermissions().inGroup(player.getUniqueId(), rank); - if (inRank) { - return true; - } - - return false; - } - - public boolean isEligable(Player player) { - return plugin.getPermissions().inGroup(player.getUniqueId(), from); - } - - @Override - public boolean isLast() { - return plugin.getPrestiges().getByName(next) == null; - } -} +package sh.okx.rankup.prestige; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.ranks.Rank; +import sh.okx.rankup.ranks.requirements.ListRankRequirements; +import sh.okx.rankup.ranks.requirements.RankRequirements; +import sh.okx.rankup.requirements.Requirement; + +import java.util.List; +import java.util.Set; + +@EqualsAndHashCode(callSuper = true) +@ToString(callSuper = true) +public class Prestige extends Rank { + @Getter + private final String from; + @Getter + private final String to; + + private Prestige(ConfigurationSection section, RankupPlugin plugin, String next, String rank, RankRequirements requirements, List commands, String from, String to) { + super(section, plugin, next, rank, requirements, commands); + this.from = from; + this.to = to; + } + + public static Prestige deserialize(RankupPlugin plugin, ConfigurationSection section) { + List requirementsList = section.getStringList("requirements"); + Set requirements = plugin.getRequirements().getRequirements(requirementsList); + + return new Prestige(section, plugin, + section.getString("next"), + section.getString("rank"), + new ListRankRequirements(requirements), + section.getStringList("commands"), + section.getString("from"), + section.getString("to")); + } + + @Override + public boolean isIn(Player player) { + // first prestige does not have a rank + boolean inFrom = plugin.getPermissions().inGroup(player.getUniqueId(), from); + if (rank == null && inFrom) { + // not in any other prestiges + for (Prestige prestige : plugin.getPrestiges().getOrderedList()) { + if (prestige != this && prestige.isIn(player)) { + return false; + } + } + return true; + } + + if (rank == null) { + return false; + } + + // subsequent prestiges + boolean inRank = plugin.getPermissions().inGroup(player.getUniqueId(), rank); + if (inRank) { + return true; + } + + return false; + } + + public boolean isEligable(Player player) { + return plugin.getPermissions().inGroup(player.getUniqueId(), from); + } + + @Override + public boolean isLast() { + return plugin.getPrestiges().getByName(next) == null; + } +} diff --git a/src/main/java/sh/okx/rankup/prestige/Prestiges.java b/src/main/java/sh/okx/rankup/prestige/Prestiges.java index 72772ee..0c229fd 100644 --- a/src/main/java/sh/okx/rankup/prestige/Prestiges.java +++ b/src/main/java/sh/okx/rankup/prestige/Prestiges.java @@ -1,22 +1,22 @@ -package sh.okx.rankup.prestige; - -import org.bukkit.configuration.file.FileConfiguration; -import sh.okx.rankup.RankList; -import sh.okx.rankup.RankupPlugin; - -public class Prestiges extends RankList { - public Prestiges(RankupPlugin plugin, FileConfiguration config) { - super(config, section -> Prestige.deserialize(plugin, section)); - } - - @Override - public Prestige getFirst() { - for (Prestige prestige : ranks) { - if (prestige.getRank() == null) { - return prestige; - } - } - throw new IllegalStateException("No prestige found for first prestige (first prestige is counted as a prestige without a rank set). " + - "Disable prestiges in config.yml if you don't want any."); - } -} +package sh.okx.rankup.prestige; + +import org.bukkit.configuration.file.FileConfiguration; +import sh.okx.rankup.RankList; +import sh.okx.rankup.RankupPlugin; + +public class Prestiges extends RankList { + public Prestiges(RankupPlugin plugin, FileConfiguration config) { + super(config, section -> Prestige.deserialize(plugin, section)); + } + + @Override + public Prestige getFirst() { + for (Prestige prestige : ranks) { + if (prestige.getRank() == null) { + return prestige; + } + } + throw new IllegalStateException("No prestige found for first prestige (first prestige is counted as a prestige without a rank set). " + + "Disable prestiges in config.yml if you don't want any."); + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/Rank.java b/src/main/java/sh/okx/rankup/ranks/Rank.java index bd6a1e3..88d09c7 100644 --- a/src/main/java/sh/okx/rankup/ranks/Rank.java +++ b/src/main/java/sh/okx/rankup/ranks/Rank.java @@ -1,63 +1,63 @@ -package sh.okx.rankup.ranks; - -import java.util.List; -import lombok.AccessLevel; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.ToString; -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.messages.MessageBuilder; -import sh.okx.rankup.ranks.requirements.RankRequirements; -import sh.okx.rankup.requirements.Requirement; - -@EqualsAndHashCode -@ToString -@RequiredArgsConstructor(access = AccessLevel.PROTECTED) -public class Rank { - @Getter - protected final ConfigurationSection section; - protected final RankupPlugin plugin; - @Getter - protected final String next; - @Getter - protected final String rank; - @Getter - protected final RankRequirements requirements; - protected final List commands; - - public boolean isIn(Player player) { - return plugin.getPermissions().inGroup(player.getUniqueId(), rank); - } - - public boolean isLast() { - return plugin.getRankups().getByName(next) == null; - } - - public boolean hasRequirements(Player player) { - return requirements.hasRequirements(player); - } - - public Requirement getRequirement(Player player, String name) { - return requirements.getRequirement(player, name); - } - - public void applyRequirements(Player player) { - requirements.applyRequirements(player); - } - - - public void runCommands(Player player) { - for (String command : commands) { - String string = new MessageBuilder(command).replaceRanks(player, this, next).toString(); - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - string = PlaceholderAPI.setPlaceholders(player, string); - } - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), string); - } - } -} +package sh.okx.rankup.ranks; + +import java.util.List; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.ToString; +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.messages.MessageBuilder; +import sh.okx.rankup.ranks.requirements.RankRequirements; +import sh.okx.rankup.requirements.Requirement; + +@EqualsAndHashCode +@ToString +@RequiredArgsConstructor(access = AccessLevel.PROTECTED) +public class Rank { + @Getter + protected final ConfigurationSection section; + protected final RankupPlugin plugin; + @Getter + protected final String next; + @Getter + protected final String rank; + @Getter + protected final RankRequirements requirements; + protected final List commands; + + public boolean isIn(Player player) { + return plugin.getPermissions().inGroup(player.getUniqueId(), rank); + } + + public boolean isLast() { + return plugin.getRankups().getByName(next) == null; + } + + public boolean hasRequirements(Player player) { + return requirements.hasRequirements(player); + } + + public Requirement getRequirement(Player player, String name) { + return requirements.getRequirement(player, name); + } + + public void applyRequirements(Player player) { + requirements.applyRequirements(player); + } + + + public void runCommands(Player player) { + for (String command : commands) { + String string = new MessageBuilder(command).replaceRanks(player, this, next).toString(); + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + string = PlaceholderAPI.setPlaceholders(player, string); + } + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), string); + } + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/Rankup.java b/src/main/java/sh/okx/rankup/ranks/Rankup.java index b1f836e..ecd06df 100644 --- a/src/main/java/sh/okx/rankup/ranks/Rankup.java +++ b/src/main/java/sh/okx/rankup/ranks/Rankup.java @@ -1,32 +1,32 @@ -package sh.okx.rankup.ranks; - -import java.util.List; -import org.bukkit.configuration.ConfigurationSection; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.ranks.requirements.RankRequirements; -import sh.okx.rankup.ranks.requirements.RankRequirementsFactory; - -public class Rankup extends Rank { - public static Rank deserialize(RankupPlugin plugin, ConfigurationSection section) { - String next = section.getString("next"); - String rank = section.getString("rank"); - - if (next != null && next.isEmpty()) { - plugin.getLogger().warning("Rankup section '" + section.getName() + "' has a blank 'next' field, will be ignored."); - return null; - } - - return new Rank(section, plugin, - next, - rank, - RankRequirementsFactory.getRequirements(plugin, section), - section.getStringList("commands")); - } - - protected Rankup(ConfigurationSection section, - RankupPlugin plugin, String next, String rank, - RankRequirements requirements, - List commands) { - super(section, plugin, next, rank, requirements, commands); - } -} +package sh.okx.rankup.ranks; + +import java.util.List; +import org.bukkit.configuration.ConfigurationSection; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.ranks.requirements.RankRequirements; +import sh.okx.rankup.ranks.requirements.RankRequirementsFactory; + +public class Rankup extends Rank { + public static Rank deserialize(RankupPlugin plugin, ConfigurationSection section) { + String next = section.getString("next"); + String rank = section.getString("rank"); + + if (next != null && next.isEmpty()) { + plugin.getLogger().warning("Rankup section '" + section.getName() + "' has a blank 'next' field, will be ignored."); + return null; + } + + return new Rank(section, plugin, + next, + rank, + RankRequirementsFactory.getRequirements(plugin, section), + section.getStringList("commands")); + } + + protected Rankup(ConfigurationSection section, + RankupPlugin plugin, String next, String rank, + RankRequirements requirements, + List commands) { + super(section, plugin, next, rank, requirements, commands); + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/Rankups.java b/src/main/java/sh/okx/rankup/ranks/Rankups.java index 30965ff..4f66a18 100644 --- a/src/main/java/sh/okx/rankup/ranks/Rankups.java +++ b/src/main/java/sh/okx/rankup/ranks/Rankups.java @@ -1,11 +1,11 @@ -package sh.okx.rankup.ranks; - -import org.bukkit.configuration.file.FileConfiguration; -import sh.okx.rankup.RankList; -import sh.okx.rankup.RankupPlugin; - -public class Rankups extends RankList { - public Rankups(RankupPlugin plugin, FileConfiguration config) { - super(config, section -> Rankup.deserialize(plugin, section)); - } -} +package sh.okx.rankup.ranks; + +import org.bukkit.configuration.file.FileConfiguration; +import sh.okx.rankup.RankList; +import sh.okx.rankup.RankupPlugin; + +public class Rankups extends RankList { + public Rankups(RankupPlugin plugin, FileConfiguration config) { + super(config, section -> Rankup.deserialize(plugin, section)); + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/requirements/ListRankRequirements.java b/src/main/java/sh/okx/rankup/ranks/requirements/ListRankRequirements.java index fad922a..0be4d86 100644 --- a/src/main/java/sh/okx/rankup/ranks/requirements/ListRankRequirements.java +++ b/src/main/java/sh/okx/rankup/ranks/requirements/ListRankRequirements.java @@ -1,48 +1,48 @@ -package sh.okx.rankup.ranks.requirements; - -import java.util.Set; -import org.bukkit.entity.Player; -import sh.okx.rankup.requirements.DeductibleRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class ListRankRequirements implements RankRequirements { - private final Set requirements; - - public ListRankRequirements(Set requirements) { - this.requirements = requirements; - } - - @Override - public Set getRequirements(Player player) { - return requirements; - } - - @Override - public boolean hasRequirements(Player player) { - for (Requirement requirement : requirements) { - if (!requirement.check(player)) { - return false; - } - } - return true; - } - - @Override - public Requirement getRequirement(Player player, String name) { - for (Requirement requirement : requirements) { - if (requirement.getFullName().equalsIgnoreCase(name)) { - return requirement; - } - } - return null; - } - - @Override - public void applyRequirements(Player player) { - for (Requirement requirement : requirements) { - if (requirement instanceof DeductibleRequirement) { - ((DeductibleRequirement) requirement).apply(player); - } - } - } -} +package sh.okx.rankup.ranks.requirements; + +import java.util.Set; +import org.bukkit.entity.Player; +import sh.okx.rankup.requirements.DeductibleRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class ListRankRequirements implements RankRequirements { + private final Set requirements; + + public ListRankRequirements(Set requirements) { + this.requirements = requirements; + } + + @Override + public Set getRequirements(Player player) { + return requirements; + } + + @Override + public boolean hasRequirements(Player player) { + for (Requirement requirement : requirements) { + if (!requirement.check(player)) { + return false; + } + } + return true; + } + + @Override + public Requirement getRequirement(Player player, String name) { + for (Requirement requirement : requirements) { + if (requirement.getFullName().equalsIgnoreCase(name)) { + return requirement; + } + } + return null; + } + + @Override + public void applyRequirements(Player player) { + for (Requirement requirement : requirements) { + if (requirement instanceof DeductibleRequirement) { + ((DeductibleRequirement) requirement).apply(player); + } + } + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/requirements/PrestigeListRankRequirements.java b/src/main/java/sh/okx/rankup/ranks/requirements/PrestigeListRankRequirements.java index ddeddd0..740c011 100644 --- a/src/main/java/sh/okx/rankup/ranks/requirements/PrestigeListRankRequirements.java +++ b/src/main/java/sh/okx/rankup/ranks/requirements/PrestigeListRankRequirements.java @@ -1,63 +1,63 @@ -package sh.okx.rankup.ranks.requirements; - -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.prestige.Prestige; -import sh.okx.rankup.prestige.Prestiges; -import sh.okx.rankup.requirements.Requirement; - -public class PrestigeListRankRequirements implements RankRequirements { - private final RankupPlugin plugin; - private final RankRequirements defaultRequirements; - private final Map requirements; - - public PrestigeListRankRequirements(RankupPlugin plugin, RankRequirements defaultRequirements, Map requirements) { - Objects.requireNonNull(plugin); - Objects.requireNonNull(defaultRequirements); - - this.plugin = plugin; - this.defaultRequirements = defaultRequirements; - this.requirements = requirements; - } - - @Override - public Set getRequirements(Player player) { - return getRankRequirements(player).getRequirements(player); - } - - @Override - public boolean hasRequirements(Player player) { - return getRankRequirements(player).hasRequirements(player); - } - - @Override - public Requirement getRequirement(Player player, String name) { - return getRankRequirements(player).getRequirement(player, name); - } - - @Override - public void applyRequirements(Player player) { - getRankRequirements(player).applyRequirements(player); - } - - private RankRequirements getRankRequirements(Player player) { - Prestiges prestiges = plugin.getPrestiges(); - if (player == null || prestiges == null) { - return defaultRequirements; - } - - for (Prestige prestige : prestiges.getOrderedList()) { - String next = prestige.getNext(); - if(plugin.getPermissions().inGroup(player.getUniqueId(), next)) { - RankRequirements rankRequirements = this.requirements.get(next.toLowerCase()); - if (rankRequirements != null) { - return rankRequirements; - } - } - } - return defaultRequirements; - } -} +package sh.okx.rankup.ranks.requirements; + +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.prestige.Prestige; +import sh.okx.rankup.prestige.Prestiges; +import sh.okx.rankup.requirements.Requirement; + +public class PrestigeListRankRequirements implements RankRequirements { + private final RankupPlugin plugin; + private final RankRequirements defaultRequirements; + private final Map requirements; + + public PrestigeListRankRequirements(RankupPlugin plugin, RankRequirements defaultRequirements, Map requirements) { + Objects.requireNonNull(plugin); + Objects.requireNonNull(defaultRequirements); + + this.plugin = plugin; + this.defaultRequirements = defaultRequirements; + this.requirements = requirements; + } + + @Override + public Set getRequirements(Player player) { + return getRankRequirements(player).getRequirements(player); + } + + @Override + public boolean hasRequirements(Player player) { + return getRankRequirements(player).hasRequirements(player); + } + + @Override + public Requirement getRequirement(Player player, String name) { + return getRankRequirements(player).getRequirement(player, name); + } + + @Override + public void applyRequirements(Player player) { + getRankRequirements(player).applyRequirements(player); + } + + private RankRequirements getRankRequirements(Player player) { + Prestiges prestiges = plugin.getPrestiges(); + if (player == null || prestiges == null) { + return defaultRequirements; + } + + for (Prestige prestige : prestiges.getOrderedList()) { + String next = prestige.getNext(); + if(plugin.getPermissions().inGroup(player.getUniqueId(), next)) { + RankRequirements rankRequirements = this.requirements.get(next.toLowerCase()); + if (rankRequirements != null) { + return rankRequirements; + } + } + } + return defaultRequirements; + } +} diff --git a/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirements.java b/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirements.java index 19f416d..f8c0696 100644 --- a/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirements.java +++ b/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirements.java @@ -1,13 +1,13 @@ -package sh.okx.rankup.ranks.requirements; - -import java.util.Set; -import org.bukkit.entity.Player; -import sh.okx.rankup.requirements.Requirement; - -public interface RankRequirements { - Set getRequirements(Player player); - - boolean hasRequirements(Player player); - Requirement getRequirement(Player player, String name); - void applyRequirements(Player player); -} +package sh.okx.rankup.ranks.requirements; + +import java.util.Set; +import org.bukkit.entity.Player; +import sh.okx.rankup.requirements.Requirement; + +public interface RankRequirements { + Set getRequirements(Player player); + + boolean hasRequirements(Player player); + Requirement getRequirement(Player player, String name); + void applyRequirements(Player player); +} diff --git a/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirementsFactory.java b/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirementsFactory.java index 41fe1d5..052e63d 100644 --- a/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirementsFactory.java +++ b/src/main/java/sh/okx/rankup/ranks/requirements/RankRequirementsFactory.java @@ -1,72 +1,72 @@ -package sh.okx.rankup.ranks.requirements; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import org.bukkit.configuration.ConfigurationSection; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class RankRequirementsFactory { - private static final String REQUIREMENTS = "requirements"; - - public static RankRequirements getRequirements(RankupPlugin plugin, ConfigurationSection section) { - if (section.isConfigurationSection(REQUIREMENTS)) { - return getPrestigeListRequirements(plugin, section.getConfigurationSection(REQUIREMENTS)); - } else { - return getListRequirements(plugin, getRequirementStrings(section, REQUIREMENTS)); - } - } - - private static Collection getRequirementStrings(ConfigurationSection section, String key) { - if (section.isList(key)) { - return section.getStringList(key); - } else { - String string = section.getString(key); - if (string == null) { - return null; - } else { - return Collections.singleton(string); - } - } - } - - private static Set stringsToRequirements(RankupPlugin plugin, Iterable strings) { - return plugin.getRequirements().getRequirements(strings); - } - - private static RankRequirements getListRequirements(RankupPlugin plugin, Iterable list) { - Set requirements = stringsToRequirements(plugin, list); - return new ListRankRequirements(requirements); - } - - private static RankRequirements getPrestigeListRequirements(RankupPlugin plugin, ConfigurationSection section) { - if (plugin.getPrestiges() == null) { - // don't know what to do here - return null; - } - - RankRequirements defaultRequirements = null; - Map requirements = new HashMap<>(); - - for (String key : section.getKeys(false)) { - Collection stringRequirements = getRequirementStrings(section, key); - if (stringRequirements != null) { - RankRequirements rankRequirements = getListRequirements(plugin, stringRequirements); - if ("default".equalsIgnoreCase(key)) { - defaultRequirements = rankRequirements; - } else { - requirements.put(key.toLowerCase(), rankRequirements); - } - } - } - - if (defaultRequirements == null) { - throw new IllegalArgumentException("No default requirements set for rank " + section.getParent().getName() + ". See the wiki for info."); - } - - return new PrestigeListRankRequirements(plugin, defaultRequirements, requirements); - } -} +package sh.okx.rankup.ranks.requirements; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.bukkit.configuration.ConfigurationSection; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class RankRequirementsFactory { + private static final String REQUIREMENTS = "requirements"; + + public static RankRequirements getRequirements(RankupPlugin plugin, ConfigurationSection section) { + if (section.isConfigurationSection(REQUIREMENTS)) { + return getPrestigeListRequirements(plugin, section.getConfigurationSection(REQUIREMENTS)); + } else { + return getListRequirements(plugin, getRequirementStrings(section, REQUIREMENTS)); + } + } + + private static Collection getRequirementStrings(ConfigurationSection section, String key) { + if (section.isList(key)) { + return section.getStringList(key); + } else { + String string = section.getString(key); + if (string == null) { + return null; + } else { + return Collections.singleton(string); + } + } + } + + private static Set stringsToRequirements(RankupPlugin plugin, Iterable strings) { + return plugin.getRequirements().getRequirements(strings); + } + + private static RankRequirements getListRequirements(RankupPlugin plugin, Iterable list) { + Set requirements = stringsToRequirements(plugin, list); + return new ListRankRequirements(requirements); + } + + private static RankRequirements getPrestigeListRequirements(RankupPlugin plugin, ConfigurationSection section) { + if (plugin.getPrestiges() == null) { + // don't know what to do here + return null; + } + + RankRequirements defaultRequirements = null; + Map requirements = new HashMap<>(); + + for (String key : section.getKeys(false)) { + Collection stringRequirements = getRequirementStrings(section, key); + if (stringRequirements != null) { + RankRequirements rankRequirements = getListRequirements(plugin, stringRequirements); + if ("default".equalsIgnoreCase(key)) { + defaultRequirements = rankRequirements; + } else { + requirements.put(key.toLowerCase(), rankRequirements); + } + } + } + + if (defaultRequirements == null) { + throw new IllegalArgumentException("No default requirements set for rank " + section.getParent().getName() + ". See the wiki for info."); + } + + return new PrestigeListRankRequirements(plugin, defaultRequirements, requirements); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/DeductibleRequirement.java b/src/main/java/sh/okx/rankup/requirements/DeductibleRequirement.java index 1f3f60a..d2c66db 100644 --- a/src/main/java/sh/okx/rankup/requirements/DeductibleRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/DeductibleRequirement.java @@ -1,20 +1,22 @@ -package sh.okx.rankup.requirements; - -import org.bukkit.entity.Player; - -public interface DeductibleRequirement { - /** - * Apply the effect of this requirement to the player. - * For money, this could be taking money away from the player. - * You can assume that Requirement#check(Player) has been called, - * and has returned true immediately prior to this. - * - * @param player the player to take from - * @param multiplier The multiplier for the value - */ - void apply(Player player, double multiplier); - - default void apply(Player player) { - apply(player, 1); - } -} +package sh.okx.rankup.requirements; + +import org.bukkit.entity.Player; + +public interface DeductibleRequirement { + /** + * Apply the effect of this requirement to the player. + * For money, this could be taking money away from the player. + * You can assume that Requirement#check(Player) has been called, + * and has returned true immediately prior to this. + * + * Currently the multiplier will always be 1, but that may change in the future. + * + * @param player the player to take from + * @param multiplier The multiplier for the value + */ + void apply(Player player, double multiplier); + + default void apply(Player player) { + apply(player, 1); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/ProgressiveRequirement.java b/src/main/java/sh/okx/rankup/requirements/ProgressiveRequirement.java index 09cdc26..fece93f 100644 --- a/src/main/java/sh/okx/rankup/requirements/ProgressiveRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/ProgressiveRequirement.java @@ -1,34 +1,34 @@ -package sh.okx.rankup.requirements; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; - -public abstract class ProgressiveRequirement extends Requirement { - public ProgressiveRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - public ProgressiveRequirement(RankupPlugin plugin, String name, boolean subRequirement) { - super(plugin, name, subRequirement); - } - - protected ProgressiveRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - return getRemaining(player) <= 0; - } - - @Override - public final double getRemaining(Player player) { - return getRemaining(player, 1); - } - - public double getRemaining(Player player, double multiplier) { - return Math.max(0, (multiplier * getTotal(player)) - getProgress(player)); - } - - public abstract double getProgress(Player player); -} +package sh.okx.rankup.requirements; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; + +public abstract class ProgressiveRequirement extends Requirement { + public ProgressiveRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + public ProgressiveRequirement(RankupPlugin plugin, String name, boolean subRequirement) { + super(plugin, name, subRequirement); + } + + protected ProgressiveRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + return getRemaining(player) <= 0; + } + + @Override + public final double getRemaining(Player player) { + return getRemaining(player, 1); + } + + public double getRemaining(Player player, double multiplier) { + return Math.max(0, (multiplier * getTotal(player)) - getProgress(player)); + } + + public abstract double getProgress(Player player); +} diff --git a/src/main/java/sh/okx/rankup/requirements/Requirement.java b/src/main/java/sh/okx/rankup/requirements/Requirement.java index 1c6b0f8..654ba4b 100644 --- a/src/main/java/sh/okx/rankup/requirements/Requirement.java +++ b/src/main/java/sh/okx/rankup/requirements/Requirement.java @@ -1,104 +1,104 @@ -package sh.okx.rankup.requirements; - -import lombok.Getter; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; - -public abstract class Requirement implements Cloneable { - protected final RankupPlugin plugin; - @Getter - protected final String name; - private String value; - @Getter - private String sub; - private boolean subRequirement; - - public Requirement(RankupPlugin plugin, String name) { - this(plugin, name, false); - } - - public Requirement(RankupPlugin plugin, String name, boolean subRequirement) { - this.plugin = plugin; - this.name = name; - this.subRequirement = subRequirement; - } - - protected Requirement(Requirement clone) { - this.plugin = clone.plugin; - this.name = clone.name; - this.value = clone.value; - this.sub = clone.sub; - this.subRequirement = clone.subRequirement; - } - - public void setValue(String value) { - if (hasSubRequirement()) { - String[] parts = value.split(" ", 2); - if (parts.length < 2) { - throw new IllegalArgumentException("Amount and sub-requirement not present for requirement '" + getName() + "'. You must use the format '" + getName() + " '"); - } - - this.sub = parts[0]; - this.value = parts[1]; - } else { - this.value = value; - } - } - - public String getValueString() { - return value; - } - - public String[] getValuesString() { - return value.split(" "); - } - - public double getValueDouble() { - return Double.parseDouble(value); - } - - public int getValueInt() { - return Integer.parseInt(value); - } - - public boolean getValueBoolean() { - return Boolean.parseBoolean(value); - } - - public String getFullName() { - if (hasSubRequirement()) { - return name + "#" + sub; - } else { - return name; - } - } - - /** - * Check if a player meets this requirement - * - * @param player the player to check - * @return true if they meet the requirement, false otherwise - */ - public abstract boolean check(Player player); - - /** - * Get the remaining amount needed for Requirement#check(Player) to yield true. - * This is not required and is only used in placeholders. - * - * @param player the player to find the remaining amount of - * @return the remaining amount needed. Should be non-negative. - */ - public double getRemaining(Player player) { - return check(player) ? 0 : 1; - } - - public final boolean hasSubRequirement() { - return subRequirement; - } - - public abstract Requirement clone(); - - public double getTotal(Player player) { - return getValueDouble(); - } -} +package sh.okx.rankup.requirements; + +import lombok.Getter; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; + +public abstract class Requirement implements Cloneable { + protected final RankupPlugin plugin; + @Getter + protected final String name; + private String value; + @Getter + private String sub; + private boolean subRequirement; + + public Requirement(RankupPlugin plugin, String name) { + this(plugin, name, false); + } + + public Requirement(RankupPlugin plugin, String name, boolean subRequirement) { + this.plugin = plugin; + this.name = name; + this.subRequirement = subRequirement; + } + + protected Requirement(Requirement clone) { + this.plugin = clone.plugin; + this.name = clone.name; + this.value = clone.value; + this.sub = clone.sub; + this.subRequirement = clone.subRequirement; + } + + public void setValue(String value) { + if (hasSubRequirement()) { + String[] parts = value.split(" ", 2); + if (parts.length < 2) { + throw new IllegalArgumentException("Amount and sub-requirement not present for requirement '" + getName() + "'. You must use the format '" + getName() + " '"); + } + + this.sub = parts[0]; + this.value = parts[1]; + } else { + this.value = value; + } + } + + public String getValueString() { + return value; + } + + public String[] getValuesString() { + return value.split(" "); + } + + public double getValueDouble() { + return Double.parseDouble(value); + } + + public int getValueInt() { + return Integer.parseInt(value); + } + + public boolean getValueBoolean() { + return Boolean.parseBoolean(value); + } + + public String getFullName() { + if (hasSubRequirement()) { + return name + "#" + sub; + } else { + return name; + } + } + + /** + * Check if a player meets this requirement + * + * @param player the player to check + * @return true if they meet the requirement, false otherwise + */ + public abstract boolean check(Player player); + + /** + * Get the remaining amount needed for Requirement#check(Player) to yield true. + * This is not required and is only used in placeholders. + * + * @param player the player to find the remaining amount of + * @return the remaining amount needed. Should be non-negative. + */ + public double getRemaining(Player player) { + return check(player) ? 0 : 1; + } + + public final boolean hasSubRequirement() { + return subRequirement; + } + + public abstract Requirement clone(); + + public double getTotal(Player player) { + return getValueDouble(); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/RequirementRegistry.java b/src/main/java/sh/okx/rankup/requirements/RequirementRegistry.java index e8effae..d74800f 100644 --- a/src/main/java/sh/okx/rankup/requirements/RequirementRegistry.java +++ b/src/main/java/sh/okx/rankup/requirements/RequirementRegistry.java @@ -1,49 +1,49 @@ -package sh.okx.rankup.requirements; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -public class RequirementRegistry { - private Set requirements = new HashSet<>(); - - public void addRequirement(Requirement requirement) { - requirements.add(requirement); - } - - public void addRequirements(Requirement... requirements) { - Collections.addAll(this.requirements, requirements); - } - - public Requirement newRequirement(String name, String value) { - for (Requirement requirement : requirements) { - if (requirement.getName().equalsIgnoreCase(name)) { - Requirement newRequirement = requirement.clone(); - newRequirement.setValue(value); - return newRequirement; - } - } - return null; - } - - public Set getRequirements(Iterable list) { - Set requirements = new HashSet<>(); - - for (String req : list) { - String[] parts = req.split(" ", 2); - if (parts.length < 2) { - throw new IllegalArgumentException("For requirement: '" + req + "'. Requirements must contain a space between" + - " the name of the requirement and the value of the requirement. If it already looks like it has a space, " + - "make sure it is not a tab or has an invisible character."); - } - - String name = parts[0]; - String value = parts[1]; - Requirement requirement = newRequirement(name, value); - Objects.requireNonNull(requirement, name.equalsIgnoreCase("money") ? "The 'money' requirement is being used but no economy is found" : "Unknown requirement: " + name); - requirements.add(requirement); - } - return requirements; - } -} +package sh.okx.rankup.requirements; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +public class RequirementRegistry { + private Set requirements = new HashSet<>(); + + public void addRequirement(Requirement requirement) { + requirements.add(requirement); + } + + public void addRequirements(Requirement... requirements) { + Collections.addAll(this.requirements, requirements); + } + + public Requirement newRequirement(String name, String value) { + for (Requirement requirement : requirements) { + if (requirement.getName().equalsIgnoreCase(name)) { + Requirement newRequirement = requirement.clone(); + newRequirement.setValue(value); + return newRequirement; + } + } + return null; + } + + public Set getRequirements(Iterable list) { + Set requirements = new HashSet<>(); + + for (String req : list) { + String[] parts = req.split(" ", 2); + if (parts.length < 2) { + throw new IllegalArgumentException("For requirement: '" + req + "'. Requirements must contain a space between" + + " the name of the requirement and the value of the requirement. If it already looks like it has a space, " + + "make sure it is not a tab or has an invisible character."); + } + + String name = parts[0]; + String value = parts[1]; + Requirement requirement = newRequirement(name, value); + Objects.requireNonNull(requirement, name.equalsIgnoreCase("money") ? "The 'money' requirement is being used but no economy is found" : "Unknown requirement: " + name); + requirements.add(requirement); + } + return requirements; + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/XpLevelDeductibleRequirement.java b/src/main/java/sh/okx/rankup/requirements/XpLevelDeductibleRequirement.java index 14c223c..6da7bbd 100644 --- a/src/main/java/sh/okx/rankup/requirements/XpLevelDeductibleRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/XpLevelDeductibleRequirement.java @@ -1,26 +1,26 @@ -package sh.okx.rankup.requirements; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.requirement.XpLevelRequirement; - -public class XpLevelDeductibleRequirement extends XpLevelRequirement implements DeductibleRequirement { - - public XpLevelDeductibleRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - private XpLevelDeductibleRequirement(XpLevelDeductibleRequirement clone) { - super(clone); - } - - @Override - public void apply(Player player, double multiplier) { - player.setLevel(player.getLevel() - (int) Math.round(getValueInt() * multiplier)); - } - - @Override - public Requirement clone() { - return new XpLevelDeductibleRequirement(this); - } -} +package sh.okx.rankup.requirements; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.requirement.XpLevelRequirement; + +public class XpLevelDeductibleRequirement extends XpLevelRequirement implements DeductibleRequirement { + + public XpLevelDeductibleRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + private XpLevelDeductibleRequirement(XpLevelDeductibleRequirement clone) { + super(clone); + } + + @Override + public void apply(Player player, double multiplier) { + player.setLevel(player.getLevel() - (int) Math.round(getValueInt() * multiplier)); + } + + @Override + public Requirement clone() { + return new XpLevelDeductibleRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/BlockBreakRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/BlockBreakRequirement.java index 5cd2e42..fded98f 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/BlockBreakRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/BlockBreakRequirement.java @@ -1,32 +1,32 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Material; -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class BlockBreakRequirement extends ProgressiveRequirement { - public BlockBreakRequirement(RankupPlugin plugin) { - super(plugin, "block-break", true); - } - - protected BlockBreakRequirement(BlockBreakRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - Material material = Material.matchMaterial(getSub()); - if (material == null || !material.isBlock()) { - throw new IllegalArgumentException("'" + getSub() + "' is not a valid block"); - } - return player.getStatistic(Statistic.MINE_BLOCK, material); - } - - @Override - public Requirement clone() { - return new BlockBreakRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class BlockBreakRequirement extends ProgressiveRequirement { + public BlockBreakRequirement(RankupPlugin plugin) { + super(plugin, "block-break", true); + } + + protected BlockBreakRequirement(BlockBreakRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + Material material = Material.matchMaterial(getSub()); + if (material == null || !material.isBlock()) { + throw new IllegalArgumentException("'" + getSub() + "' is not a valid block"); + } + return player.getStatistic(Statistic.MINE_BLOCK, material); + } + + @Override + public Requirement clone() { + return new BlockBreakRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/CraftItemRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/CraftItemRequirement.java index 5e22e93..9499b16 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/CraftItemRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/CraftItemRequirement.java @@ -1,32 +1,32 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Material; -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class CraftItemRequirement extends ProgressiveRequirement { - public CraftItemRequirement(RankupPlugin plugin) { - super(plugin, "craft-item", true); - } - - protected CraftItemRequirement(CraftItemRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - Material material = Material.matchMaterial(getSub()); - if (material == null) { - throw new IllegalArgumentException("'" + getSub() + "' is not a valid item"); - } - return player.getStatistic(Statistic.CRAFT_ITEM, material); - } - - @Override - public Requirement clone() { - return new CraftItemRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class CraftItemRequirement extends ProgressiveRequirement { + public CraftItemRequirement(RankupPlugin plugin) { + super(plugin, "craft-item", true); + } + + protected CraftItemRequirement(CraftItemRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + Material material = Material.matchMaterial(getSub()); + if (material == null) { + throw new IllegalArgumentException("'" + getSub() + "' is not a valid item"); + } + return player.getStatistic(Statistic.CRAFT_ITEM, material); + } + + @Override + public Requirement clone() { + return new CraftItemRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/GroupRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/GroupRequirement.java index 0f92e19..757fa37 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/GroupRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/GroupRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class GroupRequirement extends Requirement { - public GroupRequirement(RankupPlugin plugin) { - super(plugin, "group"); - } - - protected GroupRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - for (String group : getValuesString()) { - if (plugin.getPermissions().inGroup(player.getUniqueId(), group)) { - return true; - } - } - return false; - } - - @Override - public Requirement clone() { - return new GroupRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class GroupRequirement extends Requirement { + public GroupRequirement(RankupPlugin plugin) { + super(plugin, "group"); + } + + protected GroupRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + for (String group : getValuesString()) { + if (plugin.getPermissions().inGroup(player.getUniqueId(), group)) { + return true; + } + } + return false; + } + + @Override + public Requirement clone() { + return new GroupRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/ItemDeductibleRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/ItemDeductibleRequirement.java index a54f11a..2168421 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/ItemDeductibleRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/ItemDeductibleRequirement.java @@ -1,49 +1,49 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.DeductibleRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class ItemDeductibleRequirement extends ItemRequirement implements DeductibleRequirement { - - public ItemDeductibleRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - public ItemDeductibleRequirement(ItemDeductibleRequirement clone) { - super(clone); - } - - @Override - public void apply(Player player, double multiplier) { - int count = (int) (getTotal(player) * multiplier); - - ItemStack[] contents = player.getInventory().getStorageContents(); - for (int i = 0; i < contents.length && count > 0; i++) { - ItemStack item = contents[i]; - - if (matchItem(item)) { - if (count < item.getAmount()) { - item.setAmount(item.getAmount() - count); - count = 0; - } else { - count -= item.getAmount(); - contents[i] = null; - } - } - } - - player.getInventory().setStorageContents(contents); - - if (count > 0) { - throw new IllegalStateException("REPORT THIS ERROR TO THE DEV - COULD NOT DEDUCT ALL ITEMS"); - } - } - - @Override - public Requirement clone() { - return new ItemDeductibleRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.DeductibleRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class ItemDeductibleRequirement extends ItemRequirement implements DeductibleRequirement { + + public ItemDeductibleRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + public ItemDeductibleRequirement(ItemDeductibleRequirement clone) { + super(clone); + } + + @Override + public void apply(Player player, double multiplier) { + int count = (int) (getTotal(player) * multiplier); + + ItemStack[] contents = player.getInventory().getStorageContents(); + for (int i = 0; i < contents.length && count > 0; i++) { + ItemStack item = contents[i]; + + if (matchItem(item)) { + if (count < item.getAmount()) { + item.setAmount(item.getAmount() - count); + count = 0; + } else { + count -= item.getAmount(); + contents[i] = null; + } + } + } + + player.getInventory().setStorageContents(contents); + + if (count > 0) { + throw new IllegalStateException("REPORT THIS ERROR TO THE DEV - COULD NOT DEDUCT ALL ITEMS"); + } + } + + @Override + public Requirement clone() { + return new ItemDeductibleRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/ItemRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/ItemRequirement.java index ad6c361..cbd9748 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/ItemRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/ItemRequirement.java @@ -1,62 +1,62 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -import java.util.Arrays; - -public class ItemRequirement extends ProgressiveRequirement { - public ItemRequirement(RankupPlugin plugin, String name) { - super(plugin, name, true); - } - - protected ItemRequirement(ItemRequirement clone) { - super(clone); - } - - @Override - public Requirement clone() { - return new ItemRequirement(this); - } - - @Override - public double getProgress(Player player) { - return Arrays.stream(player.getInventory().getStorageContents()) - .filter(this::matchItem) - .mapToInt(ItemStack::getAmount).sum(); - } - - @SuppressWarnings("deprecation") - protected boolean matchItem(ItemStack item) { - if (item == null) { - return false; - } - - String sub = getSub(); - String[] parts = sub.split(":"); - - Material material = Material.matchMaterial(parts[0]); - if (material == null) { - throw new IllegalArgumentException("[item requirement] could not find material name: " + parts[0]); - } - - if (parts.length > 1) { - int durability; - try { - durability = Integer.parseInt(parts[1]); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("[item requirement] durability '" + parts[1] + "' must be a number in item: '" + sub + "'"); - } - - if (durability != item.getDurability()) { - return false; - } - } - - return material == item.getType(); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +import java.util.Arrays; + +public class ItemRequirement extends ProgressiveRequirement { + public ItemRequirement(RankupPlugin plugin, String name) { + super(plugin, name, true); + } + + protected ItemRequirement(ItemRequirement clone) { + super(clone); + } + + @Override + public Requirement clone() { + return new ItemRequirement(this); + } + + @Override + public double getProgress(Player player) { + return Arrays.stream(player.getInventory().getStorageContents()) + .filter(this::matchItem) + .mapToInt(ItemStack::getAmount).sum(); + } + + @SuppressWarnings("deprecation") + protected boolean matchItem(ItemStack item) { + if (item == null) { + return false; + } + + String sub = getSub(); + String[] parts = sub.split(":"); + + Material material = Material.matchMaterial(parts[0]); + if (material == null) { + throw new IllegalArgumentException("[item requirement] could not find material name: " + parts[0]); + } + + if (parts.length > 1) { + int durability; + try { + durability = Integer.parseInt(parts[1]); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("[item requirement] durability '" + parts[1] + "' must be a number in item: '" + sub + "'"); + } + + if (durability != item.getDurability()) { + return false; + } + } + + return material == item.getType(); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/MobKillsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/MobKillsRequirement.java index 6b26e09..77ef457 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/MobKillsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/MobKillsRequirement.java @@ -1,32 +1,32 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Statistic; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -import java.util.Objects; - -public class MobKillsRequirement extends ProgressiveRequirement { - public MobKillsRequirement(RankupPlugin plugin) { - super(plugin, "mob-kills", true); - } - - protected MobKillsRequirement(Requirement clone) { - super(clone); - } - - @SuppressWarnings("deprecation") - @Override - public double getProgress(Player player) { - EntityType entity = Objects.requireNonNull(EntityType.fromName(getSub()), "Invalid entity type '" + getSub() + "' in mob-kills requirement."); - return player.getStatistic(Statistic.KILL_ENTITY, entity); - } - - @Override - public Requirement clone() { - return new MobKillsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +import java.util.Objects; + +public class MobKillsRequirement extends ProgressiveRequirement { + public MobKillsRequirement(RankupPlugin plugin) { + super(plugin, "mob-kills", true); + } + + protected MobKillsRequirement(Requirement clone) { + super(clone); + } + + @SuppressWarnings("deprecation") + @Override + public double getProgress(Player player) { + EntityType entity = Objects.requireNonNull(EntityType.fromName(getSub()), "Invalid entity type '" + getSub() + "' in mob-kills requirement."); + return player.getStatistic(Statistic.KILL_ENTITY, entity); + } + + @Override + public Requirement clone() { + return new MobKillsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/MoneyDeductibleRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/MoneyDeductibleRequirement.java index c04116a..beca336 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/MoneyDeductibleRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/MoneyDeductibleRequirement.java @@ -1,29 +1,29 @@ -package sh.okx.rankup.requirements.requirement; - -import net.milkbowl.vault.economy.Economy; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.DeductibleRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class MoneyDeductibleRequirement extends MoneyRequirement implements DeductibleRequirement { - - public MoneyDeductibleRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - protected MoneyDeductibleRequirement(MoneyDeductibleRequirement clone) { - super(clone); - } - - @Override - public void apply(Player player, double multiplier) { - Economy economy = plugin.getEconomy(); - economy.withdrawPlayer(player, getValueDouble() * multiplier); - } - - @Override - public Requirement clone() { - return new MoneyDeductibleRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import net.milkbowl.vault.economy.Economy; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.DeductibleRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class MoneyDeductibleRequirement extends MoneyRequirement implements DeductibleRequirement { + + public MoneyDeductibleRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + protected MoneyDeductibleRequirement(MoneyDeductibleRequirement clone) { + super(clone); + } + + @Override + public void apply(Player player, double multiplier) { + Economy economy = plugin.getEconomy(); + economy.withdrawPlayer(player, getValueDouble() * multiplier); + } + + @Override + public Requirement clone() { + return new MoneyDeductibleRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/MoneyRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/MoneyRequirement.java index e31fee4..7c741ad 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/MoneyRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/MoneyRequirement.java @@ -1,26 +1,26 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class MoneyRequirement extends ProgressiveRequirement { - public MoneyRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - protected MoneyRequirement(MoneyRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return plugin.getEconomy().getBalance(player); - } - - @Override - public Requirement clone() { - return new MoneyRequirement(this); - } +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class MoneyRequirement extends ProgressiveRequirement { + public MoneyRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + protected MoneyRequirement(MoneyRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return plugin.getEconomy().getBalance(player); + } + + @Override + public Requirement clone() { + return new MoneyRequirement(this); + } } \ No newline at end of file diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/PermissionRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/PermissionRequirement.java index 1e79dcc..5546af6 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/PermissionRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/PermissionRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class PermissionRequirement extends Requirement { - public PermissionRequirement(RankupPlugin plugin) { - super(plugin, "permission"); - } - - protected PermissionRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - for (String permission : getValuesString()) { - if (player.hasPermission(permission)) { - return true; - } - } - return false; - } - - @Override - public Requirement clone() { - return new PermissionRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class PermissionRequirement extends Requirement { + public PermissionRequirement(RankupPlugin plugin) { + super(plugin, "permission"); + } + + protected PermissionRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + for (String permission : getValuesString()) { + if (player.hasPermission(permission)) { + return true; + } + } + return false; + } + + @Override + public Requirement clone() { + return new PermissionRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/PlaceholderRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/PlaceholderRequirement.java index d312721..6c9ea63 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/PlaceholderRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/PlaceholderRequirement.java @@ -1,90 +1,90 @@ -package sh.okx.rankup.requirements.requirement; - -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class PlaceholderRequirement extends ProgressiveRequirement { - - public static final double DELTA = 0.00001D; - - public PlaceholderRequirement(RankupPlugin plugin) { - super(plugin, "placeholder"); - } - - public PlaceholderRequirement(PlaceholderRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - String[] parts = getParts(player); - String parsed = parts[0]; - String value = parts[2]; - - // string operations - switch (parts[1]) { - case "=": - return parsed.equals(value) ? 1 : 0; - } - - // numeric operations - double p = Double.parseDouble(parsed); - double v = Double.parseDouble(value); - switch (parts[1]) { - case ">": - return p > v ? v : 0; - case ">=": - return Math.min(p, v); - case "<": - return p < v ? v : 0; - case "<=": - return p <= v ? 1 : 0; - case "==": - return p == v ? v : 0; - } - throw new IllegalArgumentException("Invalid operation: " + parts[1]); - } - - @Override - public double getTotal(Player player) { - String[] parts = getParts(player); - - if (parts[1].equalsIgnoreCase("=")) { - return 1; - } else { - return Double.parseDouble(parts[2]); - } - } - - private String[] getParts(Player player) { - String[] parts = getValueString().split(" "); - if (parts.length < 3) { - throw new IllegalArgumentException("Placeholder requirements must be in the form %placeholder% string"); - } - String parsed = PlaceholderAPI.setPlaceholders(player, parts[0]); - if (!PlaceholderAPI.containsPlaceholders(parts[0]) || parsed.equals(parts[0])) { - throw new IllegalArgumentException(parts[0] + " is not a PlaceholderAPI placeholder!"); - } - parts[0] = parsed; - return parts; - } - - @Override - public String getFullName() { - String[] parts = getValueString().split(" "); - return name + "#" + parts[0].replace("%", ""); - } - - @Override - public boolean check(Player player) { - return getRemaining(player) <= 0; - } - - @Override - public Requirement clone() { - return new PlaceholderRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class PlaceholderRequirement extends ProgressiveRequirement { + + public static final double DELTA = 0.00001D; + + public PlaceholderRequirement(RankupPlugin plugin) { + super(plugin, "placeholder"); + } + + public PlaceholderRequirement(PlaceholderRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + String[] parts = getParts(player); + String parsed = parts[0]; + String value = parts[2]; + + // string operations + switch (parts[1]) { + case "=": + return parsed.equals(value) ? 1 : 0; + } + + // numeric operations + double p = Double.parseDouble(parsed); + double v = Double.parseDouble(value); + switch (parts[1]) { + case ">": + return p > v ? v : 0; + case ">=": + return Math.min(p, v); + case "<": + return p < v ? v : 0; + case "<=": + return p <= v ? 1 : 0; + case "==": + return p == v ? v : 0; + } + throw new IllegalArgumentException("Invalid operation: " + parts[1]); + } + + @Override + public double getTotal(Player player) { + String[] parts = getParts(player); + + if (parts[1].equalsIgnoreCase("=")) { + return 1; + } else { + return Double.parseDouble(parts[2]); + } + } + + private String[] getParts(Player player) { + String[] parts = getValueString().split(" "); + if (parts.length < 3) { + throw new IllegalArgumentException("Placeholder requirements must be in the form %placeholder% string"); + } + String parsed = PlaceholderAPI.setPlaceholders(player, parts[0]); + if (!PlaceholderAPI.containsPlaceholders(parts[0]) || parsed.equals(parts[0])) { + throw new IllegalArgumentException(parts[0] + " is not a PlaceholderAPI placeholder!"); + } + parts[0] = parsed; + return parts; + } + + @Override + public String getFullName() { + String[] parts = getValueString().split(" "); + return name + "#" + parts[0].replace("%", ""); + } + + @Override + public boolean check(Player player) { + return getRemaining(player) <= 0; + } + + @Override + public Requirement clone() { + return new PlaceholderRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/PlayerKillsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/PlayerKillsRequirement.java index dc3ba3c..d53adf7 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/PlayerKillsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/PlayerKillsRequirement.java @@ -1,27 +1,27 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class PlayerKillsRequirement extends ProgressiveRequirement { - public PlayerKillsRequirement(RankupPlugin plugin) { - super(plugin, "player-kills"); - } - - protected PlayerKillsRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return player.getStatistic(Statistic.PLAYER_KILLS); - } - - @Override - public Requirement clone() { - return new PlayerKillsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class PlayerKillsRequirement extends ProgressiveRequirement { + public PlayerKillsRequirement(RankupPlugin plugin) { + super(plugin, "player-kills"); + } + + protected PlayerKillsRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return player.getStatistic(Statistic.PLAYER_KILLS); + } + + @Override + public Requirement clone() { + return new PlayerKillsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/PlaytimeMinutesRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/PlaytimeMinutesRequirement.java index 3e8f727..e802c20 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/PlaytimeMinutesRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/PlaytimeMinutesRequirement.java @@ -1,37 +1,37 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class PlaytimeMinutesRequirement extends ProgressiveRequirement { - private static final int TICKS_PER_MINUTE = 20 * 60; - private Statistic playOneTick; - - public PlaytimeMinutesRequirement(RankupPlugin plugin) { - super(plugin, "playtime-minutes"); - try { - playOneTick = Statistic.valueOf("PLAY_ONE_MINUTE"); - } catch (IllegalArgumentException e) { - // statistic was changed in 1.13. - playOneTick = Statistic.valueOf("PLAY_ONE_TICK"); - } - } - - protected PlaytimeMinutesRequirement(PlaytimeMinutesRequirement clone) { - super(clone); - this.playOneTick = clone.playOneTick; - } - - @Override - public double getProgress(Player player) { - return player.getStatistic(playOneTick) / TICKS_PER_MINUTE; - } - - @Override - public Requirement clone() { - return new PlaytimeMinutesRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class PlaytimeMinutesRequirement extends ProgressiveRequirement { + private static final int TICKS_PER_MINUTE = 20 * 60; + private Statistic playOneTick; + + public PlaytimeMinutesRequirement(RankupPlugin plugin) { + super(plugin, "playtime-minutes"); + try { + playOneTick = Statistic.valueOf("PLAY_ONE_MINUTE"); + } catch (IllegalArgumentException e) { + // statistic was changed in 1.13. + playOneTick = Statistic.valueOf("PLAY_ONE_TICK"); + } + } + + protected PlaytimeMinutesRequirement(PlaytimeMinutesRequirement clone) { + super(clone); + this.playOneTick = clone.playOneTick; + } + + @Override + public double getProgress(Player player) { + return player.getStatistic(playOneTick) / TICKS_PER_MINUTE; + } + + @Override + public Requirement clone() { + return new PlaytimeMinutesRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/TokensDeductibleRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/TokensDeductibleRequirement.java index 33f1e4f..364526a 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/TokensDeductibleRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/TokensDeductibleRequirement.java @@ -1,26 +1,26 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.DeductibleRequirement; -import sh.okx.rankup.requirements.requirement.tokenmanager.TokensRequirement; - -public class TokensDeductibleRequirement extends TokensRequirement implements DeductibleRequirement { - public TokensDeductibleRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - protected TokensDeductibleRequirement(TokensDeductibleRequirement clone) { - super(clone); - } - - @Override - public void apply(Player player, double multiplier) { - manager.removeTokens(player, (long) (getValueInt() * multiplier)); - } - - @Override - public TokensRequirement clone() { - return new TokensDeductibleRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.DeductibleRequirement; +import sh.okx.rankup.requirements.requirement.tokenmanager.TokensRequirement; + +public class TokensDeductibleRequirement extends TokensRequirement implements DeductibleRequirement { + public TokensDeductibleRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + protected TokensDeductibleRequirement(TokensDeductibleRequirement clone) { + super(clone); + } + + @Override + public void apply(Player player, double multiplier) { + manager.removeTokens(player, (long) (getValueInt() * multiplier)); + } + + @Override + public TokensRequirement clone() { + return new TokensDeductibleRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/TotalMobKillsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/TotalMobKillsRequirement.java index 4862246..1d634aa 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/TotalMobKillsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/TotalMobKillsRequirement.java @@ -1,27 +1,27 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class TotalMobKillsRequirement extends ProgressiveRequirement { - public TotalMobKillsRequirement(RankupPlugin plugin) { - super(plugin, "total-mob-kills"); - } - - private TotalMobKillsRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return player.getStatistic(Statistic.MOB_KILLS); - } - - @Override - public Requirement clone() { - return new TotalMobKillsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class TotalMobKillsRequirement extends ProgressiveRequirement { + public TotalMobKillsRequirement(RankupPlugin plugin) { + super(plugin, "total-mob-kills"); + } + + private TotalMobKillsRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return player.getStatistic(Statistic.MOB_KILLS); + } + + @Override + public Requirement clone() { + return new TotalMobKillsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/UseItemRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/UseItemRequirement.java index 9d071b9..54d2c7c 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/UseItemRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/UseItemRequirement.java @@ -1,32 +1,32 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.Material; -import org.bukkit.Statistic; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class UseItemRequirement extends ProgressiveRequirement { - public UseItemRequirement(RankupPlugin plugin) { - super(plugin, "use-item", true); - } - - protected UseItemRequirement(UseItemRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - Material material = Material.matchMaterial(getSub()); - if (material == null) { - throw new IllegalArgumentException("'" + getSub() + "' is not a valid item"); - } - return player.getStatistic(Statistic.USE_ITEM, material); - } - - @Override - public Requirement clone() { - return new UseItemRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class UseItemRequirement extends ProgressiveRequirement { + public UseItemRequirement(RankupPlugin plugin) { + super(plugin, "use-item", true); + } + + protected UseItemRequirement(UseItemRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + Material material = Material.matchMaterial(getSub()); + if (material == null) { + throw new IllegalArgumentException("'" + getSub() + "' is not a valid item"); + } + return player.getStatistic(Statistic.USE_ITEM, material); + } + + @Override + public Requirement clone() { + return new UseItemRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/WorldRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/WorldRequirement.java index 211319c..db82229 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/WorldRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/WorldRequirement.java @@ -1,29 +1,29 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class WorldRequirement extends Requirement { - public WorldRequirement(RankupPlugin plugin) { - super(plugin, "world"); - } - - protected WorldRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - String[] worlds = getValuesString(); - for (String world : worlds) { - return player.getWorld().getName().equalsIgnoreCase(world); - } - return false; - } - - @Override - public Requirement clone() { - return new WorldRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class WorldRequirement extends Requirement { + public WorldRequirement(RankupPlugin plugin) { + super(plugin, "world"); + } + + protected WorldRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + String[] worlds = getValuesString(); + for (String world : worlds) { + return player.getWorld().getName().equalsIgnoreCase(world); + } + return false; + } + + @Override + public Requirement clone() { + return new WorldRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/XpLevelRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/XpLevelRequirement.java index 377e812..8122a00 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/XpLevelRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/XpLevelRequirement.java @@ -1,26 +1,26 @@ -package sh.okx.rankup.requirements.requirement; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class XpLevelRequirement extends ProgressiveRequirement { - public XpLevelRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - protected XpLevelRequirement(XpLevelRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return player.getLevel(); - } - - @Override - public Requirement clone() { - return new XpLevelRequirement(this); - } +package sh.okx.rankup.requirements.requirement; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class XpLevelRequirement extends ProgressiveRequirement { + public XpLevelRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + protected XpLevelRequirement(XpLevelRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return player.getLevel(); + } + + @Override + public Requirement clone() { + return new XpLevelRequirement(this); + } } \ No newline at end of file diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsAchievementRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsAchievementRequirement.java index 0f2ca6d..5e7f8bd 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsAchievementRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsAchievementRequirement.java @@ -1,38 +1,38 @@ -package sh.okx.rankup.requirements.requirement.advancedachievements; - -import com.hm.achievement.api.AdvancedAchievementsAPI; -import com.hm.achievement.api.AdvancedAchievementsAPIFetcher; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class AdvancedAchievementsAchievementRequirement extends Requirement { - public AdvancedAchievementsAchievementRequirement(RankupPlugin plugin) { - super(plugin, "advancedachievements-achievement"); - } - - protected AdvancedAchievementsAchievementRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - AdvancedAchievementsAPI api = AdvancedAchievementsAPIFetcher.fetchInstance().get(); - return api.hasPlayerReceivedAchievement(player.getUniqueId(), getValueString()); - } - - @Override - public String getFullName() { - return super.getFullName() + "#" + getValueString(); - } - - @Override - public double getTotal(Player player) { - return 1; - } - - @Override - public Requirement clone() { - return new AdvancedAchievementsAchievementRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.advancedachievements; + +import com.hm.achievement.api.AdvancedAchievementsAPI; +import com.hm.achievement.api.AdvancedAchievementsAPIFetcher; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class AdvancedAchievementsAchievementRequirement extends Requirement { + public AdvancedAchievementsAchievementRequirement(RankupPlugin plugin) { + super(plugin, "advancedachievements-achievement"); + } + + protected AdvancedAchievementsAchievementRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + AdvancedAchievementsAPI api = AdvancedAchievementsAPIFetcher.fetchInstance().get(); + return api.hasPlayerReceivedAchievement(player.getUniqueId(), getValueString()); + } + + @Override + public String getFullName() { + return super.getFullName() + "#" + getValueString(); + } + + @Override + public double getTotal(Player player) { + return 1; + } + + @Override + public Requirement clone() { + return new AdvancedAchievementsAchievementRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsTotalRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsTotalRequirement.java index 807a417..efbc2ea 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsTotalRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/advancedachievements/AdvancedAchievementsTotalRequirement.java @@ -1,27 +1,27 @@ -package sh.okx.rankup.requirements.requirement.advancedachievements; - -import com.hm.achievement.api.AdvancedAchievementsAPIFetcher; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.ProgressiveRequirement; - -public class AdvancedAchievementsTotalRequirement extends ProgressiveRequirement { - public AdvancedAchievementsTotalRequirement(RankupPlugin plugin) { - super(plugin, "advancedachievements-total"); - } - - private AdvancedAchievementsTotalRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return AdvancedAchievementsAPIFetcher.fetchInstance().get().getPlayerTotalAchievements(player.getUniqueId()); - } - - @Override - public Requirement clone() { - return new AdvancedAchievementsTotalRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.advancedachievements; + +import com.hm.achievement.api.AdvancedAchievementsAPIFetcher; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.ProgressiveRequirement; + +public class AdvancedAchievementsTotalRequirement extends ProgressiveRequirement { + public AdvancedAchievementsTotalRequirement(RankupPlugin plugin) { + super(plugin, "advancedachievements-total"); + } + + private AdvancedAchievementsTotalRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return AdvancedAchievementsAPIFetcher.fetchInstance().get().getPlayerTotalAchievements(player.getUniqueId()); + } + + @Override + public Requirement clone() { + return new AdvancedAchievementsTotalRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOPowerLevelRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOPowerLevelRequirement.java index 3f050a4..ba752e0 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOPowerLevelRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOPowerLevelRequirement.java @@ -1,27 +1,27 @@ -package sh.okx.rankup.requirements.requirement.mcmmo; - -import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.ProgressiveRequirement; - -public class McMMOPowerLevelRequirement extends ProgressiveRequirement { - public McMMOPowerLevelRequirement(RankupPlugin plugin) { - super(plugin, "mcmmo-power-level"); - } - - protected McMMOPowerLevelRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return UserManager.getPlayer(player).getPowerLevel(); - } - - @Override - public Requirement clone() { - return new McMMOPowerLevelRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.mcmmo; + +import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.ProgressiveRequirement; + +public class McMMOPowerLevelRequirement extends ProgressiveRequirement { + public McMMOPowerLevelRequirement(RankupPlugin plugin) { + super(plugin, "mcmmo-power-level"); + } + + protected McMMOPowerLevelRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return UserManager.getPlayer(player).getPowerLevel(); + } + + @Override + public Requirement clone() { + return new McMMOPowerLevelRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillRequirement.java index 1f4ee27..fc30d63 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillRequirement.java @@ -1,26 +1,26 @@ -package sh.okx.rankup.requirements.requirement.mcmmo; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.ProgressiveRequirement; - -public class McMMOSkillRequirement extends ProgressiveRequirement { - public McMMOSkillRequirement(RankupPlugin plugin) { - super(plugin, "mcmmo", true); - } - - protected McMMOSkillRequirement(McMMOSkillRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return McMMOSkillUtil.getInstance().getSkillLevel(player, getSub()); - } - - @Override - public Requirement clone() { - return new McMMOSkillRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.mcmmo; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.ProgressiveRequirement; + +public class McMMOSkillRequirement extends ProgressiveRequirement { + public McMMOSkillRequirement(RankupPlugin plugin) { + super(plugin, "mcmmo", true); + } + + protected McMMOSkillRequirement(McMMOSkillRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return McMMOSkillUtil.getInstance().getSkillLevel(player, getSub()); + } + + @Override + public Requirement clone() { + return new McMMOSkillRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillUtil.java b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillUtil.java index 3993537..b792433 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillUtil.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/mcmmo/McMMOSkillUtil.java @@ -1,91 +1,91 @@ -package sh.okx.rankup.requirements.requirement.mcmmo; - -import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Because mcMMO like changing the name of their skill types. - * Singleton class to access different mcMMO versions. - */ -public class McMMOSkillUtil { - private static McMMOSkillUtil instance; - - private Class skillTypeClass; - private Method values; - private Method valueOf; - //private Class userManagerClass; - private Method getSkillLevel; - - private McMMOSkillUtil() { - final String pckg = "com.gmail.nossr50.datatypes.skills."; - try { - skillTypeClass = Class.forName(pckg + "PrimarySkillType"); - } catch (ClassNotFoundException e0) { - try { - skillTypeClass = Class.forName(pckg + "PrimarySkill"); - } catch (ClassNotFoundException e1) { - try { - skillTypeClass = Class.forName(pckg + "SkillType"); - } catch (ClassNotFoundException e2) { - throw new UnsupportedOperationException("mcMMO Skill Type class not found"); - } - } - } - try { - values = skillTypeClass.getMethod("values"); - } catch (NoSuchMethodException e) { - throw new UnsupportedOperationException("mcMMO " + skillTypeClass + ".values() not found"); - } - try { - valueOf = skillTypeClass.getMethod("valueOf", String.class); - } catch (NoSuchMethodException e) { - throw new UnsupportedOperationException("mcMMO" + skillTypeClass + ".valueOf(String) not found"); - } - - /*try { - userManagerClass = Class.forName("com.gmail.nossr50.util.player.UserManager"); - } catch (ClassNotFoundException e) { - throw new RuntimeException("mcMMO UserManager class not found"); - }*/ - - try { - getSkillLevel = McMMOPlayer.class.getMethod("getSkillLevel", skillTypeClass); - } catch (NoSuchMethodException e) { - throw new UnsupportedOperationException("mcMMO UserManager.getSkillLevel(" + skillTypeClass + ") not found"); - } - } - - public static McMMOSkillUtil getInstance() { - if (instance == null) { - instance = new McMMOSkillUtil(); - } - return instance; - } - - /*public String[] getSkills() { - try { - Enum[] skills = (Enum[]) values.invoke(null); - String[] stringSkills = new String[skills.length]; - for (int i = 0; i < skills.length; i++) { - stringSkills[i] = skills[i].name(); - } - return stringSkills; - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - }*/ - - public int getSkillLevel(Player player, String skill) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - try { - Object skillType = skillTypeClass.cast(valueOf.invoke(null, skill.toUpperCase())); - return (int) getSkillLevel.invoke(mcMMOPlayer, skillType); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } -} +package sh.okx.rankup.requirements.requirement.mcmmo; + +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Because mcMMO like changing the name of their skill types. + * Singleton class to access different mcMMO versions. + */ +public class McMMOSkillUtil { + private static McMMOSkillUtil instance; + + private Class skillTypeClass; + private Method values; + private Method valueOf; + //private Class userManagerClass; + private Method getSkillLevel; + + private McMMOSkillUtil() { + final String pckg = "com.gmail.nossr50.datatypes.skills."; + try { + skillTypeClass = Class.forName(pckg + "PrimarySkillType"); + } catch (ClassNotFoundException e0) { + try { + skillTypeClass = Class.forName(pckg + "PrimarySkill"); + } catch (ClassNotFoundException e1) { + try { + skillTypeClass = Class.forName(pckg + "SkillType"); + } catch (ClassNotFoundException e2) { + throw new UnsupportedOperationException("mcMMO Skill Type class not found"); + } + } + } + try { + values = skillTypeClass.getMethod("values"); + } catch (NoSuchMethodException e) { + throw new UnsupportedOperationException("mcMMO " + skillTypeClass + ".values() not found"); + } + try { + valueOf = skillTypeClass.getMethod("valueOf", String.class); + } catch (NoSuchMethodException e) { + throw new UnsupportedOperationException("mcMMO" + skillTypeClass + ".valueOf(String) not found"); + } + + /*try { + userManagerClass = Class.forName("com.gmail.nossr50.util.player.UserManager"); + } catch (ClassNotFoundException e) { + throw new RuntimeException("mcMMO UserManager class not found"); + }*/ + + try { + getSkillLevel = McMMOPlayer.class.getMethod("getSkillLevel", skillTypeClass); + } catch (NoSuchMethodException e) { + throw new UnsupportedOperationException("mcMMO UserManager.getSkillLevel(" + skillTypeClass + ") not found"); + } + } + + public static McMMOSkillUtil getInstance() { + if (instance == null) { + instance = new McMMOSkillUtil(); + } + return instance; + } + + /*public String[] getSkills() { + try { + Enum[] skills = (Enum[]) values.invoke(null); + String[] stringSkills = new String[skills.length]; + for (int i = 0; i < skills.length; i++) { + stringSkills[i] = skills[i].name(); + } + return stringSkills; + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }*/ + + public int getSkillLevel(Player player, String skill) { + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + try { + Object skillType = skillTypeClass.cast(valueOf.invoke(null, skill.toUpperCase())); + return (int) getSkillLevel.invoke(mcMMOPlayer, skillType); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/tokenmanager/TokensRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/tokenmanager/TokensRequirement.java index 2b3200d..0e42df5 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/tokenmanager/TokensRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/tokenmanager/TokensRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement.tokenmanager; - -import java.util.Objects; -import me.realized.tokenmanager.api.TokenManager; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; - -public class TokensRequirement extends ProgressiveRequirement { - protected final TokenManager manager = (TokenManager) Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("TokenManager")); - - public TokensRequirement(RankupPlugin plugin, String name) { - super(plugin, name); - } - - protected TokensRequirement(TokensRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return manager.getTokens(player).orElse(0); - } - - @Override - public TokensRequirement clone() { - return new TokensRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.tokenmanager; + +import java.util.Objects; +import me.realized.tokenmanager.api.TokenManager; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; + +public class TokensRequirement extends ProgressiveRequirement { + protected final TokenManager manager = (TokenManager) Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("TokenManager")); + + public TokensRequirement(RankupPlugin plugin, String name) { + super(plugin, name); + } + + protected TokensRequirement(TokensRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return manager.getTokens(player).orElse(0); + } + + @Override + public TokensRequirement clone() { + return new TokensRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberResidentsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberResidentsRequirement.java index ac6e441..d6a04c1 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberResidentsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberResidentsRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class TownyKingNumberResidentsRequirement extends ProgressiveRequirement { - public TownyKingNumberResidentsRequirement(RankupPlugin plugin) { - super(plugin, "towny-king-residents"); - } - - protected TownyKingNumberResidentsRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - if (TownyUtils.getInstance().isKing(player)) { - return TownyUtils.getInstance().getNation(player).getNumResidents(); - } else { - return 0; - } - } - - @Override - public Requirement clone() { - return new TownyKingNumberResidentsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class TownyKingNumberResidentsRequirement extends ProgressiveRequirement { + public TownyKingNumberResidentsRequirement(RankupPlugin plugin) { + super(plugin, "towny-king-residents"); + } + + protected TownyKingNumberResidentsRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + if (TownyUtils.getInstance().isKing(player)) { + return TownyUtils.getInstance().getNation(player).getNumResidents(); + } else { + return 0; + } + } + + @Override + public Requirement clone() { + return new TownyKingNumberResidentsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberTownsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberTownsRequirement.java index b84b7f6..e31c173 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberTownsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingNumberTownsRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class TownyKingNumberTownsRequirement extends ProgressiveRequirement { - public TownyKingNumberTownsRequirement(RankupPlugin plugin) { - super(plugin, "towny-king-towns"); - } - - protected TownyKingNumberTownsRequirement(TownyKingNumberTownsRequirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - if (TownyUtils.getInstance().isKing(player)) { - return TownyUtils.getInstance().getNation(player).getNumTowns(); - } else { - return 0; - } - } - - @Override - public Requirement clone() { - return new TownyKingNumberTownsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class TownyKingNumberTownsRequirement extends ProgressiveRequirement { + public TownyKingNumberTownsRequirement(RankupPlugin plugin) { + super(plugin, "towny-king-towns"); + } + + protected TownyKingNumberTownsRequirement(TownyKingNumberTownsRequirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + if (TownyUtils.getInstance().isKing(player)) { + return TownyUtils.getInstance().getNation(player).getNumTowns(); + } else { + return 0; + } + } + + @Override + public Requirement clone() { + return new TownyKingNumberTownsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingRequirement.java index ae14753..4161433 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyKingRequirement.java @@ -1,25 +1,25 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class TownyKingRequirement extends Requirement { - public TownyKingRequirement(RankupPlugin plugin) { - super(plugin, "towny-king"); - } - - protected TownyKingRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - return TownyUtils.getInstance().isKing(player) == getValueBoolean(); - } - - @Override - public Requirement clone() { - return new TownyKingRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class TownyKingRequirement extends Requirement { + public TownyKingRequirement(RankupPlugin plugin) { + super(plugin, "towny-king"); + } + + protected TownyKingRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + return TownyUtils.getInstance().isKing(player) == getValueBoolean(); + } + + @Override + public Requirement clone() { + return new TownyKingRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorNumberResidentsRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorNumberResidentsRequirement.java index 9d50364..dcf25de 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorNumberResidentsRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorNumberResidentsRequirement.java @@ -1,30 +1,30 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.ProgressiveRequirement; -import sh.okx.rankup.requirements.Requirement; - -public class TownyMayorNumberResidentsRequirement extends ProgressiveRequirement { - public TownyMayorNumberResidentsRequirement(RankupPlugin plugin) { - super(plugin, "towny-mayor-residents"); - } - - protected TownyMayorNumberResidentsRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - if (TownyUtils.getInstance().isMayor(player)) { - return TownyUtils.getInstance().getTown(player).getNumResidents(); - } else { - return 0; - } - } - - @Override - public Requirement clone() { - return new TownyMayorNumberResidentsRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.ProgressiveRequirement; +import sh.okx.rankup.requirements.Requirement; + +public class TownyMayorNumberResidentsRequirement extends ProgressiveRequirement { + public TownyMayorNumberResidentsRequirement(RankupPlugin plugin) { + super(plugin, "towny-mayor-residents"); + } + + protected TownyMayorNumberResidentsRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + if (TownyUtils.getInstance().isMayor(player)) { + return TownyUtils.getInstance().getTown(player).getNumResidents(); + } else { + return 0; + } + } + + @Override + public Requirement clone() { + return new TownyMayorNumberResidentsRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorRequirement.java index e4d7ee1..722ee95 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyMayorRequirement.java @@ -1,25 +1,25 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class TownyMayorRequirement extends Requirement { - public TownyMayorRequirement(RankupPlugin plugin) { - super(plugin, "towny-mayor"); - } - - protected TownyMayorRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - return TownyUtils.getInstance().isMayor(player) == getValueBoolean(); - } - - @Override - public Requirement clone() { - return new TownyMayorRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class TownyMayorRequirement extends Requirement { + public TownyMayorRequirement(RankupPlugin plugin) { + super(plugin, "towny-mayor"); + } + + protected TownyMayorRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + return TownyUtils.getInstance().isMayor(player) == getValueBoolean(); + } + + @Override + public Requirement clone() { + return new TownyMayorRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyResidentRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyResidentRequirement.java index 42a99bd..f470a5c 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyResidentRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyResidentRequirement.java @@ -1,25 +1,25 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; - -public class TownyResidentRequirement extends Requirement { - public TownyResidentRequirement(RankupPlugin plugin) { - super(plugin, "towny-resident"); - } - - protected TownyResidentRequirement(Requirement clone) { - super(clone); - } - - @Override - public boolean check(Player player) { - return TownyUtils.getInstance().isResident(player) == getValueBoolean(); - } - - @Override - public Requirement clone() { - return new TownyResidentRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; + +public class TownyResidentRequirement extends Requirement { + public TownyResidentRequirement(RankupPlugin plugin) { + super(plugin, "towny-resident"); + } + + protected TownyResidentRequirement(Requirement clone) { + super(clone); + } + + @Override + public boolean check(Player player) { + return TownyUtils.getInstance().isResident(player) == getValueBoolean(); + } + + @Override + public Requirement clone() { + return new TownyResidentRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyUtils.java b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyUtils.java index faa09f8..e024aac 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyUtils.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/towny/TownyUtils.java @@ -1,71 +1,71 @@ -package sh.okx.rankup.requirements.requirement.towny; - -import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; -import com.palmergames.bukkit.towny.object.Nation; -import com.palmergames.bukkit.towny.object.Resident; -import com.palmergames.bukkit.towny.object.Town; -import com.palmergames.bukkit.towny.object.TownyUniverse; -import org.bukkit.entity.Player; - -public class TownyUtils { - private static TownyUtils instance; - - public static TownyUtils getInstance() { - if (instance == null) { - instance = new TownyUtils(); - } - return instance; - } - - public boolean isResident(Player player) { - try { - Town town = TownyUniverse.getDataSource().getResident(player.getName()).getTown(); - - return town != null; - } catch (NotRegisteredException e) { - return false; - } - } - - public Resident getResident(Player player) { - try { - return TownyUniverse.getDataSource().getResident(player.getName()); - } catch (NotRegisteredException e) { - return null; - } - } - - public Town getTown(Player player) { - try { - return TownyUniverse.getDataSource().getResident(player.getName()).getTown(); - } catch (NotRegisteredException e) { - return null; - } - } - - public Nation getNation(Player player) { - Town town = getTown(player); - - try { - return getTown(player) == null ? null : town.getNation(); - } catch (NotRegisteredException e) { - return null; - } - } - - public boolean isMayor(Player player) { - try { - return TownyUniverse.getDataSource().getResident(player.getName()).isMayor(); - } catch (NotRegisteredException e) { - return false; - } - } - - public boolean isKing(Player player) { - try { - return TownyUniverse.getDataSource().getResident(player.getName()).isKing(); - } catch (NotRegisteredException e) { - return false; - } - } -} +package sh.okx.rankup.requirements.requirement.towny; + +import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; +import com.palmergames.bukkit.towny.object.Nation; +import com.palmergames.bukkit.towny.object.Resident; +import com.palmergames.bukkit.towny.object.Town; +import com.palmergames.bukkit.towny.object.TownyUniverse; +import org.bukkit.entity.Player; + +public class TownyUtils { + private static TownyUtils instance; + + public static TownyUtils getInstance() { + if (instance == null) { + instance = new TownyUtils(); + } + return instance; + } + + public boolean isResident(Player player) { + try { + Town town = TownyUniverse.getDataSource().getResident(player.getName()).getTown(); + + return town != null; + } catch (NotRegisteredException e) { + return false; + } + } + + public Resident getResident(Player player) { + try { + return TownyUniverse.getDataSource().getResident(player.getName()); + } catch (NotRegisteredException e) { + return null; + } + } + + public Town getTown(Player player) { + try { + return TownyUniverse.getDataSource().getResident(player.getName()).getTown(); + } catch (NotRegisteredException e) { + return null; + } + } + + public Nation getNation(Player player) { + Town town = getTown(player); + + try { + return getTown(player) == null ? null : town.getNation(); + } catch (NotRegisteredException e) { + return null; + } + } + + public boolean isMayor(Player player) { + try { + return TownyUniverse.getDataSource().getResident(player.getName()).isMayor(); + } catch (NotRegisteredException e) { + return false; + } + } + + public boolean isKing(Player player) { + try { + return TownyUniverse.getDataSource().getResident(player.getName()).isKing(); + } catch (NotRegisteredException e) { + return false; + } + } +} diff --git a/src/main/java/sh/okx/rankup/requirements/requirement/votingplugin/VotingPluginVotesRequirement.java b/src/main/java/sh/okx/rankup/requirements/requirement/votingplugin/VotingPluginVotesRequirement.java index a628e7f..bbbd45c 100644 --- a/src/main/java/sh/okx/rankup/requirements/requirement/votingplugin/VotingPluginVotesRequirement.java +++ b/src/main/java/sh/okx/rankup/requirements/requirement/votingplugin/VotingPluginVotesRequirement.java @@ -1,27 +1,27 @@ -package sh.okx.rankup.requirements.requirement.votingplugin; - -import com.Ben12345rocks.VotingPlugin.UserManager.UserManager; -import org.bukkit.entity.Player; -import sh.okx.rankup.RankupPlugin; -import sh.okx.rankup.requirements.Requirement; -import sh.okx.rankup.requirements.ProgressiveRequirement; - -public class VotingPluginVotesRequirement extends ProgressiveRequirement { - public VotingPluginVotesRequirement(RankupPlugin plugin) { - super(plugin, "votingplugin-votes"); - } - - protected VotingPluginVotesRequirement(Requirement clone) { - super(clone); - } - - @Override - public double getProgress(Player player) { - return UserManager.getInstance().getVotingPluginUser(player).getPoints(); - } - - @Override - public Requirement clone() { - return new VotingPluginVotesRequirement(this); - } -} +package sh.okx.rankup.requirements.requirement.votingplugin; + +import com.Ben12345rocks.VotingPlugin.UserManager.UserManager; +import org.bukkit.entity.Player; +import sh.okx.rankup.RankupPlugin; +import sh.okx.rankup.requirements.Requirement; +import sh.okx.rankup.requirements.ProgressiveRequirement; + +public class VotingPluginVotesRequirement extends ProgressiveRequirement { + public VotingPluginVotesRequirement(RankupPlugin plugin) { + super(plugin, "votingplugin-votes"); + } + + protected VotingPluginVotesRequirement(Requirement clone) { + super(clone); + } + + @Override + public double getProgress(Player player) { + return UserManager.getInstance().getVotingPluginUser(player).getPoints(); + } + + @Override + public Requirement clone() { + return new VotingPluginVotesRequirement(this); + } +} diff --git a/src/main/java/sh/okx/rankup/util/ItemUtil.java b/src/main/java/sh/okx/rankup/util/ItemUtil.java index 4130e24..ac16882 100644 --- a/src/main/java/sh/okx/rankup/util/ItemUtil.java +++ b/src/main/java/sh/okx/rankup/util/ItemUtil.java @@ -1,29 +1,29 @@ -package sh.okx.rankup.util; - -import org.bukkit.Material; - -public class ItemUtil { - private static boolean flattened; - - static { - try { - Material.valueOf("BLACK_STAINED_GLASS_PANE"); - flattened = true; - } catch (IllegalArgumentException e) { - flattened = false; - } - } - - /** - * Determines if a server is post-flattening or pre-flattening. - * The flattening is the name for the event where, instead of using durability to represent - * similar items, Mojang decided to use distinct item types for each item. - * This caused many {@link Material} names to change, making some things incompatible. - * The flattening happened in 1.13. - * - * @return true if the server is post-flattening (server versions 1.13, 1.14, 1.15) or false if it is pre-flattening (1.12, 1.11, 1.10 etc) - */ - public static boolean isServerFlattened() { - return flattened; - } -} +package sh.okx.rankup.util; + +import org.bukkit.Material; + +public class ItemUtil { + private static boolean flattened; + + static { + try { + Material.valueOf("BLACK_STAINED_GLASS_PANE"); + flattened = true; + } catch (IllegalArgumentException e) { + flattened = false; + } + } + + /** + * Determines if a server is post-flattening or pre-flattening. + * The flattening is the name for the event where, instead of using durability to represent + * similar items, Mojang decided to use distinct item types for each item. + * This caused many {@link Material} names to change, making some things incompatible. + * The flattening happened in 1.13. + * + * @return true if the server is post-flattening (server versions 1.13, 1.14, 1.15) or false if it is pre-flattening (1.12, 1.11, 1.10 etc) + */ + public static boolean isServerFlattened() { + return flattened; + } +} diff --git a/src/main/java/sh/okx/rankup/util/UpdateNotifier.java b/src/main/java/sh/okx/rankup/util/UpdateNotifier.java index 393403d..2529cf5 100644 --- a/src/main/java/sh/okx/rankup/util/UpdateNotifier.java +++ b/src/main/java/sh/okx/rankup/util/UpdateNotifier.java @@ -1,57 +1,57 @@ -package sh.okx.rankup.util; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import sh.okx.rankup.util.VersionChecker.VersionCheckerCallback; - -public class UpdateNotifier { - private final String prefix; - - private final VersionChecker checker; - - public UpdateNotifier(VersionChecker checker) { - this.prefix = ChatColor.GREEN + "" + ChatColor.BOLD + checker.getPlugin().getName() + ChatColor.RESET + " "; - this.checker = checker; - } - - public void notify(CommandSender sender, boolean join) { - if (!checker.hasChecked() && !join) { - send(sender, false, ChatColor.YELLOW + "Checking version..."); - } - checker.checkVersion(new VersionCheckerCallback() { - @Override - public void onLatestVersion(String version) { - if (!join) { - send(sender, false, ChatColor.GREEN + "You are on the latest version."); - } - } - - @Override - public void onOutdatedVersion(String currentVersion, String latestVersion) { - send(sender, join, ChatColor.YELLOW + "A new version is available: " + ChatColor.GOLD + latestVersion - + ChatColor.YELLOW + ". You are on: " + ChatColor.GOLD + currentVersion - + ChatColor.GOLD + "\nhttps://www.spigotmc.org/resources/" + VersionChecker.RESOURCE_ID + "/"); - } - - @Override - public void onPreReleaseVersion(String version) { - send(sender, join, ChatColor.RED + "You are on a pre-release version."); - } - - @Override - public void onFailure() { - if (!join) { - send(sender, false, ChatColor.RED + "Error while checking version."); - } - } - }); - } - - private void send(CommandSender sender, boolean prefix, String message) { - if (prefix) { - sender.sendMessage(this.prefix + message); - } else { - sender.sendMessage(message); - } - } -} +package sh.okx.rankup.util; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import sh.okx.rankup.util.VersionChecker.VersionCheckerCallback; + +public class UpdateNotifier { + private final String prefix; + + private final VersionChecker checker; + + public UpdateNotifier(VersionChecker checker) { + this.prefix = ChatColor.GREEN + "" + ChatColor.BOLD + checker.getPlugin().getName() + ChatColor.RESET + " "; + this.checker = checker; + } + + public void notify(CommandSender sender, boolean join) { + if (!checker.hasChecked() && !join) { + send(sender, false, ChatColor.YELLOW + "Checking version..."); + } + checker.checkVersion(new VersionCheckerCallback() { + @Override + public void onLatestVersion(String version) { + if (!join) { + send(sender, false, ChatColor.GREEN + "You are on the latest version."); + } + } + + @Override + public void onOutdatedVersion(String currentVersion, String latestVersion) { + send(sender, join, ChatColor.YELLOW + "A new version is available: " + ChatColor.GOLD + latestVersion + + ChatColor.YELLOW + ". You are on: " + ChatColor.GOLD + currentVersion + + ChatColor.GOLD + "\nhttps://www.spigotmc.org/resources/" + VersionChecker.RESOURCE_ID + "/"); + } + + @Override + public void onPreReleaseVersion(String version) { + send(sender, join, ChatColor.RED + "You are on a pre-release version."); + } + + @Override + public void onFailure() { + if (!join) { + send(sender, false, ChatColor.RED + "Error while checking version."); + } + } + }); + } + + private void send(CommandSender sender, boolean prefix, String message) { + if (prefix) { + sender.sendMessage(this.prefix + message); + } else { + sender.sendMessage(message); + } + } +} diff --git a/src/main/java/sh/okx/rankup/util/VersionChecker.java b/src/main/java/sh/okx/rankup/util/VersionChecker.java index b98dcbf..e4d5692 100644 --- a/src/main/java/sh/okx/rankup/util/VersionChecker.java +++ b/src/main/java/sh/okx/rankup/util/VersionChecker.java @@ -1,150 +1,150 @@ -package sh.okx.rankup.util; - -import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - -public class VersionChecker { - public static final int RESOURCE_ID = 76964; - - private final Plugin plugin; - private final String currentVersion; - private String latestVersion; - private boolean checked = false; - - public VersionChecker(Plugin plugin) { - this.currentVersion = plugin.getDescription().getVersion(); - this.plugin = plugin; - } - - public Plugin getPlugin() { - return plugin; - } - - /** - * Checks if the version checker has already made an asynchronous call to the web server to check - * the version, so future checks will run instantly. - * - * @return true if the version checker already knows the latest version, false otherwise - */ - public boolean hasChecked() { - return checked; - } - - public void checkVersion(VersionCheckerCallback callback) { - if (latestVersion != null) { - if (currentVersion.equals(latestVersion)) { - callback.onLatestVersion(currentVersion); - } else { - callback.onOutdatedVersion(currentVersion, latestVersion); - } - } else if (currentVersion.contains("alpha") - || currentVersion.contains("beta") - || currentVersion.contains("rc")) { - checked = true; - callback.onPreReleaseVersion(currentVersion); - } else { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> checkVersionAsync(callback)); - } - } - - private void checkVersionAsync(VersionCheckerCallback callback) { - try { - latestVersion = getLatestVersion(); - checked = true; - if (currentVersion.equals(latestVersion)) { - callback.onLatestVersion(currentVersion); - } else { - callback.onOutdatedVersion(currentVersion, latestVersion); - } - - } catch (IOException e) { - callback.onFailure(); - } - } - - private String getLatestVersion() throws IOException { - URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); - return CharStreams.toString(new InputStreamReader(url.openStream(), Charsets.UTF_8)); - } - - /** - * A callback used when a version check runs - */ - public interface VersionCheckerCallback { - - /** - * Called when the plugin is already on the latest version - * May be called asynchronously - * - * @param version the current, and latest, version of the plugin - */ - void onLatestVersion(String version); - - /** - * Called when the plugin is on a version other than the latest on the SpigotMC plugin page. - * May be called asynchronously. - * - * @param currentVersion the current version of the plugin specified in plugin.yml - * @param latestVersion the latest version of the plugin specified on SpigotMC. - */ - void onOutdatedVersion(String currentVersion, String latestVersion); - - /** - * Called when the plugin is on a pre-release version and is exempt to the usual update system. - * - * @param version the current version of the plugin - */ - void onPreReleaseVersion(String version); - - /** - * Called when the version checker was unable to retrieve the latest version. - * May be called asynchronously. - */ - void onFailure(); - } - - /** - * An implementation of {@link VersionCheckerCallback} that is called asynchronously, and then - * forwards the calls an underlying VersionCheckerCallback synchronously on the main Bukkit - * thread. - */ - static class SyncVersionCheckerCallback implements VersionCheckerCallback { - - private final Plugin plugin; - private final VersionCheckerCallback callback; - - SyncVersionCheckerCallback(Plugin plugin, VersionCheckerCallback callback) { - this.plugin = plugin; - this.callback = callback; - } - - @Override - public void onLatestVersion(String version) { - doSync(() -> callback.onLatestVersion(version)); - } - - @Override - public void onOutdatedVersion(String currentVersion, String latestVersion) { - doSync(() -> callback.onOutdatedVersion(currentVersion, latestVersion)); - } - - @Override - public void onPreReleaseVersion(String version) { - doSync(() -> callback.onPreReleaseVersion(version)); - } - - @Override - public void onFailure() { - doSync(callback::onFailure); - } - - private void doSync(Runnable r) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, r); - } - } -} +package sh.okx.rankup.util; + +import com.google.common.base.Charsets; +import com.google.common.io.CharStreams; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +public class VersionChecker { + public static final int RESOURCE_ID = 76964; + + private final Plugin plugin; + private final String currentVersion; + private String latestVersion; + private boolean checked = false; + + public VersionChecker(Plugin plugin) { + this.currentVersion = plugin.getDescription().getVersion(); + this.plugin = plugin; + } + + public Plugin getPlugin() { + return plugin; + } + + /** + * Checks if the version checker has already made an asynchronous call to the web server to check + * the version, so future checks will run instantly. + * + * @return true if the version checker already knows the latest version, false otherwise + */ + public boolean hasChecked() { + return checked; + } + + public void checkVersion(VersionCheckerCallback callback) { + if (latestVersion != null) { + if (currentVersion.equals(latestVersion)) { + callback.onLatestVersion(currentVersion); + } else { + callback.onOutdatedVersion(currentVersion, latestVersion); + } + } else if (currentVersion.contains("alpha") + || currentVersion.contains("beta") + || currentVersion.contains("rc")) { + checked = true; + callback.onPreReleaseVersion(currentVersion); + } else { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> checkVersionAsync(callback)); + } + } + + private void checkVersionAsync(VersionCheckerCallback callback) { + try { + latestVersion = getLatestVersion(); + checked = true; + if (currentVersion.equals(latestVersion)) { + callback.onLatestVersion(currentVersion); + } else { + callback.onOutdatedVersion(currentVersion, latestVersion); + } + + } catch (IOException e) { + callback.onFailure(); + } + } + + private String getLatestVersion() throws IOException { + URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); + return CharStreams.toString(new InputStreamReader(url.openStream(), Charsets.UTF_8)); + } + + /** + * A callback used when a version check runs + */ + public interface VersionCheckerCallback { + + /** + * Called when the plugin is already on the latest version + * May be called asynchronously + * + * @param version the current, and latest, version of the plugin + */ + void onLatestVersion(String version); + + /** + * Called when the plugin is on a version other than the latest on the SpigotMC plugin page. + * May be called asynchronously. + * + * @param currentVersion the current version of the plugin specified in plugin.yml + * @param latestVersion the latest version of the plugin specified on SpigotMC. + */ + void onOutdatedVersion(String currentVersion, String latestVersion); + + /** + * Called when the plugin is on a pre-release version and is exempt to the usual update system. + * + * @param version the current version of the plugin + */ + void onPreReleaseVersion(String version); + + /** + * Called when the version checker was unable to retrieve the latest version. + * May be called asynchronously. + */ + void onFailure(); + } + + /** + * An implementation of {@link VersionCheckerCallback} that is called asynchronously, and then + * forwards the calls an underlying VersionCheckerCallback synchronously on the main Bukkit + * thread. + */ + static class SyncVersionCheckerCallback implements VersionCheckerCallback { + + private final Plugin plugin; + private final VersionCheckerCallback callback; + + SyncVersionCheckerCallback(Plugin plugin, VersionCheckerCallback callback) { + this.plugin = plugin; + this.callback = callback; + } + + @Override + public void onLatestVersion(String version) { + doSync(() -> callback.onLatestVersion(version)); + } + + @Override + public void onOutdatedVersion(String currentVersion, String latestVersion) { + doSync(() -> callback.onOutdatedVersion(currentVersion, latestVersion)); + } + + @Override + public void onPreReleaseVersion(String version) { + doSync(() -> callback.onPreReleaseVersion(version)); + } + + @Override + public void onFailure() { + doSync(callback::onFailure); + } + + private void doSync(Runnable r) { + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, r); + } + } +} diff --git a/src/main/resources/LICENSE.txt b/src/main/resources/LICENSE.txt index 7d3e802..d567c0e 100644 --- a/src/main/resources/LICENSE.txt +++ b/src/main/resources/LICENSE.txt @@ -1,21 +1,21 @@ -The MIT License (MIT) - -Copyright (c) 2018-2020 Okx - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +The MIT License (MIT) + +Copyright (c) 2018-2020 Okx + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index a9775d1..1944e44 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,92 +1,92 @@ -# this is used for letting you know that you need to update/change your config file -version: 6 - -# the locale to use for messages -# all messages can be customised but this allows you to -# choose messages that are already translated -# locales can be found in the locale/ folder -locale: en - -# interval (in minutes) to check to autorankup players -# ranking up manually wil always be enabled -# set to 0 to disable -autorankup-interval: 0 - -# whether /ranks and /prestiges should be enabled (true) or disabled (false) -# /rankup3 reload will not do anything if this is changed, -# you will have to restart your server. -ranks: true -# you can alternatively negate the permission rankup.prestiges -# this will also make the command not autocomplete in 1.13 -prestiges: true - -# whether or not /prestige and /prestiges should be enabled. -# when a player reaches the top rank, they can do /prestige to return to the first rank, -# but you will be able to grant them an additional "prestige" group or additional items. -# -# if you do not want this command to autocomplete, make sure -# you negate the permission rankup.prestige with your permissions plugin. -# if enabled, a prestiges.yml file will be generated with some example prestiges -# You must restart your server when you change this for it to work! -prestige: false - -# if true, players with the permission rankup.notify will receive notifications when they join -# to update if the server is on an older version of Rankup. -notify-update: true - -# how people should confirm ranking up -# options are: gui, text or none -confirmation-type: 'gui' - -# how long, in seconds, people have to wait between a successful /rankup or /prestige -# set to 0 to disable. -cooldown: 1 - -# if enabled, players can run /maxrankup to rankup as many times as possible, -# before they fail the requirements for the next rank. -# the permission rankup.maxrankup is used for this command, but it is usually given by default. -# note that /maxrankup, if enabled, has no confirmation. -max-rankup: - # You must restart your server if you enable or disable /maxrankup! - enabled: false - # whether to send a message for each rankup a player does - # if set to true, the chat may be spammed for each rankup a player goes through with /maxrankup - # if set to false, only the last rankup will be shown (if a player starts on rank A, then does - # /maxrankup and ranks up to B and then C, it will just say "player has ranked up to C") - individual-messages: true - -# options when using the text rankup confirmation -text: - # the time in seconds for a player to - # confirm by typing /rankup again - timeout: 10 - -# placeholders: -# https://github.com/okx-code/Rankup3/wiki/PAPI-Placeholders -placeholders: - # format for money. for more information, see - # https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html - money-format: "#,##0.##" - percent-format: "0.##" - # the format used for requirements - simple-format: "#.##" - # used for current_rank and next_rank placeholders when a player is not in anything in rankups.yml - not-in-ladder: "None" - # used in the current_prestige placeholders when a player hasn't prestiged yet - no-prestige: "None" - # used in the next_rank and next_prestige placeholders when a player is at the highest rank or prestige - highest-rank: "None" - -# what to shorten money by. -# ie 1000 -> 1k -# set to an empty list to disable -# for each entry here, it counts as increasing by a factor of 1,000 -# the first represents thousands (1,000) then millions (1,000,000) then billions (1,000,000,000) etc. -shorten: -- 'k' -- 'M' -- 'B' -- 'T' -- 'Q' -- 'Qu' +# this is used for letting you know that you need to update/change your config file +version: 6 + +# the locale to use for messages +# all messages can be customised but this allows you to +# choose messages that are already translated +# locales can be found in the locale/ folder +locale: en + +# interval (in minutes) to check to autorankup players +# ranking up manually wil always be enabled +# set to 0 to disable +autorankup-interval: 0 + +# whether /ranks and /prestiges should be enabled (true) or disabled (false) +# /rankup3 reload will not do anything if this is changed, +# you will have to restart your server. +ranks: true +# you can alternatively negate the permission rankup.prestiges +# this will also make the command not autocomplete in 1.13 +prestiges: true + +# whether or not /prestige and /prestiges should be enabled. +# when a player reaches the top rank, they can do /prestige to return to the first rank, +# but you will be able to grant them an additional "prestige" group or additional items. +# +# if you do not want this command to autocomplete, make sure +# you negate the permission rankup.prestige with your permissions plugin. +# if enabled, a prestiges.yml file will be generated with some example prestiges +# You must restart your server when you change this for it to work! +prestige: false + +# if true, players with the permission rankup.notify will receive notifications when they join +# to update if the server is on an older version of Rankup. +notify-update: true + +# how people should confirm ranking up +# options are: gui, text or none +confirmation-type: 'gui' + +# how long, in seconds, people have to wait between a successful /rankup or /prestige +# set to 0 to disable. +cooldown: 1 + +# if enabled, players can run /maxrankup to rankup as many times as possible, +# before they fail the requirements for the next rank. +# the permission rankup.maxrankup is used for this command, but it is usually given by default. +# note that /maxrankup, if enabled, has no confirmation. +max-rankup: + # You must restart your server if you enable or disable /maxrankup! + enabled: false + # whether to send a message for each rankup a player does + # if set to true, the chat may be spammed for each rankup a player goes through with /maxrankup + # if set to false, only the last rankup will be shown (if a player starts on rank A, then does + # /maxrankup and ranks up to B and then C, it will just say "player has ranked up to C") + individual-messages: true + +# options when using the text rankup confirmation +text: + # the time in seconds for a player to + # confirm by typing /rankup again + timeout: 10 + +# placeholders: +# https://github.com/okx-code/Rankup3/wiki/PAPI-Placeholders +placeholders: + # format for money. for more information, see + # https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html + money-format: "#,##0.##" + percent-format: "0.##" + # the format used for requirements + simple-format: "#.##" + # used for current_rank and next_rank placeholders when a player is not in anything in rankups.yml + not-in-ladder: "None" + # used in the current_prestige placeholders when a player hasn't prestiged yet + no-prestige: "None" + # used in the next_rank and next_prestige placeholders when a player is at the highest rank or prestige + highest-rank: "None" + +# what to shorten money by. +# ie 1000 -> 1k +# set to an empty list to disable +# for each entry here, it counts as increasing by a factor of 1,000 +# the first represents thousands (1,000) then millions (1,000,000) then billions (1,000,000,000) etc. +shorten: +- 'k' +- 'M' +- 'B' +- 'T' +- 'Q' +- 'Qu' - 'S' \ No newline at end of file diff --git a/src/main/resources/locale/en.yml b/src/main/resources/locale/en.yml index 6f98eab..cb6c440 100644 --- a/src/main/resources/locale/en.yml +++ b/src/main/resources/locale/en.yml @@ -1,103 +1,103 @@ -# the messages in this section can be customised for each rankup in rankups.yml. -rankup: - requirements-not-met: "&cYou need {MONEY} money to rankup." - no-rankup: "&eYou are at the highest rank." - # set to an empty string, ie: success-public: "" - # to hide that message. - success-public: "&a{PLAYER} &ehas ranked up to: &d{RANK}" - success-private: "&aYou have ranked up to: &d{RANK}" - # used for the text confirmation - confirmation: |- - &eAre you sure you want to rankup to &a{RANK}&e? - &eType &c/rankup &eagain to confirm. - # used for the GUI confirmation - title: "Rankup to {RANK}" - - must-prestige: "&cYou must prestige to /rankup further!" - - gui: - title: "Rankup to {RANK}" - rankup: - material: EMERALD_BLOCK - # index can be separated by spaces to show in multiple groups - # for example: 0-3 9-12 18-21 - # you can also just use a single number instead of a range. - index: 0-3 - name: '&a&lConfirm' - # lore is optional - lore: '&6Rankup to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - # you can (and probably should) you override these in rankups.yml - # to show the specific requirements for each rank. - # however if you are just using money or don't need to change the message per rank, you can use any combination of: - # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } - # {MONEY} and {MONEY_NEEDED} are different from {AMOUNT money} and {AMOUNT_NEEDED money} in that they use a different format. - # here is an example of showing the requirements for just money: - #list: - # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" - # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" - # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - # an empty string disables the header/footer - header: "" - footer: "" - # sent when a player tries to rankup when they are on cooldown - cooldown: - singular: "&cYou must wait {SECONDS_LEFT} more second to rankup again." - plural: "&cYou must wait {SECONDS_LEFT} more seconds to rankup again." -# prestige messages can also be customised -prestige: - requirements-not-met: "&cYou need {MONEY} money to prestige." - no-prestige: "&eYou are at the highest prestige." - - success-public: "&a{PLAYER} &ehas prestiged to: &d{RANK}" - success-private: "&aYou have prestiged to: &d{RANK}" - - confirmation: |- - &eAre you sure you want to prestige to &a{RANK}&e? - &eType &c/prestige &eagain to confirm. - - gui: - title: "Prestige to {RANK}" - rankup: - material: GOLD_BLOCK - index: 0-3 - name: '&a&lConfirm' - lore: '&6Prestige to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - header: "" - footer: "" - cooldown: - singular: "&cYou must wait {SECONDS_LEFT} second to prestige again." - plural: "&cYou must wait {SECONDS_LEFT} more seconds to prestige again." - -not-high-enough: "&cYou cannot prestige at your rank!" -not-in-ladder: "&cSorry, but we could not find any rankups for the group(s) you are in. Use /ranks to list the rankups." +# the messages in this section can be customised for each rankup in rankups.yml. +rankup: + requirements-not-met: "&cYou need {MONEY} money to rankup." + no-rankup: "&eYou are at the highest rank." + # set to an empty string, ie: success-public: "" + # to hide that message. + success-public: "&a{PLAYER} &ehas ranked up to: &d{RANK}" + success-private: "&aYou have ranked up to: &d{RANK}" + # used for the text confirmation + confirmation: |- + &eAre you sure you want to rankup to &a{RANK}&e? + &eType &c/rankup &eagain to confirm. + # used for the GUI confirmation + title: "Rankup to {RANK}" + + must-prestige: "&cYou must prestige to /rankup further!" + + gui: + title: "Rankup to {RANK}" + rankup: + material: EMERALD_BLOCK + # index can be separated by spaces to show in multiple groups + # for example: 0-3 9-12 18-21 + # you can also just use a single number instead of a range. + index: 0-3 + name: '&a&lConfirm' + # lore is optional + lore: '&6Rankup to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + # you can (and probably should) you override these in rankups.yml + # to show the specific requirements for each rank. + # however if you are just using money or don't need to change the message per rank, you can use any combination of: + # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } + # {MONEY} and {MONEY_NEEDED} are different from {AMOUNT money} and {AMOUNT_NEEDED money} in that they use a different format. + # here is an example of showing the requirements for just money: + #list: + # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" + # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" + # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + # an empty string disables the header/footer + header: "" + footer: "" + # sent when a player tries to rankup when they are on cooldown + cooldown: + singular: "&cYou must wait {SECONDS_LEFT} more second to rankup again." + plural: "&cYou must wait {SECONDS_LEFT} more seconds to rankup again." +# prestige messages can also be customised +prestige: + requirements-not-met: "&cYou need {MONEY} money to prestige." + no-prestige: "&eYou are at the highest prestige." + + success-public: "&a{PLAYER} &ehas prestiged to: &d{RANK}" + success-private: "&aYou have prestiged to: &d{RANK}" + + confirmation: |- + &eAre you sure you want to prestige to &a{RANK}&e? + &eType &c/prestige &eagain to confirm. + + gui: + title: "Prestige to {RANK}" + rankup: + material: GOLD_BLOCK + index: 0-3 + name: '&a&lConfirm' + lore: '&6Prestige to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + header: "" + footer: "" + cooldown: + singular: "&cYou must wait {SECONDS_LEFT} second to prestige again." + plural: "&cYou must wait {SECONDS_LEFT} more seconds to prestige again." + +not-high-enough: "&cYou cannot prestige at your rank!" +not-in-ladder: "&cSorry, but we could not find any rankups for the group(s) you are in. Use /ranks to list the rankups." invalid-rankup: "&cInvalid rankup defined in config, please check console." \ No newline at end of file diff --git a/src/main/resources/locale/pt_br.yml b/src/main/resources/locale/pt_br.yml index 578673b..3a3b50a 100644 --- a/src/main/resources/locale/pt_br.yml +++ b/src/main/resources/locale/pt_br.yml @@ -1,107 +1,107 @@ -# As mensagens nessa sessão podem ser customizadas para cada rankup em rankups.yml. -rankup: - requirements-not-met: "&cVocê {MONEY} para poder dar subir de rank." - no-rankup: "&eVocê já está no maior rank." - # coloque como uma String vazia, ex: success-public: "" - # para ocultar a mensagem. - success-public: "&a{PLAYER} &eacaba de subir para: &d{RANK}" - success-private: "&aVocê subiu para: &d{RANK}" - # Utilizado para a confirmação via mensagem. - confirmation: |- - &eVocê tem certeza que deseja subir para &a{RANK}&e? - &eDigite &c/rankup &enovamente para confirmar. - - must-prestige: "&cVocê deve subir de prestígio para dar /rankup a frente!" - - gui: - rows: 1 - title: "Rankup to {RANK}" - rankup: - material: EMERALD_BLOCK - # index can be separated by spaces to show in multiple groups - # for example: 0-3 9-12 18-21 - # you can also just use a single number instead of a range. - index: 0-3 - name: '&a&lConfirm' - # lore is optional - lore: '&6Rankup to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - # Você pode (e deveria) substituir isto em rankups.yml - # para mostrar os requerimentos específicos para cada rank. - # contudo, se você está apenas usando dinheiro ou não precisa mudar as mensagens por rank, você pode usar qualquer combinação de: - # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } - # {MONEY} e {MONEY_NEEDED} são diferentes de {AMOUNT money} e {AMOUNT_NEEDED money} pois eles usam diferentes formatos. - # here is an example of showing the requirements for just money: - # Segue um exemplo de como mostrar um requerimento para apenas dinheiro. - #list: - # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" - # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" - # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - # Uma string vázia desativa o cabeçalho/rodapé - header: "" - footer: "" - # sent when a player tries to rankup when they are on cooldown. - # Enviado quando um jogador tenta dar rankup enquanto ele está em um cooldown (tempo de espera entre comandos, freeze). - cooldown: - singular: "&cVocê precisa esperar {SECONDS_LEFT} segundo para dar rankup novamente." - plural: "&cVocê precisa {SECONDS_LEFT} segundos para dar rankup novamente." -# prestige messages can also be customised -# Mensagens de prestígio também podem ser customizadas -prestige: - requirements-not-met: "&cVocê precisa {MONEY} para dar prestigiar." - no-prestige: "&eVocê está no maior prestígio." - - success-public: "&a{PLAYER} &esubiu de prestígio para: &d{RANK}" - success-private: "&aVocê subiu de prestígio para: &d{RANK}" - - confirmation: |- - &eVocê tem certeza que deseja subir de prestígio para &a{RANK}&e? - &eDigite &c/prestige &enovamente para confimar. - title: "Subiu de prestígio para {RANK}" - - gui: - rows: 1 - title: "Prestige to {RANK}" - rankup: - material: GOLD_BLOCK - index: 0-3 - name: '&a&lConfirm' - lore: '&6Prestige to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - header: "" - footer: "" - cooldown: - singular: "&cVocê deve esperar {SECONDS_LEFT} segundo para subir de prestígio novamente." - plural: "&cVocê deve esperar {SECONDS_LEFT} segundos para subir de prestígio novamente." - -not-high-enough: "&cVocê não pode subir de prestígio nesse rank!" -not-in-ladder: "&cDesculpa, não conseguimos achar nenhum rank para você subir." +# As mensagens nessa sessão podem ser customizadas para cada rankup em rankups.yml. +rankup: + requirements-not-met: "&cVocê {MONEY} para poder dar subir de rank." + no-rankup: "&eVocê já está no maior rank." + # coloque como uma String vazia, ex: success-public: "" + # para ocultar a mensagem. + success-public: "&a{PLAYER} &eacaba de subir para: &d{RANK}" + success-private: "&aVocê subiu para: &d{RANK}" + # Utilizado para a confirmação via mensagem. + confirmation: |- + &eVocê tem certeza que deseja subir para &a{RANK}&e? + &eDigite &c/rankup &enovamente para confirmar. + + must-prestige: "&cVocê deve subir de prestígio para dar /rankup a frente!" + + gui: + rows: 1 + title: "Rankup to {RANK}" + rankup: + material: EMERALD_BLOCK + # index can be separated by spaces to show in multiple groups + # for example: 0-3 9-12 18-21 + # you can also just use a single number instead of a range. + index: 0-3 + name: '&a&lConfirm' + # lore is optional + lore: '&6Rankup to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + # Você pode (e deveria) substituir isto em rankups.yml + # para mostrar os requerimentos específicos para cada rank. + # contudo, se você está apenas usando dinheiro ou não precisa mudar as mensagens por rank, você pode usar qualquer combinação de: + # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } + # {MONEY} e {MONEY_NEEDED} são diferentes de {AMOUNT money} e {AMOUNT_NEEDED money} pois eles usam diferentes formatos. + # here is an example of showing the requirements for just money: + # Segue um exemplo de como mostrar um requerimento para apenas dinheiro. + #list: + # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" + # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" + # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + # Uma string vázia desativa o cabeçalho/rodapé + header: "" + footer: "" + # sent when a player tries to rankup when they are on cooldown. + # Enviado quando um jogador tenta dar rankup enquanto ele está em um cooldown (tempo de espera entre comandos, freeze). + cooldown: + singular: "&cVocê precisa esperar {SECONDS_LEFT} segundo para dar rankup novamente." + plural: "&cVocê precisa {SECONDS_LEFT} segundos para dar rankup novamente." +# prestige messages can also be customised +# Mensagens de prestígio também podem ser customizadas +prestige: + requirements-not-met: "&cVocê precisa {MONEY} para dar prestigiar." + no-prestige: "&eVocê está no maior prestígio." + + success-public: "&a{PLAYER} &esubiu de prestígio para: &d{RANK}" + success-private: "&aVocê subiu de prestígio para: &d{RANK}" + + confirmation: |- + &eVocê tem certeza que deseja subir de prestígio para &a{RANK}&e? + &eDigite &c/prestige &enovamente para confimar. + title: "Subiu de prestígio para {RANK}" + + gui: + rows: 1 + title: "Prestige to {RANK}" + rankup: + material: GOLD_BLOCK + index: 0-3 + name: '&a&lConfirm' + lore: '&6Prestige to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + header: "" + footer: "" + cooldown: + singular: "&cVocê deve esperar {SECONDS_LEFT} segundo para subir de prestígio novamente." + plural: "&cVocê deve esperar {SECONDS_LEFT} segundos para subir de prestígio novamente." + +not-high-enough: "&cVocê não pode subir de prestígio nesse rank!" +not-in-ladder: "&cDesculpa, não conseguimos achar nenhum rank para você subir." invalid-rankup: "Rankup inválido definido na config, por favor confira o console." \ No newline at end of file diff --git a/src/main/resources/locale/ru.yml b/src/main/resources/locale/ru.yml index d4acdbc..e050121 100644 --- a/src/main/resources/locale/ru.yml +++ b/src/main/resources/locale/ru.yml @@ -1,104 +1,104 @@ -# Сообщения в этой секции могут быть изменены для каждого повышения уровня в rankups.yml -rankup: - requirements-not-met: "&cВам нужно ещё {MONEY} денег для повышения уровня." - no-rankup: "&eУ Вас уже самый высокий ранг." - # Оставьте это поле пустым, чтобы скрыть сообщение (success-public: '') - success-public: "&eРанг игрока &a{PLAYER} &eбыл повышен до: &d{RANK}" - success-private: "&aВаш ранг повысился до: &d{RANK}" - # Используется как текст подтверждения - confirmation: |- - &eВы уверены, что хотите ранг до &a{RANK}&e? - &eВведите &c/rankup &eещё раз, чтобы подтвердить. - - gui: - rows: 1 - title: "Повысить до {RANK}" - rankup: - material: EMERALD_BLOCK - # index can be separated by spaces to show in multiple groups - # for example: 0-3 9-12 18-21 - # you can also just use a single number instead of a range. - index: 0-3 - name: '&a&lConfirm' - # lore is optional - lore: '&6Rankup to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - must-prestige: "&cВам нужно будет больше престижа для /rankup в будущем!" - - # Вы можете (вам стоит ;D) переписать это в rankups.yml, чтобы показать специфичные требования для каждого ранга. - # Тем не менее, если Вы просто используете деньги или не нуждаетесь в смене сообщений для кажого ранга - Вы - # можете использовать комбинации из: {MONEY} {MONEY_NEEDED} {PERCENT_DONE <требование>} {PERCENT_LEFT <требование>} - # {AMOUNT <требование>} {AMOUNT_NEDDED <требование>}. "{MONEY}" и "{MONEY_NEEDED}" отличаются от - # {AMOUNT сумма} {AMOUNT_NEDDED сумма} тем, что они используют разный формат. - # Вот пример показа требований только для денег - # P.S. \xbb - "»" в Unicode. - #list: - # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &eза &7${MONEY}" - # current: "&c{OLD_RANK} &e\xbb &c{RANK} &eза &a${MONEY} &e{PERCENT_DONE money}%" - # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &eза &a${MONEY}" - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - # Пустая строка выключает заголовок/нижнюю часть - header: '' - footer: '' - # Отправляется игроку, который попытался повысить уровень, когда ещё не прошёл кулдаун (откат/перезарядка) - cooldown: - singular: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." - plural: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." -# Сообщения престижа тоже могут быть изменены -prestige: - requirements-not-met: "&cВам нужно {MONEY} денг для повышения престижа." - no-prestige: "&eУ Вас уже самый высокий уровень престижа." - - success-public: "Престиж игрока &a{PLAYER} &eповышен в: &d{RANK}" - success-private: "&aВаш престиж повышен в: &d{RANK}" - - confirmation: |- - &eВы уверены, что хотите престиж в &a{RANK}&e? - &eВведите &c/prestige &eснова для подтверждения. - title: "Повысить престиж в {RANK}" - - gui: - rows: 1 - title: "Prestige to {RANK}" - rankup: - material: GOLD_BLOCK - index: 0-3 - name: '&a&lConfirm' - lore: '&6Prestige to &b{RANK}' - cancel: - material: REDSTONE_BLOCK - index: 5-8 - name: '&c&lCancel' - fill: - name: ' ' - # if you are using a 1.8-1.12 and you want to change this - # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 - # this works for both the rankup and cancel blocks as well - material: BLACK_STAINED_GLASS_PANE - - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - header: "" - footer: "" - cooldown: - singular: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." - plural: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." - -not-high-enough: "&cВы не можете поднять уровень престижа в этом ранге" -not-in-ladder: "&cПростите, но мне не можем найти какие-нибудь повышения для Вашей группы." -invalid-rankup: "В конфигурации определён неверное повышение, пожалуйста, проверьте консоль." +# Сообщения в этой секции могут быть изменены для каждого повышения уровня в rankups.yml +rankup: + requirements-not-met: "&cВам нужно ещё {MONEY} денег для повышения уровня." + no-rankup: "&eУ Вас уже самый высокий ранг." + # Оставьте это поле пустым, чтобы скрыть сообщение (success-public: '') + success-public: "&eРанг игрока &a{PLAYER} &eбыл повышен до: &d{RANK}" + success-private: "&aВаш ранг повысился до: &d{RANK}" + # Используется как текст подтверждения + confirmation: |- + &eВы уверены, что хотите ранг до &a{RANK}&e? + &eВведите &c/rankup &eещё раз, чтобы подтвердить. + + gui: + rows: 1 + title: "Повысить до {RANK}" + rankup: + material: EMERALD_BLOCK + # index can be separated by spaces to show in multiple groups + # for example: 0-3 9-12 18-21 + # you can also just use a single number instead of a range. + index: 0-3 + name: '&a&lConfirm' + # lore is optional + lore: '&6Rankup to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + must-prestige: "&cВам нужно будет больше престижа для /rankup в будущем!" + + # Вы можете (вам стоит ;D) переписать это в rankups.yml, чтобы показать специфичные требования для каждого ранга. + # Тем не менее, если Вы просто используете деньги или не нуждаетесь в смене сообщений для кажого ранга - Вы + # можете использовать комбинации из: {MONEY} {MONEY_NEEDED} {PERCENT_DONE <требование>} {PERCENT_LEFT <требование>} + # {AMOUNT <требование>} {AMOUNT_NEDDED <требование>}. "{MONEY}" и "{MONEY_NEEDED}" отличаются от + # {AMOUNT сумма} {AMOUNT_NEDDED сумма} тем, что они используют разный формат. + # Вот пример показа требований только для денег + # P.S. \xbb - "»" в Unicode. + #list: + # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &eза &7${MONEY}" + # current: "&c{OLD_RANK} &e\xbb &c{RANK} &eза &a${MONEY} &e{PERCENT_DONE money}%" + # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &eза &a${MONEY}" + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + # Пустая строка выключает заголовок/нижнюю часть + header: '' + footer: '' + # Отправляется игроку, который попытался повысить уровень, когда ещё не прошёл кулдаун (откат/перезарядка) + cooldown: + singular: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." + plural: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." +# Сообщения престижа тоже могут быть изменены +prestige: + requirements-not-met: "&cВам нужно {MONEY} денг для повышения престижа." + no-prestige: "&eУ Вас уже самый высокий уровень престижа." + + success-public: "Престиж игрока &a{PLAYER} &eповышен в: &d{RANK}" + success-private: "&aВаш престиж повышен в: &d{RANK}" + + confirmation: |- + &eВы уверены, что хотите престиж в &a{RANK}&e? + &eВведите &c/prestige &eснова для подтверждения. + title: "Повысить престиж в {RANK}" + + gui: + rows: 1 + title: "Prestige to {RANK}" + rankup: + material: GOLD_BLOCK + index: 0-3 + name: '&a&lConfirm' + lore: '&6Prestige to &b{RANK}' + cancel: + material: REDSTONE_BLOCK + index: 5-8 + name: '&c&lCancel' + fill: + name: ' ' + # if you are using a 1.8-1.12 and you want to change this + # you can use MATERIAL:data, for example STAINED_GLASS_PANE:8 + # this works for both the rankup and cancel blocks as well + material: BLACK_STAINED_GLASS_PANE + + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + header: "" + footer: "" + cooldown: + singular: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." + plural: "&cПожалуйста, подождите {SECONDS_LEFT} сек., чтобы повысить ранг снова." + +not-high-enough: "&cВы не можете поднять уровень престижа в этом ранге" +not-in-ladder: "&cПростите, но мне не можем найти какие-нибудь повышения для Вашей группы." +invalid-rankup: "В конфигурации определён неверное повышение, пожалуйста, проверьте консоль." diff --git a/src/main/resources/locale/zh_cn.yml b/src/main/resources/locale/zh_cn.yml index 40602d9..606026a 100644 --- a/src/main/resources/locale/zh_cn.yml +++ b/src/main/resources/locale/zh_cn.yml @@ -1,64 +1,64 @@ -# the messages in this section can be customised for each rankup in rankups.yml. -rankup: - requirements-not-met: "&c 你还需要 {MONEY} 才能够升级。" - no-rankup: "&e你已经处在最高的等级了。" - # set to an empty string, ie: success-public: "" - # to hide that message. - success-public: "&a玩家 {PLAYER} &e升级到: &d{RANK}" - success-private: "&a你已经升级到: &d{RANK}" - # used for the text confirmation - confirmation: |- - &e你确定要升级到 &a{RANK}&e? - &e再次输入 &c/rankup &e来确定。 - # used for the GUI confirmation - title: "升级到 {RANK}" - - must-prestige: "&cYou must prestige to /rankup further!" - - # you can (and probably should) you override these in rankups.yml - # to show the specific requirements for each rank. - # however if you are just using money or don't need to change the message per rank, you can use any combination of: - # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } - # {MONEY} and {MONEY_NEEDED} are different from {AMOUNT money} and {AMOUNT_NEEDED money} in that they use a different format. - # here is an example of showing the requirements for just money: - #list: - # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" - # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" - # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - # an empty string disables the header/footer - header: "" - footer: "" - # sent when a player tries to rankup when they are on cooldown - cooldown: - singular: "&c你必须等候 {SECONDS_LEFT} 才能够再次升级!" - plural: "&c你必须等候 {SECONDS_LEFT} 才能够再次升级!" -# prestige messages can also be customised -prestige: - requirements-not-met: "&cYou need {MONEY} money to prestige." - no-prestige: "&eYou are at the highest prestige." - - success-public: "&a{PLAYER} &ehas prestiged to: &d{RANK}" - success-private: "&aYou have prestiged to: &d{RANK}" - - confirmation: |- - &eAre you sure you want to prestige to &a{RANK}&e? - &eType &c/prestige &eagain to confirm. - title: "Prestige to {RANK}" - - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK}" - current: "&c{OLD_RANK} &e\xbb &c{RANK}" - incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" - header: "" - footer: "" - cooldown: - singular: "&cYou must wait {SECONDS_LEFT} second to prestige again." - plural: "&cYou must wait {SECONDS_LEFT} more seconds to prestige again." - -not-high-enough: "&cYou cannot prestige at your rank!" -not-in-ladder: "&cSorry, but we could not find any rankups for the group(s) you are in. 使用 /ranks 指令去查看所有等级的列表。" +# the messages in this section can be customised for each rankup in rankups.yml. +rankup: + requirements-not-met: "&c 你还需要 {MONEY} 才能够升级。" + no-rankup: "&e你已经处在最高的等级了。" + # set to an empty string, ie: success-public: "" + # to hide that message. + success-public: "&a玩家 {PLAYER} &e升级到: &d{RANK}" + success-private: "&a你已经升级到: &d{RANK}" + # used for the text confirmation + confirmation: |- + &e你确定要升级到 &a{RANK}&e? + &e再次输入 &c/rankup &e来确定。 + # used for the GUI confirmation + title: "升级到 {RANK}" + + must-prestige: "&cYou must prestige to /rankup further!" + + # you can (and probably should) you override these in rankups.yml + # to show the specific requirements for each rank. + # however if you are just using money or don't need to change the message per rank, you can use any combination of: + # {MONEY} {MONEY_NEEDED} {PERCENT_DONE } {PERCENT_LEFT } {AMOUNT } {AMOUNT_NEEDED } + # {MONEY} and {MONEY_NEEDED} are different from {AMOUNT money} and {AMOUNT_NEEDED money} in that they use a different format. + # here is an example of showing the requirements for just money: + #list: + # complete: "&7{OLD_RANK} &8\xbb &7{RANK} &efor &7${MONEY}" + # current: "&c{OLD_RANK} &e\xbb &c{RANK} &efor &a${MONEY} &e{PERCENT_DONE money}%" + # incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &efor &a${MONEY}" + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + # an empty string disables the header/footer + header: "" + footer: "" + # sent when a player tries to rankup when they are on cooldown + cooldown: + singular: "&c你必须等候 {SECONDS_LEFT} 才能够再次升级!" + plural: "&c你必须等候 {SECONDS_LEFT} 才能够再次升级!" +# prestige messages can also be customised +prestige: + requirements-not-met: "&cYou need {MONEY} money to prestige." + no-prestige: "&eYou are at the highest prestige." + + success-public: "&a{PLAYER} &ehas prestiged to: &d{RANK}" + success-private: "&aYou have prestiged to: &d{RANK}" + + confirmation: |- + &eAre you sure you want to prestige to &a{RANK}&e? + &eType &c/prestige &eagain to confirm. + title: "Prestige to {RANK}" + + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK}" + current: "&c{OLD_RANK} &e\xbb &c{RANK}" + incomplete: "&r{OLD_RANK} &e\xbb &r{RANK}" + header: "" + footer: "" + cooldown: + singular: "&cYou must wait {SECONDS_LEFT} second to prestige again." + plural: "&cYou must wait {SECONDS_LEFT} more seconds to prestige again." + +not-high-enough: "&cYou cannot prestige at your rank!" +not-in-ladder: "&cSorry, but we could not find any rankups for the group(s) you are in. 使用 /ranks 指令去查看所有等级的列表。" invalid-rankup: "&c配置中定义的等级无效,请联系管理员检查后台。" \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index db89bc2..11b807f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,65 +1,65 @@ -name: Rankup -version: ${version} -main: sh.okx.rankup.RankupPlugin -author: Okx -depend: [Vault] -softdepend: [PlaceholderAPI, mcMMO, AdvancedAchievements, Towny] -api-version: 1.13 - -commands: - rankup: - permission: rankup.rankup - description: Rankup. - rankup3: - permission: rankup3.info - description: View Rankup version and perform some administrative commands. - # support the old command - aliases: [pru] - ranks: - permission: rankup.ranks - description: List all the ranks. - prestige: - permission: rankup.prestige - description: Prestige. - prestiges: - permission: rankup.prestiges - description: List all the prestiges. - maxrankup: - permission: rankup.maxrankup - description: Rankup as much as possible. -permissions: - rankup.*: - children: - rankup.info: true - rankup.rankup: true - rankup.admin: true - rankup.ranks: true - rankup.prestige: true - rankup.prestiges: true - rankup.auto: true - rankup.maxrankup: true - rankup.admin: - children: - # if a player can see if the plugin needs updating when they run /pru - rankup.checkversion: true - # if a player can run /pru reload - rankup.reload: true - # if a player can force rankup or prestige someone - rankup.force: true - # if a player receives notifications to update rankup when they log in. - rankup.notify: true - default: op - rankup.info: - default: true - rankup.rankup: - default: true - rankup.ranks: - default: true - rankup.prestige: - default: true - rankup.prestiges: - default: true - rankup.auto: - default: true - rankup.maxrankup: +name: Rankup +version: ${version} +main: sh.okx.rankup.RankupPlugin +author: Okx +depend: [Vault] +softdepend: [PlaceholderAPI, mcMMO, AdvancedAchievements, Towny] +api-version: 1.13 + +commands: + rankup: + permission: rankup.rankup + description: Rankup. + rankup3: + permission: rankup3.info + description: View Rankup version and perform some administrative commands. + # support the old command + aliases: [pru] + ranks: + permission: rankup.ranks + description: List all the ranks. + prestige: + permission: rankup.prestige + description: Prestige. + prestiges: + permission: rankup.prestiges + description: List all the prestiges. + maxrankup: + permission: rankup.maxrankup + description: Rankup as much as possible. +permissions: + rankup.*: + children: + rankup.info: true + rankup.rankup: true + rankup.admin: true + rankup.ranks: true + rankup.prestige: true + rankup.prestiges: true + rankup.auto: true + rankup.maxrankup: true + rankup.admin: + children: + # if a player can see if the plugin needs updating when they run /pru + rankup.checkversion: true + # if a player can run /pru reload + rankup.reload: true + # if a player can force rankup or prestige someone + rankup.force: true + # if a player receives notifications to update rankup when they log in. + rankup.notify: true + default: op + rankup.info: + default: true + rankup.rankup: + default: true + rankup.ranks: + default: true + rankup.prestige: + default: true + rankup.prestiges: + default: true + rankup.auto: + default: true + rankup.maxrankup: default: true \ No newline at end of file diff --git a/src/main/resources/prestiges.yml b/src/main/resources/prestiges.yml index d84f138..606bd0b 100644 --- a/src/main/resources/prestiges.yml +++ b/src/main/resources/prestiges.yml @@ -1,19 +1,19 @@ - -first: - # the rank people must be to use this prestige - from: 'D' - # the rank to change it to - to: 'A' - next: 'P1' - # see rankups.yml for more information on requirements, commands, and messages - requirements: - - 'money 10000' -P1example: - from: 'D' - to: 'A' - # the rank added to indicate this prestige - rank: 'P1' - next: 'P2' - requirements: - - 'money 20000' + +first: + # the rank people must be to use this prestige + from: 'D' + # the rank to change it to + to: 'A' + next: 'P1' + # see rankups.yml for more information on requirements, commands, and messages + requirements: + - 'money 10000' +P1example: + from: 'D' + to: 'A' + # the rank added to indicate this prestige + rank: 'P1' + next: 'P2' + requirements: + - 'money 20000' - 'xp-level 5' \ No newline at end of file diff --git a/src/main/resources/rankups.yml b/src/main/resources/rankups.yml index c7a2bcc..4b49453 100644 --- a/src/main/resources/rankups.yml +++ b/src/main/resources/rankups.yml @@ -1,44 +1,44 @@ -# -# If you are adding your own ranks, make sure to delete the example ranks! -# Need help setting the plugin up? -# Read an example: https://github.com/okx-code/Rankup3/wiki/Configuration-Example -# Join the discord server for live support: https://discord.gg/maB4382 (buyers only) -# - -# this name doesn't matter -Aexample: - # the name of the group - # players have to be in this rank to rankup - rank: 'A' - # the name of the rank a player can rankup to - next: 'B' - # List of requirements to go to the next rank - # This example will charge 1000 money to rankup from A to B. - # https://github.com/okx-code/Rankup3/wiki/Requirements - # custom requirements can also be added by other plugins. - requirements: - - 'money 1000' - # the console will run these commands when a player ranks up - # nb: groups are automatically changed with vault - #commands: - # this will run when a player ranks up from A to B. - #- 'say {PLAYER} well done for ranking up from {OLD_RANK} to {RANK}!' -Bexample: - rank: 'B' - next: 'C' - requirements: - - 'money 2500' -Cexample: - rank: 'C' - next: 'D' - requirements: - - 'money 5000' - - 'xp-level 2' - # you can have a custom messages for each rank - # the paths of these messages are the same as in the messages for your locale - rankup: - requirements-not-met: '&cYou need 5000 money and 2 levels of XP to rankup to D.' - list: - complete: "&7{OLD_RANK} &8\xbb &7{RANK} &e(5000 money, 2 XP levels)" - current: "&c{OLD_RANK} &e\xbb &c{RANK} &e(5000 money, 2 XP levels)" +# +# If you are adding your own ranks, make sure to delete the example ranks! +# Need help setting the plugin up? +# Read an example: https://github.com/okx-code/Rankup3/wiki/Configuration-Example +# Join the discord server for live support: https://discord.gg/maB4382 (buyers only) +# + +# this name doesn't matter +Aexample: + # the name of the group + # players have to be in this rank to rankup + rank: 'A' + # the name of the rank a player can rankup to + next: 'B' + # List of requirements to go to the next rank + # This example will charge 1000 money to rankup from A to B. + # https://github.com/okx-code/Rankup3/wiki/Requirements + # custom requirements can also be added by other plugins. + requirements: + - 'money 1000' + # the console will run these commands when a player ranks up + # nb: groups are automatically changed with vault + #commands: + # this will run when a player ranks up from A to B. + #- 'say {PLAYER} well done for ranking up from {OLD_RANK} to {RANK}!' +Bexample: + rank: 'B' + next: 'C' + requirements: + - 'money 2500' +Cexample: + rank: 'C' + next: 'D' + requirements: + - 'money 5000' + - 'xp-level 2' + # you can have a custom messages for each rank + # the paths of these messages are the same as in the messages for your locale + rankup: + requirements-not-met: '&cYou need 5000 money and 2 levels of XP to rankup to D.' + list: + complete: "&7{OLD_RANK} &8\xbb &7{RANK} &e(5000 money, 2 XP levels)" + current: "&c{OLD_RANK} &e\xbb &c{RANK} &e(5000 money, 2 XP levels)" incomplete: "&r{OLD_RANK} &e\xbb &r{RANK} &e(5000 money, 2 XP levels)" \ No newline at end of file diff --git a/src/test/java/sh/okx/rankup/messages/MessageBuilderTest.java b/src/test/java/sh/okx/rankup/messages/MessageBuilderTest.java index 8ac0837..9b42281 100644 --- a/src/test/java/sh/okx/rankup/messages/MessageBuilderTest.java +++ b/src/test/java/sh/okx/rankup/messages/MessageBuilderTest.java @@ -1,14 +1,14 @@ -package sh.okx.rankup.messages; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; - - -public class MessageBuilderTest { - @Test - public void testFailIfEmpty() { - assertThat(new MessageBuilder("").failIfEmpty(), instanceOf(NullMessageBuilder.class)); - } +package sh.okx.rankup.messages; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; + + +public class MessageBuilderTest { + @Test + public void testFailIfEmpty() { + assertThat(new MessageBuilder("").failIfEmpty(), instanceOf(NullMessageBuilder.class)); + } } \ No newline at end of file