├── .gitignore ├── Jenkinsfile ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src └── main ├── java └── cat │ └── nyaa │ └── nyaautils │ ├── CommandHandler.java │ ├── Configuration.java │ ├── DamageStatListener.java │ ├── GlobalLoreBlacklist.java │ ├── I18n.java │ ├── NyaaUtils.java │ ├── api │ └── DamageStatistic.java │ ├── commandwarpper │ ├── EsschatCmdWarpper.java │ ├── TeleportCmdWarpper.java │ └── TpsPingCmdWarpper.java │ ├── dropprotect │ ├── DropProtectListener.java │ └── DropProtectMode.java │ ├── elytra │ ├── ElytraCommands.java │ ├── ElytraEnhanceListener.java │ ├── FuelConfig.java │ ├── FuelItem.java │ └── FuelManager.java │ ├── enchant │ ├── EnchantCommands.java │ └── EnchantSrcConfig.java │ ├── exhibition │ ├── ExhibitionCommands.java │ ├── ExhibitionFrame.java │ └── ExhibitionListener.java │ ├── expcapsule │ ├── ExpCapListener.java │ └── ExpCapsuleCommands.java │ ├── extrabackpack │ ├── ExtraBackpackCommands.java │ ├── ExtraBackpackConfig.java │ ├── ExtraBackpackGUI.java │ ├── ExtraBackpackInventory.java │ ├── ExtraBackpackLine.java │ └── ExtraBackpackListener.java │ ├── lootprotect │ ├── LootProtectListener.java │ └── LootProtectMode.java │ ├── mailbox │ ├── MailboxCommands.java │ ├── MailboxListener.java │ └── MailboxLocations.java │ ├── mention │ ├── MentionListener.java │ └── MentionNotification.java │ ├── messagequeue │ └── MessageQueue.java │ ├── particle │ ├── ParticleCommands.java │ ├── ParticleConfig.java │ ├── ParticleData.java │ ├── ParticleLimit.java │ ├── ParticleListener.java │ ├── ParticleSet.java │ ├── ParticleTask.java │ ├── ParticleType.java │ └── PlayerSetting.java │ ├── realm │ ├── Realm.java │ ├── RealmCommands.java │ ├── RealmConfig.java │ ├── RealmListener.java │ └── RealmType.java │ ├── redstonecontrol │ └── RedstoneControlListener.java │ ├── repair │ ├── RepairCommands.java │ ├── RepairConfig.java │ └── RepairInstance.java │ ├── signedit │ ├── SignContent.java │ ├── SignEditCommands.java │ └── SignEditListener.java │ ├── sit │ ├── SitListener.java │ └── SitLocation.java │ ├── timer │ ├── Checkpoint.java │ ├── PlayerStats.java │ ├── Timer.java │ ├── TimerCommands.java │ ├── TimerConfig.java │ ├── TimerListener.java │ └── TimerManager.java │ ├── tpsping │ └── TpsPingTask.java │ └── vote │ └── VoteTask.java └── resources ├── config.yml ├── i16r ├── en_us.lang └── zh_cn.lang ├── lang ├── en_US.yml ├── zh_CN.yml └── zh_TW.yml └── plugin.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 5 | 6 | # User-specific stuff: 7 | .idea/workspace.xml 8 | .idea/tasks.xml 9 | .idea/dictionaries 10 | .idea/vcs.xml 11 | .idea/jsLibraryMappings.xml 12 | 13 | # Sensitive or high-churn files: 14 | .idea/dataSources.ids 15 | .idea/dataSources.xml 16 | .idea/dataSources.local.xml 17 | .idea/sqlDataSources.xml 18 | .idea/dynamic.xml 19 | .idea/uiDesigner.xml 20 | 21 | # Gradle: 22 | .idea/gradle.xml 23 | .idea/libraries 24 | 25 | # Mongo Explorer plugin: 26 | .idea/mongoSettings.xml 27 | 28 | ## File-based project format: 29 | *.iws 30 | 31 | ## Plugin-specific files: 32 | 33 | # IntelliJ 34 | /out/ 35 | 36 | # mpeltonen/sbt-idea plugin 37 | .idea_modules/ 38 | 39 | # JIRA plugin 40 | atlassian-ide-plugin.xml 41 | 42 | # Crashlytics plugin (for Android Studio and IntelliJ) 43 | com_crashlytics_export_strings.xml 44 | crashlytics.properties 45 | crashlytics-build.properties 46 | fabric.properties 47 | ### Example user template template 48 | ### Example user template 49 | 50 | # IntelliJ project files 51 | .idea 52 | *.iml 53 | out 54 | gen### Java template 55 | *.class 56 | 57 | # Mobile Tools for Java (J2ME) 58 | .mtj.tmp/ 59 | 60 | # Package Files # 61 | *.jar 62 | *.war 63 | *.ear 64 | 65 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 66 | hs_err_pid* 67 | 68 | .DS_Store 69 | .gradle 70 | build 71 | 72 | !lib/LocketteProAPI.jar 73 | !lib/EssentialsX-2.0.1-468.jar 74 | !/lib/ourtown-api.jar 75 | !/gradle/wrapper/gradle-wrapper.jar 76 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent any 3 | stages { 4 | stage('Build') { 5 | tools { 6 | jdk "jdk16" 7 | } 8 | steps { 9 | sh './gradlew build publish' 10 | } 11 | } 12 | } 13 | 14 | post { 15 | always { 16 | archiveArtifacts artifacts: 'build/libs/*.jar', fingerprint: true 17 | cleanWs() 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 NyaaCat Community 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NyaaUtils [![Build Status](https://ci.nyaacat.com/job/NyaaUtils/badge/icon)](https://ci.nyaacat.com/job/NyaaUtils/) 2 | 3 | Gaming utilities/helpers for NyaaCat Minecraft Server 4 | 5 | Detailed function manual please refer to [Wiki](https://github.com/NyaaCat/NyaaUtils/wiki). 6 | 7 | ## Version history 8 | - 7.1.x: Minecraft 1.15.1, since build 258 9 | - 7.0.x: Miencraft 1.14.4 10 | 11 | You can find all builds from [Nyaa CI](https://ci.nyaacat.com/job/NyaaUtils/) or 12 | [Release Page](https://github.com/NyaaCat/NyaaUtils/releases) 13 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "java-library" 2 | apply plugin: "maven-publish" 3 | 4 | // Plugin config 5 | compileJava.options.encoding = 'UTF-8' 6 | ext.pluginNameUpper = "NyaaUtils" 7 | ext.pluginNameLower = ext.pluginNameUpper.toLowerCase() 8 | ext.majorVersion = 8 9 | ext.minorVersion = 1 10 | ext.minecraftVersion = "1.17" 11 | sourceCompatibility = 16 12 | targetCompatibility = 16 13 | 14 | 15 | // Suppiled by Jenkins 16 | ext.buildNumber = System.env.BUILD_NUMBER == null ? "x" : "$System.env.BUILD_NUMBER" 17 | ext.mavenDirectory = System.env.MAVEN_DIR == null ? "$projectDir/repo" : "$System.env.MAVEN_DIR" 18 | ext.jdDirectory = System.env.JAVADOCS_DIR == null ? null : "$System.env.JAVADOCS_DIR" 19 | 20 | // Search for spigot nms jar file 21 | String spigotNmsPath = "" 22 | if (System.env.NMS_JAR != null) { 23 | // use NMS_JAR if it's explicitly specified 24 | spigotNmsPath = "$System.env.NMS_JAR" 25 | if (new File(spigotNmsPath).exists()) { 26 | logger.warn("NMS jar is set manually: ${spigotNmsPath}") 27 | } else { 28 | throw new GradleException("NMS jar not found: ${spigotNmsPath}") 29 | } 30 | } else if (new File("${mavenDirectory}/spigot-${minecraftVersion}-latest.jar").exists()) { 31 | // ci environment 32 | spigotNmsPath = "${mavenDirectory}/spigot-${minecraftVersion}-latest.jar" 33 | } else { 34 | // check local dir (dev environment) 35 | spigotNmsPath = "${projectDir}/../nms_binaries/spigot-${minecraftVersion}.jar" 36 | if (!(new File(spigotNmsPath).exists())) { 37 | // nms not found, download from nyaaci 38 | def f = new File(spigotNmsPath) 39 | println "Downloading spigot-${minecraftVersion}.jar" 40 | f.getParentFile().mkdirs() 41 | new URL("https://ci.nyaacat.com/maven/spigot-${minecraftVersion}-latest.jar").withInputStream{ i -> f.withOutputStream{ it << i }} 42 | } 43 | } 44 | println ("Found NMS jar: ${spigotNmsPath}") 45 | 46 | // Version used for distribution. Different from maven repo 47 | group = "cat.nyaa" 48 | archivesBaseName = "${pluginNameUpper}-mc$minecraftVersion" 49 | version = "$majorVersion.$minorVersion.$buildNumber".toString() 50 | 51 | repositories { 52 | mavenCentral() 53 | maven { name 'Spigot'; url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } 54 | maven { name 'Sonatype'; url 'https://oss.sonatype.org/content/groups/public' } 55 | maven { name 'sk89q'; url 'https://maven.sk89q.com/artifactory/repo/' } 56 | maven { name 'vault-repo'; url 'https://jitpack.io' } 57 | maven { name 'NyaaCat'; url 'https://ci.nyaacat.com/maven/' } 58 | maven { name 'EssentialsX'; url 'https://ci.ender.zone/plugin/repository/everything' } 59 | maven { name 'aikar'; url 'https://repo.aikar.co/content/groups/aikar/' } 60 | } 61 | 62 | dependencies { 63 | // spigot dependencies 64 | compileOnly "org.spigotmc:spigot-api:$minecraftVersion-R0.1-SNAPSHOT" 65 | compileOnly files(spigotNmsPath) 66 | // Nyaa plugins 67 | if (gradle.hasProperty("useLocalDependencies") && gradle.useLocalDependencies) { 68 | compileOnly project(":NyaaCore") 69 | compileOnly project(":LockettePro") 70 | } else { 71 | compileOnly "cat.nyaa:nyaacore:${majorVersion}.${minorVersion}-SNAPSHOT" 72 | compileOnly "me.crafter.mc:lockettepro:2.9-SNAPSHOT" 73 | } 74 | 75 | // Other plugins 76 | compileOnly('net.ess3:EssentialsX:2.18.0') { transitive = false } 77 | compileOnly ('com.sk89q.worldedit:worldedit-bukkit:7.1.0-SNAPSHOT') { 78 | exclude group: 'io.papermc', module: 'paperlib' 79 | exclude group: 'org.bstats.bStats-Metrics', module: 'bstats-bukkit' 80 | exclude group: 'org.bukkit', module: 'bukkit' 81 | exclude group: 'com.destroystokyo.paper', module: 'paper-api' 82 | } 83 | } 84 | 85 | // source file modification (modify version string) 86 | processResources { 87 | filesMatching("**/plugin.yml") { 88 | expand 'version': project.version 89 | } 90 | } 91 | 92 | // source file jar 93 | task sourcesJar(type: Jar) { 94 | archiveClassifier.set("sources") 95 | from sourceSets.main.allSource 96 | } 97 | 98 | // javadoc generation options 99 | javadoc { 100 | // javadoc output folder 101 | if (project.jdDirectory != null) destinationDir = file("${jdDirectory}/${pluginNameLower}-${version}") 102 | 103 | (options as StandardJavadocDocletOptions).with { 104 | links 'https://docs.oracle.com/en/java/javase/16/docs/api/' 105 | links 'https://hub.spigotmc.org/javadocs/spigot/' 106 | links 'https://google.github.io/guava/releases/21.0/api/docs/' 107 | links 'https://ci.md-5.net/job/BungeeCord/ws/chat/target/apidocs/' 108 | 109 | locale 'en_US' 110 | encoding 'UTF-8' 111 | docEncoding 'UTF-8' 112 | addBooleanOption('keywords', true) 113 | addStringOption('Xdoclint:none', '-quiet') 114 | 115 | addBooleanOption('html5', true) 116 | 117 | windowTitle = "${pluginNameUpper} Javadoc" 118 | docTitle = "${pluginNameUpper} (mc$minecraftVersion-${project.version})" 119 | } 120 | } 121 | 122 | // javadoc jar 123 | task javadocJar(type: Jar, dependsOn: javadoc) { 124 | archiveClassifier.set("javadoc") 125 | from javadoc.destinationDir 126 | } 127 | 128 | // compile options 129 | compileJava { 130 | options.compilerArgs += ["-Xlint:deprecation"] 131 | } 132 | 133 | // maven publish 134 | publishing { 135 | publications { 136 | mavenJava(MavenPublication) { 137 | group project.group 138 | artifactId pluginNameLower 139 | version "$majorVersion.$minorVersion-SNAPSHOT" 140 | 141 | from components.java 142 | artifact sourcesJar 143 | artifact javadocJar 144 | } 145 | } 146 | repositories { 147 | maven { 148 | url mavenDirectory 149 | } 150 | } 151 | } 152 | 153 | tasks.withType(JavaCompile) { 154 | options.encoding = "UTF-8" 155 | } 156 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NyaaCat/NyaaUtils/76f0b3ee75f507237eeb827e8b7324adf2b55e53/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/DamageStatListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils; 2 | 3 | import cat.nyaa.nyaautils.api.DamageStatistic; 4 | import com.google.common.cache.CacheBuilder; 5 | import com.google.common.cache.CacheLoader; 6 | import com.google.common.cache.LoadingCache; 7 | import org.bukkit.entity.Entity; 8 | import org.bukkit.entity.LivingEntity; 9 | import org.bukkit.entity.Player; 10 | import org.bukkit.entity.Projectile; 11 | import org.bukkit.event.EventHandler; 12 | import org.bukkit.event.EventPriority; 13 | import org.bukkit.event.Listener; 14 | import org.bukkit.event.entity.EntityDamageByEntityEvent; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | import java.util.UUID; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | public class DamageStatListener implements Listener, DamageStatistic { 22 | /* Cache> */ 23 | public final LoadingCache> entityList; 24 | public final NyaaUtils plugin; 25 | 26 | public DamageStatListener(NyaaUtils plugin) { 27 | this.plugin = plugin; 28 | entityList = CacheBuilder.newBuilder() 29 | .expireAfterAccess(plugin.cfg.damageStatCacheTTL, TimeUnit.MINUTES) 30 | .build( 31 | new CacheLoader>() { 32 | @Override 33 | public Map load(UUID key) throws Exception { 34 | return new HashMap<>(); 35 | } 36 | } 37 | ); 38 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 39 | } 40 | 41 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 42 | public void onEntityDamaged(EntityDamageByEntityEvent ev) { 43 | if (!plugin.cfg.damageStatEnabled) return; 44 | if (!(ev.getEntity() instanceof LivingEntity)) return; 45 | 46 | UUID playerId = null; 47 | if (ev.getDamager() instanceof Player) { 48 | playerId = ev.getDamager().getUniqueId(); 49 | } else if (ev.getDamager() instanceof Projectile) { 50 | if (((Projectile) ev.getDamager()).getShooter() instanceof Player) { 51 | playerId = ((Player) ((Projectile) ev.getDamager()).getShooter()).getUniqueId(); 52 | } else { 53 | return; 54 | } 55 | } else { 56 | return; 57 | } 58 | 59 | UUID mobUid = ev.getEntity().getUniqueId(); 60 | double damage = ev.getFinalDamage(); 61 | double health = ((LivingEntity) ev.getEntity()).getHealth(); 62 | if (damage > health) damage = health; 63 | Map damageMap = entityList.getUnchecked(mobUid); 64 | if (damageMap.containsKey(playerId)) { 65 | damageMap.put(playerId, damageMap.get(playerId) + damage); 66 | } else { 67 | damageMap.put(playerId, damage); 68 | } 69 | } 70 | 71 | @Override 72 | public Map getDamagePlayerList(UUID mobUUID) { 73 | return entityList.getUnchecked(mobUUID); 74 | } 75 | 76 | @Override 77 | public Player getMaxDamagePlayer(Entity mobEntity) { 78 | Player p = null; 79 | double currentMax = -1; 80 | UUID mob = mobEntity.getUniqueId(); 81 | Map map = entityList.getUnchecked(mob); 82 | for (UUID playerUUID : map.keySet()) { 83 | if (plugin.getServer().getPlayer(playerUUID) != null && map.get(playerUUID) > currentMax) { 84 | p = plugin.getServer().getPlayer(playerUUID); 85 | currentMax = map.get(playerUUID); 86 | } 87 | } 88 | return p; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/GlobalLoreBlacklist.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils; 2 | 3 | import cat.nyaa.nyaacore.configuration.FileConfigure; 4 | import cat.nyaa.nyaacore.configuration.ISerializable; 5 | import cat.nyaa.nyaacore.utils.HexColorUtils; 6 | import org.bukkit.ChatColor; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.plugin.java.JavaPlugin; 9 | 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | /* Used by enchantment & repair system. 15 | * Forbid certain items from being enchanted or repaired 16 | * e.g. Much too powerful weapons 17 | */ 18 | public class GlobalLoreBlacklist extends FileConfigure { 19 | 20 | // true = enchant/repair allowed 21 | // false = enchant/repair forbidden 22 | private static class Flags implements ISerializable { 23 | @Serializable 24 | boolean enchant = true; 25 | @Serializable 26 | boolean repair = true; 27 | } 28 | 29 | private boolean default_enchant = true; 30 | private boolean default_repair = true; 31 | private static final Map aclMap = new HashMap<>(); 32 | private final NyaaUtils plugin; 33 | 34 | public GlobalLoreBlacklist(NyaaUtils plugin) { 35 | this.plugin = plugin; 36 | } 37 | 38 | @Override 39 | protected String getFileName() { 40 | return "acl.yml"; 41 | } 42 | 43 | @Override 44 | protected JavaPlugin getPlugin() { 45 | return plugin; 46 | } 47 | 48 | @Override 49 | public void deserialize(ConfigurationSection config) { 50 | aclMap.clear(); 51 | // load default values 52 | if (config.isConfigurationSection("default")) { 53 | this.default_enchant = config.getBoolean("default.enchant", default_enchant); 54 | this.default_repair = config.getBoolean("default.repair", default_repair); 55 | } 56 | // load all lores 57 | for (String key : config.getKeys(false)) { 58 | if (!key.equals("default") && config.isConfigurationSection(key)) { 59 | Flags flags = new Flags(); 60 | flags.deserialize(config.getConfigurationSection(key)); 61 | aclMap.put(key, flags); 62 | } 63 | } 64 | } 65 | 66 | @Override 67 | public void serialize(ConfigurationSection config) { 68 | // save default 69 | ConfigurationSection sectionDefault = config.createSection("default"); 70 | sectionDefault.set("enchant", this.default_enchant); 71 | sectionDefault.set("repair", this.default_repair); 72 | // save lores 73 | for (String lore : aclMap.keySet()) { 74 | aclMap.get(lore).serialize(config.createSection(lore)); 75 | } 76 | } 77 | 78 | public boolean canEnchant(List lore) { 79 | for (String s : lore) { 80 | if (aclMap.containsKey(HexColorUtils.stripEssentialsFormat(s))) { 81 | if (aclMap.get(HexColorUtils.stripEssentialsFormat(s)).enchant != this.default_enchant) { 82 | return aclMap.get(HexColorUtils.stripEssentialsFormat(s)).enchant; 83 | } 84 | } 85 | } 86 | return this.default_enchant; 87 | 88 | } 89 | 90 | public boolean canRepair(List lore) { 91 | for (String s : lore) { 92 | if (aclMap.containsKey(HexColorUtils.stripEssentialsFormat(s))) { 93 | if (aclMap.get(HexColorUtils.stripEssentialsFormat(s)).repair != this.default_repair) { 94 | return aclMap.get(HexColorUtils.stripEssentialsFormat(s)).repair; 95 | } 96 | } 97 | } 98 | return this.default_repair; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/I18n.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils; 2 | 3 | import cat.nyaa.nyaacore.LanguageRepository; 4 | import org.bukkit.plugin.java.JavaPlugin; 5 | 6 | public class I18n extends LanguageRepository { 7 | public static I18n instance = null; 8 | private String lang = null; 9 | private final NyaaUtils plugin; 10 | 11 | @Override 12 | protected JavaPlugin getPlugin() { 13 | return plugin; 14 | } 15 | 16 | @Override 17 | protected String getLanguage() { 18 | return lang; 19 | } 20 | 21 | public I18n(NyaaUtils plugin, String lang) { 22 | instance = this; 23 | this.plugin = plugin; 24 | this.lang = lang; 25 | load(); 26 | } 27 | 28 | public static String format(String key, Object... args) { 29 | return instance.getFormatted(key, args); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/NyaaUtils.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils; 2 | 3 | import cat.nyaa.nyaacore.component.ComponentNotAvailableException; 4 | import cat.nyaa.nyaacore.component.IMessageQueue; 5 | import cat.nyaa.nyaacore.component.ISystemBalance; 6 | import cat.nyaa.nyaacore.component.NyaaComponent; 7 | import cat.nyaa.nyaautils.commandwarpper.EsschatCmdWarpper; 8 | import cat.nyaa.nyaautils.commandwarpper.TeleportCmdWarpper; 9 | import cat.nyaa.nyaautils.commandwarpper.TpsPingCmdWarpper; 10 | import cat.nyaa.nyaautils.dropprotect.DropProtectListener; 11 | import cat.nyaa.nyaautils.elytra.ElytraEnhanceListener; 12 | import cat.nyaa.nyaautils.elytra.FuelManager; 13 | import cat.nyaa.nyaautils.exhibition.ExhibitionListener; 14 | import cat.nyaa.nyaautils.expcapsule.ExpCapListener; 15 | import cat.nyaa.nyaautils.extrabackpack.ExtraBackpackGUI; 16 | import cat.nyaa.nyaautils.extrabackpack.ExtraBackpackListener; 17 | import cat.nyaa.nyaautils.lootprotect.LootProtectListener; 18 | import cat.nyaa.nyaautils.mailbox.MailboxListener; 19 | import cat.nyaa.nyaautils.mention.MentionListener; 20 | import cat.nyaa.nyaautils.messagequeue.MessageQueue; 21 | import cat.nyaa.nyaautils.particle.ParticleListener; 22 | import cat.nyaa.nyaautils.particle.ParticleTask; 23 | import cat.nyaa.nyaautils.realm.RealmListener; 24 | import cat.nyaa.nyaautils.redstonecontrol.RedstoneControlListener; 25 | import cat.nyaa.nyaautils.signedit.SignEditListener; 26 | import cat.nyaa.nyaautils.sit.SitListener; 27 | import cat.nyaa.nyaautils.timer.TimerListener; 28 | import cat.nyaa.nyaautils.timer.TimerManager; 29 | import cat.nyaa.nyaautils.tpsping.TpsPingTask; 30 | import cat.nyaa.nyaautils.vote.VoteTask; 31 | import com.earth2me.essentials.ISettings; 32 | import com.sk89q.worldedit.bukkit.WorldEditPlugin; 33 | import net.ess3.api.IEssentials; 34 | import org.bukkit.Bukkit; 35 | import org.bukkit.command.TabCompleter; 36 | import org.bukkit.event.HandlerList; 37 | import org.bukkit.plugin.java.JavaPlugin; 38 | 39 | import java.lang.reflect.InvocationTargetException; 40 | 41 | public class NyaaUtils extends JavaPlugin { 42 | public static NyaaUtils instance; 43 | public ISystemBalance systemBalance = null; 44 | public I18n i18n; 45 | public CommandHandler commandHandler; 46 | public Configuration cfg; 47 | public LootProtectListener lpListener; 48 | public DropProtectListener dpListener; 49 | public DamageStatListener dsListener; 50 | public ExhibitionListener exhibitionListener; 51 | public ExpCapListener expCapListener; 52 | public MailboxListener mailboxListener; 53 | public ElytraEnhanceListener elytraEnhanceListener; 54 | public TeleportCmdWarpper teleportCmdWarpper; 55 | public FuelManager fuelManager; 56 | public TimerManager timerManager; 57 | public TimerListener timerListener; 58 | public WorldEditPlugin worldEditPlugin; 59 | public RealmListener realmListener; 60 | public IEssentials ess; 61 | public ParticleListener particleListener; 62 | public ParticleTask particleTask; 63 | public SignEditListener signEditListener; 64 | public MentionListener mentionListener; 65 | public EsschatCmdWarpper esschatCmdWarpper; 66 | public VoteTask voteTask; 67 | public MessageQueue messageQueueListener; 68 | public RedstoneControlListener redstoneControlListener; 69 | public TpsPingTask tpsPingTask; 70 | public TpsPingCmdWarpper tpsPingCmdWarpper; 71 | public SitListener sitListener; 72 | public ExtraBackpackListener extraBackpackListener; 73 | 74 | @Override 75 | public void onEnable() { 76 | instance = this; 77 | cfg = new Configuration(this); 78 | cfg.load(); 79 | i18n = new I18n(this, cfg.language); 80 | commandHandler = new CommandHandler(this, i18n); 81 | getCommand("nyaautils").setExecutor(commandHandler); 82 | getCommand("nyaautils").setTabCompleter((TabCompleter) commandHandler); 83 | lpListener = new LootProtectListener(this); 84 | dpListener = new DropProtectListener(this); 85 | dsListener = new DamageStatListener(this); 86 | elytraEnhanceListener = new ElytraEnhanceListener(this); 87 | teleportCmdWarpper = new TeleportCmdWarpper(this); 88 | exhibitionListener = new ExhibitionListener(this); 89 | expCapListener = new ExpCapListener(this); 90 | mailboxListener = new MailboxListener(this); 91 | fuelManager = new FuelManager(this); 92 | timerManager = new TimerManager(this); 93 | timerListener = new TimerListener(this); 94 | if (Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { 95 | worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); 96 | } 97 | realmListener = new RealmListener(this); 98 | try { 99 | systemBalance = NyaaComponent.get(ISystemBalance.class); 100 | } catch (ComponentNotAvailableException e) { 101 | systemBalance = null; 102 | } 103 | ess = (IEssentials) getServer().getPluginManager().getPlugin("Essentials"); 104 | particleTask = new ParticleTask(this); 105 | particleListener = new ParticleListener(this); 106 | signEditListener = new SignEditListener(this); 107 | mentionListener = new MentionListener(this); 108 | messageQueueListener = new MessageQueue(this); 109 | NyaaComponent.register(IMessageQueue.class, messageQueueListener); 110 | redstoneControlListener = new RedstoneControlListener(this); 111 | sitListener = new SitListener(this); 112 | extraBackpackListener = new ExtraBackpackListener(this); 113 | try { 114 | ISettings settings = ess.getSettings(); 115 | Class essSettingsClass = settings.getClass(); 116 | Long timeout = (Long) essSettingsClass.getMethod("getLastMessageReplyRecipientTimeout").invoke(settings); 117 | // TODO: sort out reply recipient when isLastMessageReplyRecipient set to false instead disabling it 118 | Boolean allow = (Boolean) essSettingsClass.getMethod("isLastMessageReplyRecipient").invoke(settings); 119 | esschatCmdWarpper = new EsschatCmdWarpper(this, allow, timeout); 120 | } catch (NoSuchMethodException e) { 121 | getLogger().warning("EssentialsX not available, not enabling mention notify in /reply commands"); 122 | } catch (IllegalAccessException | InvocationTargetException e) { 123 | e.printStackTrace(); 124 | getLogger().warning("Unexpected error when enabling mention notify in EssentialsX commands"); 125 | } 126 | 127 | voteTask = null; 128 | if (cfg.ping_enable || cfg.tps_enable) { 129 | tpsPingTask = new TpsPingTask(this); 130 | tpsPingTask.runTaskTimer(this, 0, 0); 131 | tpsPingCmdWarpper = new TpsPingCmdWarpper(this); 132 | } 133 | } 134 | 135 | @Override 136 | public void onDisable() { 137 | ExtraBackpackGUI.closeAll(); 138 | getServer().getScheduler().cancelTasks(this); 139 | getCommand("nyaautils").setExecutor(null); 140 | getCommand("nyaautils").setTabCompleter(null); 141 | HandlerList.unregisterAll(this); 142 | cfg.save(); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/api/DamageStatistic.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.api; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.entity.Entity; 5 | import org.bukkit.entity.Player; 6 | 7 | import java.util.Map; 8 | import java.util.UUID; 9 | 10 | public interface DamageStatistic { 11 | static DamageStatistic instance() { 12 | return NyaaUtils.instance.dsListener; 13 | } 14 | 15 | Map getDamagePlayerList(UUID mobUUID); 16 | 17 | Player getMaxDamagePlayer(Entity mobEntity); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/commandwarpper/EsschatCmdWarpper.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.commandwarpper; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import cat.nyaa.nyaautils.mention.MentionListener; 5 | import com.google.common.cache.Cache; 6 | import com.google.common.cache.CacheBuilder; 7 | import org.bukkit.Bukkit; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.EventPriority; 11 | import org.bukkit.event.Listener; 12 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 13 | 14 | import java.util.Collections; 15 | import java.util.UUID; 16 | import java.util.concurrent.ExecutionException; 17 | import java.util.concurrent.TimeUnit; 18 | import java.util.stream.Stream; 19 | 20 | public class EsschatCmdWarpper implements Listener { 21 | private final NyaaUtils plugin; 22 | private final boolean allowMentionReply; 23 | private final Cache r; 24 | 25 | public EsschatCmdWarpper(NyaaUtils pl, boolean allowMentionReply, long timeout) { 26 | this.plugin = pl; 27 | this.allowMentionReply = allowMentionReply; 28 | if (plugin.cfg.mention_enable) { 29 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 30 | } 31 | r = CacheBuilder.newBuilder().expireAfterWrite(timeout, TimeUnit.SECONDS).build(); 32 | } 33 | 34 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 35 | public void onCommandPreProcess(PlayerCommandPreprocessEvent e) throws ExecutionException { 36 | if (plugin.cfg.mention_enable) { 37 | String cmd = e.getMessage().toLowerCase().trim(); 38 | if (Stream.of("/msg ", "/tell ", "/m ", "/t ", "/whisper ").parallel().anyMatch(cmd::startsWith)) { 39 | String[] split = cmd.split(" ", 3); 40 | if (split.length != 3) return; 41 | String recipient = split[1]; 42 | String raw = split[2]; 43 | Player p = Bukkit.getPlayer(recipient); 44 | if (p == null) return; 45 | MentionListener.notify(e.getPlayer(), raw, Collections.singleton(p), plugin); 46 | r.put(e.getPlayer().getUniqueId(), p.getUniqueId()); 47 | r.get(p.getUniqueId(), e.getPlayer()::getUniqueId); 48 | } 49 | 50 | if (Stream.of("/r ", "/reply ").parallel().anyMatch(cmd::startsWith) && allowMentionReply && r.getIfPresent(e.getPlayer().getUniqueId()) != null) { 51 | r.put(e.getPlayer().getUniqueId(), r.getIfPresent(e.getPlayer().getUniqueId())); 52 | String[] split = cmd.split(" ", 2); 53 | if (split.length != 2) return; 54 | Player p = Bukkit.getPlayer(r.getIfPresent(e.getPlayer().getUniqueId())); 55 | if (p == null) return; 56 | MentionListener.notify(e.getPlayer(), null, Collections.singleton(p), plugin); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/commandwarpper/TpsPingCmdWarpper.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.commandwarpper; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.EventPriority; 7 | import org.bukkit.event.Listener; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | import org.bukkit.event.server.ServerCommandEvent; 10 | 11 | public class TpsPingCmdWarpper implements Listener { 12 | private final NyaaUtils plugin; 13 | 14 | public TpsPingCmdWarpper(NyaaUtils pl) { 15 | plugin = pl; 16 | Bukkit.getPluginManager().registerEvents(this, plugin); 17 | } 18 | 19 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) 20 | public void onPlayerCommandPreProcess(PlayerCommandPreprocessEvent e) { 21 | String cmd = e.getMessage(); 22 | if (plugin.cfg.tps_enable && plugin.cfg.tps_override && (cmd.startsWith("/tps ") || cmd.equals("/tps"))) { 23 | e.setMessage(cmd.replaceAll("^/tps", "/nu tps")); 24 | } 25 | 26 | if (plugin.cfg.ping_enable && plugin.cfg.ping_override && (cmd.startsWith("/ping ") || cmd.equals("/ping"))) { 27 | e.setMessage(cmd.replaceAll("^/ping", "/nu ping")); 28 | } 29 | 30 | if (plugin.cfg.ping_enable && plugin.cfg.ping_override && (cmd.startsWith("/pingtop ") || cmd.equals("/pingtop"))) { 31 | e.setMessage(cmd.replaceAll("^/pingtop", "/nu pingtop")); 32 | } 33 | } 34 | 35 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) 36 | public void onServerCommandPreProcess(ServerCommandEvent e) { 37 | String cmd = e.getCommand(); 38 | if (plugin.cfg.tps_enable && plugin.cfg.tps_override && (cmd.startsWith("tps ") || cmd.equals("tps"))) { 39 | e.setCommand(cmd.replaceAll("^tps", "nu tps")); 40 | } 41 | 42 | if (plugin.cfg.ping_enable && plugin.cfg.ping_override && (cmd.startsWith("ping ") || cmd.equals("ping"))) { 43 | e.setCommand(cmd.replaceAll("^ping", "nu ping")); 44 | } 45 | 46 | if (plugin.cfg.ping_enable && plugin.cfg.ping_override && (cmd.startsWith("pingtop ") || cmd.equals("pingtop"))) { 47 | e.setCommand(cmd.replaceAll("^pingtop", "nu pingtop")); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/dropprotect/DropProtectListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.dropprotect; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import com.google.common.cache.Cache; 5 | import com.google.common.cache.CacheBuilder; 6 | import org.bukkit.Bukkit; 7 | import org.bukkit.Location; 8 | import org.bukkit.entity.Entity; 9 | import org.bukkit.entity.Item; 10 | import org.bukkit.event.EventHandler; 11 | import org.bukkit.event.EventPriority; 12 | import org.bukkit.event.Listener; 13 | import org.bukkit.event.entity.ItemDespawnEvent; 14 | import org.bukkit.event.entity.ItemMergeEvent; 15 | import org.bukkit.event.entity.PlayerDeathEvent; 16 | import org.bukkit.event.entity.EntityPickupItemEvent; 17 | import org.bukkit.inventory.ItemStack; 18 | 19 | import java.util.*; 20 | import java.util.concurrent.TimeUnit; 21 | import java.util.stream.Stream; 22 | 23 | public class DropProtectListener implements Listener { 24 | final private NyaaUtils plugin; 25 | final private Map bypassPlayer = new HashMap<>(); 26 | final private Cache items; 27 | 28 | public DropProtectListener(NyaaUtils pl) { 29 | plugin = pl; 30 | plugin.getServer().getPluginManager().registerEvents(this, pl); 31 | items = CacheBuilder.newBuilder() 32 | .concurrencyLevel(2) 33 | .maximumSize(plugin.cfg.dropProtectMaximumItem) 34 | .expireAfterWrite(plugin.cfg.dropProtectSecond, TimeUnit.SECONDS) 35 | .build(); 36 | } 37 | 38 | /** 39 | * @return true: drop protect is enabled 40 | * false: drop protect is disabled 41 | */ 42 | public boolean toggleStatus(UUID uuid) { 43 | if (bypassPlayer.containsKey(uuid)) { 44 | bypassPlayer.remove(uuid); 45 | return true; 46 | } else { 47 | bypassPlayer.put(uuid, uuid); 48 | return false; 49 | } 50 | } 51 | 52 | @EventHandler(priority = EventPriority.MONITOR) 53 | public void onPlayerDeath(PlayerDeathEvent e) { 54 | if (plugin.cfg.dropProtectMode == DropProtectMode.OFF) return; 55 | UUID id = e.getEntity().getUniqueId(); 56 | if (bypassPlayer.containsKey(id)) return; 57 | List dropStacks = e.getDrops(); 58 | Location loc = e.getEntity().getLocation(); 59 | Bukkit.getScheduler().runTaskLater(plugin, () -> { 60 | Collection ents = loc.getWorld().getNearbyEntities(loc, 3, 3, 10); 61 | ents.stream() 62 | .flatMap(ent -> (ent instanceof Item) ? Stream.of((Item) ent) : Stream.empty()) 63 | .filter(i -> dropStacks.contains(i.getItemStack())) 64 | .forEach(dropItem -> items.put(dropItem.getEntityId(), id)); 65 | }, 1); 66 | } 67 | 68 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) 69 | public void onItemDespawn(ItemDespawnEvent e) { 70 | if (plugin.cfg.dropProtectMode == DropProtectMode.OFF) return; 71 | Item ent = e.getEntity(); 72 | if (items.getIfPresent(ent.getEntityId()) != null) { 73 | e.setCancelled(true); 74 | } 75 | } 76 | 77 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) 78 | public void onItemMerge(ItemMergeEvent e) { 79 | if (plugin.cfg.dropProtectMode == DropProtectMode.OFF) return; 80 | Item ent = e.getEntity(); 81 | Item target = e.getTarget(); 82 | if (items.getIfPresent(ent.getEntityId()) != null && items.getIfPresent(target.getEntityId()) == null) { 83 | items.put(target.getEntityId(), items.getIfPresent(ent.getEntityId())); 84 | } else if (items.getIfPresent(ent.getEntityId()) == null && items.getIfPresent(target.getEntityId()) != null) { 85 | items.put(target.getEntityId(), items.getIfPresent(target.getEntityId()));//Refresh 86 | } else if (items.getIfPresent(ent.getEntityId()) != null && items.getIfPresent(target.getEntityId()) != null && items.getIfPresent(ent.getEntityId()) != items.getIfPresent(target.getEntityId())) { 87 | e.setCancelled(true); 88 | } 89 | } 90 | 91 | @EventHandler(priority = EventPriority.MONITOR) 92 | public void onPickup(EntityPickupItemEvent e) { 93 | if (plugin.cfg.dropProtectMode == DropProtectMode.OFF) return; 94 | items.invalidate(e.getItem().getEntityId()); 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/dropprotect/DropProtectMode.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.dropprotect; 2 | 3 | public enum DropProtectMode { 4 | OFF, 5 | ON 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/elytra/ElytraCommands.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.elytra; 2 | 3 | import cat.nyaa.nyaacore.LanguageRepository; 4 | import cat.nyaa.nyaacore.cmdreceiver.Arguments; 5 | import cat.nyaa.nyaacore.cmdreceiver.CommandReceiver; 6 | import cat.nyaa.nyaacore.cmdreceiver.SubCommand; 7 | import cat.nyaa.nyaacore.utils.InventoryUtils; 8 | import cat.nyaa.nyaautils.NyaaUtils; 9 | import org.bukkit.Bukkit; 10 | import org.bukkit.Material; 11 | import org.bukkit.command.CommandSender; 12 | import org.bukkit.entity.Player; 13 | import org.bukkit.inventory.ItemStack; 14 | 15 | public class ElytraCommands extends CommandReceiver { 16 | private NyaaUtils plugin; 17 | 18 | public ElytraCommands(Object plugin, LanguageRepository i18n) { 19 | super((NyaaUtils) plugin, i18n); 20 | this.plugin = (NyaaUtils) plugin; 21 | } 22 | 23 | @Override 24 | public String getHelpPrefix() { 25 | return "el"; 26 | } 27 | 28 | @Override 29 | public void acceptCommand(CommandSender sender, Arguments cmd) { 30 | String subCommand = cmd.top(); 31 | if (subCommand == null) subCommand = ""; 32 | if (subCommand.length() > 0) { 33 | super.acceptCommand(sender, cmd); 34 | } else { 35 | commandElytraToggle(sender, cmd); 36 | } 37 | } 38 | 39 | @SubCommand(value = "addfuel", permission = "nu.addfuel") 40 | public void commandAddFuel(CommandSender sender, Arguments args) { 41 | ItemStack item = getItemInHand(sender); 42 | int durability = 0; 43 | if (args.length() == 3) { 44 | durability = args.nextInt(); 45 | } 46 | if (item != null && item.getType() != Material.AIR) { 47 | if (durability > 0) { 48 | int fuelID = -1; 49 | for (int i = plugin.cfg.fuelConfig.pos; i < 100000; i++) { 50 | if (!plugin.cfg.fuelConfig.fuel.containsKey(i)) { 51 | fuelID = i; 52 | plugin.cfg.fuelConfig.pos = i + 1; 53 | break; 54 | } 55 | } 56 | if (fuelID != -1) { 57 | item.setAmount(1); 58 | FuelItem fuel = new FuelItem(fuelID, item.clone(), durability); 59 | plugin.cfg.fuelConfig.fuel.put(fuelID, fuel.clone()); 60 | plugin.cfg.save(); 61 | msg(sender, "user.elytra_enhance.fuel_info", fuelID, durability); 62 | plugin.fuelManager.updateItem(item, fuelID, durability); 63 | plugin.fuelManager.invalidateCache(); 64 | } 65 | } else { 66 | item.setAmount(1); 67 | plugin.cfg.fuelConfig.elytra_fuel = item.clone(); 68 | } 69 | NyaaUtils.instance.cfg.save(); 70 | msg(sender, "user.elytra_enhance.save_success"); 71 | } 72 | } 73 | 74 | @SubCommand(value = "removefuel", permission = "nu.addfuel") 75 | public void commandRemoveFuel(CommandSender sender, Arguments args) { 76 | ItemStack item = getItemInHand(sender).clone(); 77 | if (item != null && item.getType() != Material.AIR) { 78 | if (plugin.fuelManager.getFuelID(item) != -1 && 79 | plugin.fuelManager.getFuel(plugin.fuelManager.getFuelID(item)) != null) { 80 | plugin.cfg.fuelConfig.fuel.remove(plugin.fuelManager.getFuelID(item)); 81 | plugin.fuelManager.invalidateCache(); 82 | msg(sender, "user.elytra_enhance.remove"); 83 | NyaaUtils.instance.cfg.save(); 84 | msg(sender, "user.elytra_enhance.save_success"); 85 | } 86 | } 87 | } 88 | 89 | @SubCommand(value = "givefuel", permission = "nu.givefuel") 90 | public void commandGiveFuel(CommandSender sender, Arguments args) { 91 | if (args.length() != 5) { 92 | msg(sender, "manual.el.givefuel.usage"); 93 | return; 94 | } 95 | String playerName = args.next(); 96 | Player player = Bukkit.getPlayer(playerName); 97 | if (player == null) { 98 | msg(sender, "user.elytra_enhance.player_not_found", playerName); 99 | return; 100 | } 101 | int fuelID = args.nextInt(); 102 | int amount = args.nextInt(); 103 | if (plugin.fuelManager.getFuel(fuelID) != null) { 104 | ItemStack item = plugin.fuelManager.getFuel(fuelID).getItem(); 105 | item.setAmount(amount); 106 | plugin.fuelManager.updateItem(item, fuelID, plugin.fuelManager.getFuel(fuelID).getMaxDurability()); 107 | InventoryUtils.addItem(player, item); 108 | } else { 109 | msg(sender, "user.elytra_enhance.fuel_not_found", fuelID); 110 | } 111 | } 112 | 113 | @SubCommand(permission = "nu.elytratoggle", isDefaultCommand = true) 114 | public void commandElytraToggle(CommandSender sender, Arguments args) { 115 | Player player = asPlayer(sender); 116 | if (ElytraEnhanceListener.disableFuelMode.contains(player.getUniqueId())) { 117 | ElytraEnhanceListener.disableFuelMode.remove(player.getUniqueId()); 118 | msg(sender, "user.elytra_enhance.fuelmode_on"); 119 | } else { 120 | ElytraEnhanceListener.disableFuelMode.add(player.getUniqueId()); 121 | msg(sender, "user.elytra_enhance.fuelmode_off"); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/elytra/ElytraEnhanceListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.elytra; 2 | 3 | import cat.nyaa.nyaautils.I18n; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import org.bukkit.Material; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.EventPriority; 9 | import org.bukkit.event.Listener; 10 | import org.bukkit.event.inventory.InventoryClickEvent; 11 | import org.bukkit.event.player.PlayerMoveEvent; 12 | import org.bukkit.inventory.ItemStack; 13 | import org.bukkit.inventory.meta.Damageable; 14 | 15 | import java.util.*; 16 | 17 | public class ElytraEnhanceListener implements Listener { 18 | public static List FuelMode = new ArrayList<>(); 19 | public static Set disableFuelMode = new HashSet<>(); 20 | public static Map duration = new HashMap(); 21 | public NyaaUtils plugin; 22 | 23 | public ElytraEnhanceListener(NyaaUtils pl) { 24 | plugin = pl; 25 | plugin.getServer().getPluginManager().registerEvents(this, pl); 26 | } 27 | 28 | @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) 29 | public void playerMove(PlayerMoveEvent e) { 30 | Player player = e.getPlayer(); 31 | if (player.isGliding() && 32 | plugin.cfg.elytra_enhance_enabled && 33 | !plugin.cfg.disabled_world.contains(player.getWorld().getName()) && 34 | player.getLocation().getBlock().isEmpty() && 35 | player.getEyeLocation().getBlock().isEmpty() && 36 | !disableFuelMode.contains(player.getUniqueId()) && 37 | !player.isSneaking()) { 38 | if (!FuelMode.contains(player.getUniqueId()) && 39 | player.getVelocity().length() >= 0.75 && 40 | plugin.fuelManager.getFuelAmount(player, false) > 0) { 41 | FuelMode.add(player.getUniqueId()); 42 | } 43 | if (duration.containsKey(player.getUniqueId()) && 44 | duration.get(player.getUniqueId()) >= System.currentTimeMillis()) { 45 | player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity)); 46 | } 47 | if (FuelMode.contains(player.getUniqueId()) && 48 | player.getVelocity().length() <= plugin.cfg.elytra_min_velocity && 49 | player.getLocation().getBlockY() <= plugin.cfg.elytra_boost_max_height && 50 | player.getLocation().getPitch() < 50) { 51 | if (player.getInventory().getChestplate() != null && 52 | player.getInventory().getChestplate().getType() == Material.ELYTRA) { 53 | int durability = player.getInventory().getChestplate().getType().getMaxDurability() - 54 | ((Damageable)player.getInventory().getChestplate().getItemMeta()).getDamage(); 55 | if (durability <= plugin.cfg.elytra_durability_notify) { 56 | player.sendMessage(I18n.format("user.elytra_enhance.durability_notify", durability)); 57 | } 58 | } 59 | if (!plugin.fuelManager.useFuel(player)) { 60 | FuelMode.remove(player.getUniqueId()); 61 | if (duration.containsKey(player.getUniqueId())) { 62 | duration.remove(player.getUniqueId()); 63 | } 64 | return; 65 | } else { 66 | duration.put(player.getUniqueId(), System.currentTimeMillis() + (plugin.cfg.elytra_power_duration * 1000)); 67 | player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity)); 68 | } 69 | int fuelAmount = plugin.fuelManager.getFuelAmount(player, false); 70 | if (fuelAmount <= plugin.cfg.elytra_fuel_notify) { 71 | player.sendMessage(I18n.format("user.elytra_enhance.fuel_notify", fuelAmount)); 72 | } 73 | } 74 | return; 75 | } else if (FuelMode.contains(player.getUniqueId())) { 76 | FuelMode.remove(player.getUniqueId()); 77 | } 78 | } 79 | 80 | @EventHandler(ignoreCancelled = true) 81 | public void onInventoryClickEvent(InventoryClickEvent event) { 82 | if (!event.getWhoClicked().isGliding() && event.getCurrentItem() != null && plugin.fuelManager.getFuelID(event.getCurrentItem()) != -1) { 83 | ItemStack item = event.getCurrentItem(); 84 | int id = plugin.fuelManager.getFuelID(item); 85 | int durability = plugin.fuelManager.getFuelDurability(item); 86 | plugin.fuelManager.updateItem(item, id, durability); 87 | event.setCurrentItem(item); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/elytra/FuelConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.elytra; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import cat.nyaa.nyaacore.configuration.FileConfigure; 5 | import cat.nyaa.nyaacore.configuration.ISerializable; 6 | import org.bukkit.Material; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.inventory.ItemStack; 9 | import org.bukkit.plugin.java.JavaPlugin; 10 | 11 | import java.util.HashMap; 12 | 13 | public class FuelConfig extends FileConfigure { 14 | private final NyaaUtils plugin; 15 | @Serializable 16 | public ItemStack elytra_fuel = new ItemStack(Material.GUNPOWDER); 17 | @Serializable 18 | public int pos = 0; 19 | 20 | public HashMap fuel = new HashMap<>(); 21 | 22 | public FuelConfig(NyaaUtils pl) { 23 | this.plugin = pl; 24 | } 25 | 26 | @Override 27 | protected String getFileName() { 28 | return "fuel.yml"; 29 | } 30 | 31 | @Override 32 | protected JavaPlugin getPlugin() { 33 | return this.plugin; 34 | } 35 | 36 | @Override 37 | public void deserialize(ConfigurationSection config) { 38 | fuel.clear(); 39 | ISerializable.deserialize(config, this); 40 | if (config.isConfigurationSection("fuel")) { 41 | ConfigurationSection fuelList = config.getConfigurationSection("fuel"); 42 | for (String k : fuelList.getKeys(false)) { 43 | FuelItem fuel = new FuelItem(); 44 | fuel.deserialize(fuelList.getConfigurationSection(k)); 45 | this.fuel.put(fuel.getItemID(), fuel.clone()); 46 | } 47 | } 48 | } 49 | 50 | @Override 51 | public void serialize(ConfigurationSection config) { 52 | ISerializable.serialize(config, this); 53 | config.set("fuel", null); 54 | ConfigurationSection fuelList = config.createSection("fuel"); 55 | for (int k : fuel.keySet()) { 56 | FuelItem fuel = this.fuel.get(k).clone(); 57 | fuel.serialize(fuelList.createSection(String.valueOf(k))); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/elytra/FuelItem.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.elytra; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | import org.bukkit.configuration.ConfigurationSection; 5 | import org.bukkit.inventory.ItemStack; 6 | 7 | public class FuelItem implements ISerializable { 8 | @Serializable 9 | private int itemID = 0; 10 | @Serializable 11 | private ItemStack item = null; 12 | @Serializable 13 | private int maxDurability = 0; 14 | 15 | public FuelItem() { 16 | } 17 | 18 | public FuelItem(int itemID, ItemStack item, int maxDurability) { 19 | this.itemID = itemID; 20 | this.item = item.clone(); 21 | this.maxDurability = maxDurability; 22 | } 23 | 24 | public int getItemID() { 25 | return itemID; 26 | } 27 | 28 | public void setItemID(int itemID) { 29 | this.itemID = itemID; 30 | } 31 | 32 | public ItemStack getItem() { 33 | return item.clone(); 34 | } 35 | 36 | public void setItem(ItemStack item) { 37 | this.item = item.clone(); 38 | } 39 | 40 | public int getMaxDurability() { 41 | return maxDurability; 42 | } 43 | 44 | public void setMaxDurability(int maxDurability) { 45 | this.maxDurability = maxDurability; 46 | } 47 | 48 | @Override 49 | public void deserialize(ConfigurationSection config) { 50 | ISerializable.deserialize(config, this); 51 | } 52 | 53 | @Override 54 | public void serialize(ConfigurationSection config) { 55 | ISerializable.serialize(config, this); 56 | } 57 | 58 | public FuelItem clone() { 59 | return new FuelItem(this.itemID, this.item.clone(), this.maxDurability); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/elytra/FuelManager.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.elytra; 2 | 3 | 4 | import cat.nyaa.nyaacore.utils.InventoryUtils; 5 | import cat.nyaa.nyaautils.I18n; 6 | import cat.nyaa.nyaautils.NyaaUtils; 7 | import com.google.common.cache.Cache; 8 | import com.google.common.cache.CacheBuilder; 9 | import org.bukkit.Material; 10 | import org.bukkit.NamespacedKey; 11 | import org.bukkit.entity.Player; 12 | import org.bukkit.inventory.ItemStack; 13 | import org.bukkit.inventory.meta.ItemMeta; 14 | import org.bukkit.persistence.PersistentDataContainer; 15 | import org.bukkit.persistence.PersistentDataType; 16 | 17 | import java.util.ArrayList; 18 | import java.util.HashSet; 19 | import java.util.List; 20 | import java.util.Set; 21 | import java.util.concurrent.TimeUnit; 22 | 23 | public class FuelManager { 24 | private final NyaaUtils plugin; 25 | 26 | private static final NamespacedKey keyFuelId = new NamespacedKey(NyaaUtils.instance, "fuelId"); 27 | private static final NamespacedKey keyFuelDurability = new NamespacedKey(NyaaUtils.instance, "fuelDurability"); 28 | private static final int cacheKey = 1; 29 | 30 | public FuelManager(NyaaUtils pl) { 31 | plugin = pl; 32 | } 33 | 34 | private Cache> fuelMaterialCache = CacheBuilder.newBuilder() 35 | .expireAfterWrite(10, TimeUnit.MINUTES) 36 | .build(); 37 | 38 | public int getFuelAmount(Player player, boolean exact) { 39 | int fuel = 0; 40 | if (InventoryUtils.hasItem(player, plugin.cfg.fuelConfig.elytra_fuel, 1)) { 41 | fuel = InventoryUtils.getAmount(player, plugin.cfg.fuelConfig.elytra_fuel); 42 | } 43 | for (int i = 0; i <= player.getInventory().getSize(); i++) { 44 | if (!exact && fuel > plugin.cfg.elytra_fuel_notify) { 45 | return fuel; 46 | } 47 | ItemStack item = player.getInventory().getItem(i); 48 | int fuelID = getFuelID(item); 49 | if (fuelID != -1 && plugin.cfg.fuelConfig.fuel.containsKey(fuelID)) { 50 | fuel += getFuelDurability(item); 51 | } 52 | } 53 | return fuel; 54 | } 55 | 56 | public boolean useFuel(Player player) { 57 | if (plugin.cfg.fuelConfig.elytra_fuel != null && plugin.cfg.fuelConfig.elytra_fuel.getType() != Material.AIR) { 58 | if (InventoryUtils.removeItem(player, plugin.cfg.fuelConfig.elytra_fuel, 1)) { 59 | return true; 60 | } 61 | } 62 | for (int i = 0; i <= player.getInventory().getSize(); i++) { 63 | ItemStack item = player.getInventory().getItem(i); 64 | int fuelID = getFuelID(item); 65 | if (fuelID != -1 && getFuel(fuelID) != null) { 66 | int durability = getFuelDurability(item); 67 | FuelItem fuel = getFuel(fuelID); 68 | if (durability > fuel.getMaxDurability()) { 69 | durability = fuel.getMaxDurability(); 70 | } 71 | durability--; 72 | if (durability <= 0) { 73 | player.getInventory().setItem(i, new ItemStack(Material.AIR)); 74 | } else { 75 | updateItem(item, fuelID, durability); 76 | } 77 | return true; 78 | } 79 | } 80 | return false; 81 | } 82 | 83 | public void updateItem(ItemStack item, int fuelID, int durability) { 84 | FuelItem fuel = plugin.cfg.fuelConfig.fuel.get(fuelID); 85 | if (fuel == null) { 86 | return; 87 | } 88 | ItemMeta meta = fuel.getItem().getItemMeta(); 89 | PersistentDataContainer persistentDataContainer = meta.getPersistentDataContainer(); 90 | persistentDataContainer.set(keyFuelId, PersistentDataType.INTEGER, fuelID); 91 | persistentDataContainer.set(keyFuelDurability, PersistentDataType.INTEGER, durability); 92 | 93 | List lore; 94 | String fuelLore = I18n.format("user.elytra_enhance.fuel_durability", durability, fuel.getMaxDurability()); 95 | if (meta.hasLore()) { 96 | lore = meta.getLore(); 97 | if (lore.size() == 0) { 98 | lore.add(""); 99 | } 100 | lore.set(0, fuelLore); 101 | } else { 102 | lore = new ArrayList<>(); 103 | lore.add(fuelLore); 104 | } 105 | item.setType(fuel.getItem().getType()); 106 | if(fuel.getItem().getType().isLegacy()) { 107 | item.setData(fuel.getItem().getData()); 108 | } 109 | meta.setLore(lore); 110 | item.setItemMeta(meta); 111 | } 112 | 113 | public int getFuelID(ItemStack item) { 114 | boolean isItem = item != null && !item.getType().equals(Material.AIR); 115 | if (!isItem){ 116 | return -1; 117 | } 118 | Set types = fuelMaterialCache.getIfPresent(cacheKey); 119 | if (types == null){ 120 | types = loadCache(); 121 | } 122 | Material type = item.getType(); 123 | if (!types.contains(type)){ 124 | return -1; 125 | } 126 | if (item.hasItemMeta()) { 127 | ItemMeta itemMeta = item.getItemMeta(); 128 | PersistentDataContainer persistentDataContainer = itemMeta.getPersistentDataContainer(); 129 | Integer id = persistentDataContainer.get(keyFuelId, PersistentDataType.INTEGER); 130 | if (id == null) { 131 | return -1; 132 | } 133 | return id; 134 | } 135 | return -1; 136 | } 137 | 138 | private Set loadCache() { 139 | Set materials = new HashSet<>(); 140 | plugin.cfg.fuelConfig.fuel.values().stream().forEach(fuelItem -> { 141 | materials.add(fuelItem.getItem().getType()); 142 | }); 143 | fuelMaterialCache.put(cacheKey, materials); 144 | return materials; 145 | } 146 | 147 | public int getFuelDurability(ItemStack item) { 148 | if (item != null && !item.getType().equals(Material.AIR) && item.hasItemMeta()) { 149 | ItemMeta itemMeta = item.getItemMeta(); 150 | PersistentDataContainer persistentDataContainer = itemMeta.getPersistentDataContainer(); 151 | Integer durability = persistentDataContainer.get(keyFuelDurability, PersistentDataType.INTEGER); 152 | if (durability == null) { 153 | return -1; 154 | } 155 | return durability; 156 | } 157 | return -1; 158 | } 159 | 160 | public FuelItem getFuel(int fuelID) { 161 | if (plugin.cfg.fuelConfig.fuel.containsKey(fuelID)) { 162 | return plugin.cfg.fuelConfig.fuel.get(fuelID); 163 | } 164 | return null; 165 | } 166 | 167 | public String toHexString(int i) { 168 | String string = Integer.toHexString(i); 169 | if (string.length() < 4) { 170 | return "0000".substring(0, 4 - string.length()) + string; 171 | } 172 | return string; 173 | } 174 | 175 | public void invalidateCache() { 176 | fuelMaterialCache.invalidateAll(); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/enchant/EnchantSrcConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.enchant; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import cat.nyaa.nyaacore.BasicItemMatcher; 5 | import cat.nyaa.nyaacore.configuration.FileConfigure; 6 | import cat.nyaa.nyaacore.configuration.ISerializable; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.plugin.java.JavaPlugin; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class EnchantSrcConfig extends FileConfigure { 14 | public List enchantSrc = new ArrayList<>(); 15 | private NyaaUtils plugin = null; 16 | 17 | public EnchantSrcConfig(NyaaUtils pl) { 18 | plugin = pl; 19 | } 20 | 21 | @Override 22 | protected String getFileName() { 23 | return "enchantsrc.yml"; 24 | } 25 | 26 | @Override 27 | protected JavaPlugin getPlugin() { 28 | return plugin; 29 | } 30 | 31 | @Override 32 | public void deserialize(ConfigurationSection config) { 33 | ISerializable.deserialize(config, this); 34 | 35 | enchantSrc = new ArrayList<>(); 36 | if (config.isConfigurationSection("enchantSrc")) { 37 | ConfigurationSection src = config.getConfigurationSection("enchantSrc"); 38 | for (String key : src.getKeys(false)) { 39 | if (src.isConfigurationSection(key)) { 40 | BasicItemMatcher tmp = new BasicItemMatcher(); 41 | tmp.deserialize(src.getConfigurationSection(key)); 42 | enchantSrc.add(tmp); 43 | } 44 | } 45 | } 46 | } 47 | 48 | @Override 49 | public void serialize(ConfigurationSection config) { 50 | ISerializable.serialize(config, this); 51 | 52 | ConfigurationSection dst = config.createSection("enchantSrc"); 53 | int idx = 0; 54 | for (BasicItemMatcher m : enchantSrc) { 55 | m.serialize(dst.createSection(Integer.toString(idx))); 56 | idx++; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/exhibition/ExhibitionCommands.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.exhibition; 2 | 3 | import cat.nyaa.nyaacore.LanguageRepository; 4 | import cat.nyaa.nyaacore.cmdreceiver.Arguments; 5 | import cat.nyaa.nyaacore.cmdreceiver.CommandReceiver; 6 | import cat.nyaa.nyaacore.cmdreceiver.SubCommand; 7 | import cat.nyaa.nyaautils.NyaaUtils; 8 | import org.bukkit.GameMode; 9 | import org.bukkit.Material; 10 | import org.bukkit.command.CommandSender; 11 | import org.bukkit.entity.Player; 12 | import org.bukkit.inventory.ItemStack; 13 | 14 | import java.util.List; 15 | 16 | public class ExhibitionCommands extends CommandReceiver { 17 | private final NyaaUtils plugin; 18 | 19 | public ExhibitionCommands(Object plugin, LanguageRepository i18n) { 20 | super((NyaaUtils) plugin, i18n); 21 | this.plugin = (NyaaUtils) plugin; 22 | } 23 | 24 | @Override 25 | public String getHelpPrefix() { 26 | return "exhibition"; 27 | } 28 | 29 | @SubCommand(value = "set", permission = "nu.exhibition.set") 30 | public void commandSet(CommandSender sender, Arguments args) { 31 | Player p = asPlayer(sender); 32 | ExhibitionFrame f = ExhibitionFrame.fromPlayerEye(p); 33 | if (f == null) { 34 | msg(sender, "user.exhibition.no_item_frame"); 35 | return; 36 | } 37 | if (f.getItemFrame().isFixed()) { 38 | msg(sender, "user.exhibition.already_set"); 39 | return; 40 | } 41 | if (!f.hasItem()) { 42 | msg(sender, "user.exhibition.no_item"); 43 | return; 44 | } 45 | if (f.isSet()) { 46 | msg(sender, "user.exhibition.already_set"); 47 | return; 48 | } 49 | if (p.getGameMode() == GameMode.SURVIVAL) { 50 | p.getWorld().dropItem(p.getEyeLocation(), f.getItemFrame().getItem()); 51 | } 52 | f.set(p); 53 | msg(sender, "user.exhibition.set"); 54 | } 55 | 56 | @SubCommand(value = "unset", permission = "nu.exhibition.unset") 57 | public void commandUnset(CommandSender sender, Arguments args) { 58 | Player p = asPlayer(sender); 59 | ExhibitionFrame f = ExhibitionFrame.fromPlayerEye(p); 60 | if (f == null) { 61 | msg(sender, "user.exhibition.no_item_frame"); 62 | return; 63 | } 64 | if (!f.hasItem()) { 65 | msg(sender, "user.exhibition.no_item"); 66 | return; 67 | } 68 | if (!f.isSet()) { 69 | msg(sender, "user.exhibition.have_not_set"); 70 | return; 71 | } 72 | if (f.ownerMatch(p)) { 73 | f.unset(); 74 | msg(sender, "user.exhibition.unset"); 75 | if (p.getGameMode() == GameMode.SURVIVAL) { 76 | f.getItemFrame().setItem(new ItemStack(Material.AIR)); 77 | } 78 | } else if (p.hasPermission("nu.exhibition.forceUnset")) { 79 | f.unset(); 80 | msg(sender, "user.exhibition.unset"); 81 | } else { 82 | msg(sender, "user.exhibition.unset_protected"); 83 | } 84 | } 85 | 86 | @SubCommand(value = "toggleinv", permission = "nu.exhibition.inv") 87 | public void commandInv(CommandSender sender, Arguments args) { 88 | Player p = asPlayer(sender); 89 | ExhibitionFrame f = ExhibitionFrame.fromPlayerEye(p); 90 | if (f == null) { 91 | msg(sender, "user.exhibition.no_item_frame"); 92 | return; 93 | } 94 | if (!f.hasItem()) { 95 | msg(sender, "user.exhibition.no_item"); 96 | return; 97 | } 98 | if (f.ownerMatch(p) || p.isOp() || p.hasPermission("nu.exhibition.forceToggleInv")) { 99 | if (f.isVisible()) { 100 | f.setVisible(false); 101 | msg(sender, "user.exhibition.inv"); 102 | } else { 103 | f.setVisible(true); 104 | msg(sender, "user.exhibition.uninv"); 105 | } 106 | } else { 107 | msg(sender, "user.exhibition.not_owner"); 108 | } 109 | 110 | 111 | } 112 | 113 | @SubCommand(value = "desc", permission = "nu.exhibition.desc") 114 | public void commandDesc(CommandSender sender, Arguments args) { 115 | Player p = asPlayer(sender); 116 | ExhibitionFrame f = ExhibitionFrame.fromPlayerEye(p); 117 | if (f == null) { 118 | msg(sender, "user.exhibition.no_item_frame"); 119 | return; 120 | } 121 | if (!f.hasItem()) { 122 | msg(sender, "user.exhibition.no_item"); 123 | return; 124 | } 125 | if (!f.isSet()) { 126 | msg(sender, "user.exhibition.have_not_set"); 127 | return; 128 | } 129 | if (f.ownerMatch(p) || p.hasPermission("nu.exhibition.forceUnset")) { 130 | List desc = f.getDescriptions(); 131 | if (args.top() == null) { 132 | if (desc.size() == 0) { 133 | msg(sender, "user.exhibition.no_desc"); 134 | } else { 135 | int i = 0; 136 | for (String s : desc) { 137 | sender.sendMessage(String.format("%d: %s", i, s)); 138 | i++; 139 | } 140 | } 141 | msg(sender, "manual.exhibition.desc.usage"); 142 | return; 143 | } 144 | int lineNumber = args.nextInt(); 145 | if (args.top() == null) { 146 | if (lineNumber < 0 || lineNumber >= desc.size()) { 147 | msg(sender, "user.exhibition.range_error"); 148 | } else { 149 | f.setDescription(lineNumber, null); 150 | msg(sender, "user.exhibition.line_removed", lineNumber); 151 | } 152 | } else { 153 | String str = args.next(); 154 | if (lineNumber < 0 || lineNumber > desc.size()) { 155 | msg(sender, "user.exhibition.range_error"); 156 | } else { 157 | f.setDescription(lineNumber, str); 158 | msg(sender, "user.exhibition.line_changed", lineNumber); 159 | } 160 | } 161 | } else { 162 | msg(sender, "user.exhibition.desc_protected"); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/exhibition/ExhibitionListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.exhibition; 2 | 3 | import cat.nyaa.nyaacore.Message; 4 | import cat.nyaa.nyaautils.I18n; 5 | import cat.nyaa.nyaautils.NyaaUtils; 6 | import org.bukkit.Material; 7 | import org.bukkit.entity.ItemFrame; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.Listener; 11 | import org.bukkit.event.entity.EntityDamageByEntityEvent; 12 | import org.bukkit.event.hanging.HangingBreakEvent; 13 | import org.bukkit.event.inventory.InventoryClickEvent; 14 | import org.bukkit.event.player.PlayerInteractEntityEvent; 15 | import org.bukkit.inventory.ItemStack; 16 | 17 | import static org.bukkit.event.EventPriority.HIGHEST; 18 | 19 | public class ExhibitionListener implements Listener { 20 | public final NyaaUtils plugin; 21 | 22 | public ExhibitionListener(NyaaUtils plugin) { 23 | this.plugin = plugin; 24 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 25 | } 26 | 27 | @EventHandler(priority = HIGHEST, ignoreCancelled = true) 28 | public void onPlayerInteractItemFrame(PlayerInteractEntityEvent ev) { 29 | if (!(ev.getRightClicked() instanceof ItemFrame)) return; 30 | ItemFrame f = (ItemFrame) ev.getRightClicked(); 31 | if (f.getItem() == null || f.getItem().getType() == Material.AIR) return; 32 | ExhibitionFrame fr = ExhibitionFrame.fromItemFrame(f); 33 | if (fr.isSet()) { 34 | new Message(I18n.format("user.exhibition.looking_at")).append(fr.getItemInFrame()).send(ev.getPlayer()); 35 | ev.getPlayer().sendMessage(I18n.format("user.exhibition.provided_by", fr.getOwnerName())); 36 | for (String line : fr.getDescriptions()) { 37 | ev.getPlayer().sendMessage(line); 38 | } 39 | ev.setCancelled(true); 40 | if (fr.hasItem() && fr.getItemInFrame().getType() == Material.WRITTEN_BOOK) { 41 | ev.getPlayer().openBook(fr.getItemInFrame()); 42 | } 43 | } 44 | } 45 | 46 | @EventHandler(priority = HIGHEST, ignoreCancelled = true) 47 | public void onPlayerHitItemFrame(EntityDamageByEntityEvent ev) { 48 | if (!(ev.getEntity() instanceof ItemFrame)) return; 49 | ItemFrame f = (ItemFrame) ev.getEntity(); 50 | if (f.getItem() == null || f.getItem().getType() == Material.AIR) return; 51 | if (ExhibitionFrame.fromItemFrame(f).isSet()) { 52 | ev.setCancelled(true); 53 | if (ev.getDamager() instanceof Player) { 54 | ev.getDamager().sendMessage(I18n.format("user.exhibition.frame_protected")); 55 | } 56 | } 57 | } 58 | 59 | @EventHandler(priority = HIGHEST, ignoreCancelled = true) 60 | public void onItemFrameBreak(HangingBreakEvent ev) { 61 | if (!(ev.getEntity() instanceof ItemFrame)) return; 62 | ItemFrame f = (ItemFrame) ev.getEntity(); 63 | if (f.getItem() == null || f.getItem().getType() == Material.AIR) return; 64 | if (ExhibitionFrame.fromItemFrame(f).isSet()) { 65 | if (ev.getCause() == HangingBreakEvent.RemoveCause.EXPLOSION) { // Explosion protect 66 | ev.setCancelled(true); 67 | } else { 68 | plugin.getLogger().warning(String.format("Exhibition broken: Location: %s, item: %s", f.getLocation(), 69 | f.getItem())); 70 | f.setItem(new ItemStack(Material.AIR)); 71 | } 72 | } 73 | } 74 | 75 | @EventHandler(priority = HIGHEST, ignoreCancelled = true) 76 | public void onPlayerFetchItem(InventoryClickEvent ev) { 77 | if (!(ev.getWhoClicked() instanceof Player)) return; 78 | if (ExhibitionFrame.isFrameInnerItem(ev.getCursor())) { 79 | plugin.getLogger().warning( 80 | String.format("Illegal Exhibition Item use: {player: %s, location: %s, item: %s}", 81 | ev.getWhoClicked().getName(), ev.getWhoClicked().getLocation(), 82 | ev.getCursor().toString())); 83 | ev.setCancelled(true); 84 | ev.getView().setCursor(new ItemStack(Material.AIR)); 85 | } 86 | if (ExhibitionFrame.isFrameInnerItem(ev.getCurrentItem())) { 87 | plugin.getLogger().warning( 88 | String.format("Illegal Exhibition Item use: {player: %s, location: %s, item: %s}", 89 | ev.getWhoClicked().getName(), ev.getWhoClicked().getLocation(), 90 | ev.getCursor().toString())); 91 | ev.setCancelled(true); 92 | ev.setCurrentItem(new ItemStack(Material.AIR)); 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/expcapsule/ExpCapListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.expcapsule; 2 | 3 | import cat.nyaa.nyaautils.Configuration; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.Location; 7 | import org.bukkit.Material; 8 | import org.bukkit.World; 9 | import org.bukkit.entity.ExperienceOrb; 10 | import org.bukkit.entity.Player; 11 | import org.bukkit.entity.ThrownExpBottle; 12 | import org.bukkit.event.EventHandler; 13 | import org.bukkit.event.Listener; 14 | import org.bukkit.event.block.Action; 15 | import org.bukkit.event.entity.ExpBottleEvent; 16 | import org.bukkit.event.entity.ProjectileLaunchEvent; 17 | import org.bukkit.event.player.PlayerInteractEvent; 18 | import org.bukkit.inventory.ItemStack; 19 | import org.bukkit.metadata.FixedMetadataValue; 20 | import org.bukkit.metadata.MetadataValue; 21 | import org.bukkit.plugin.java.JavaPlugin; 22 | import org.bukkit.projectiles.ProjectileSource; 23 | import org.bukkit.util.Vector; 24 | 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Random; 28 | import java.util.UUID; 29 | 30 | public class ExpCapListener implements Listener { 31 | 32 | private final JavaPlugin plugin; 33 | private Configuration cfg; 34 | private HashMap thrownExpMap = new HashMap(); 35 | 36 | public ExpCapListener(JavaPlugin plugin) { 37 | this.plugin = plugin; 38 | cfg = ((NyaaUtils) plugin).cfg; 39 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 40 | } 41 | 42 | @EventHandler 43 | public void onPlayerRightClick(PlayerInteractEvent event) { 44 | ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); 45 | ItemStack itemInOffHand = event.getPlayer().getInventory().getItemInOffHand(); 46 | if (!itemInMainHand.getType().equals(Material.EXPERIENCE_BOTTLE) 47 | && !itemInOffHand.getType().equals(Material.EXPERIENCE_BOTTLE)) { 48 | return; 49 | } 50 | if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR)) { 51 | ItemStack item = event.getItem(); 52 | if (item == null) return; 53 | if (item.getType().equals(Material.EXPERIENCE_BOTTLE)) { 54 | Long storedExp = ExpCapsuleCommands.getStoredExp(item); 55 | thrownExpMap.put(event.getPlayer().getUniqueId(), storedExp); 56 | } 57 | } 58 | } 59 | 60 | @EventHandler 61 | public void onExpCapThrown(ProjectileLaunchEvent event) { 62 | if (!cfg.expcap_thron_enabled) return; 63 | if (event.getEntity() instanceof ThrownExpBottle) { 64 | ProjectileSource shooter = event.getEntity().getShooter(); 65 | if (shooter instanceof Player) { 66 | event.getEntity().setMetadata("nu_expcap_exp", 67 | new FixedMetadataValue(plugin, 68 | thrownExpMap.computeIfAbsent(((Player) shooter).getUniqueId(), uuid -> 0L) 69 | ) 70 | ); 71 | } 72 | } 73 | } 74 | 75 | Random random = new Random(); 76 | @EventHandler 77 | public void onExpCapHit(ExpBottleEvent event) { 78 | if (event.getEntity().hasMetadata("nu_expcap_exp")) { 79 | List nu_expcap_exp = event.getEntity().getMetadata("nu_expcap_exp"); 80 | MetadataValue metadataValue = nu_expcap_exp.get(0); 81 | if (metadataValue == null) { 82 | return; 83 | } 84 | long exp = metadataValue.asLong(); 85 | if (exp <= 0)return; 86 | //生成的经验球数量大于1,小于总经验数 87 | long maxOrbAmount = Math.min(exp,cfg.expcap_max_orb_amount); 88 | int minOrbAmount = Math.max(1, ((NyaaUtils) plugin).cfg.expcap_min_orb_amount); 89 | long orbAmount = Math.min(Math.max(exp, minOrbAmount), maxOrbAmount); 90 | Location location = event.getEntity().getLocation(); 91 | long expPerOrb = exp / orbAmount; 92 | int delay = 0; 93 | int step = Math.max(cfg.expcap_orb_ticksBetweenSpawn,0); 94 | //整形除法可能导致实际生成经验量偏少 95 | long spawnedExp = orbAmount * expPerOrb; 96 | long remain = exp - spawnedExp; 97 | final World world = location.getWorld(); 98 | if (world == null) return; 99 | world.spawn(location, ExperienceOrb.class, experienceOrb -> { 100 | experienceOrb.setExperience((int) Math.min(Integer.MAX_VALUE, remain)); 101 | }); 102 | 103 | for (int i = 0; i < orbAmount; i++) { 104 | Bukkit.getScheduler().runTaskLater(plugin, ()->{ 105 | Location add = null; 106 | for (int j = 0; j < 5; j++) { 107 | Location clone = location.clone(); 108 | double dx = random.nextDouble() * 6; 109 | double dy = random.nextDouble() * 3; 110 | double dz = random.nextDouble() * 6; 111 | dx -= 3; 112 | dz -= 3; 113 | add = clone.add(new Vector(dx, dy, dz)); 114 | if (!world.getBlockAt(location).getType().isSolid())break; 115 | } 116 | if (!world.getBlockAt(location).getType().isSolid()) add = location; 117 | world.spawn(add, ExperienceOrb.class, experienceOrb -> { 118 | experienceOrb.setExperience((int) Math.min(Integer.MAX_VALUE, expPerOrb)); 119 | }); 120 | },delay+=step); 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/expcapsule/ExpCapsuleCommands.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.expcapsule; 2 | 3 | import cat.nyaa.nyaacore.ILocalizer; 4 | import cat.nyaa.nyaacore.Message; 5 | import cat.nyaa.nyaacore.cmdreceiver.Arguments; 6 | import cat.nyaa.nyaacore.cmdreceiver.BadCommandException; 7 | import cat.nyaa.nyaacore.cmdreceiver.CommandReceiver; 8 | import cat.nyaa.nyaacore.cmdreceiver.SubCommand; 9 | import cat.nyaa.nyaacore.utils.ExperienceUtils; 10 | import cat.nyaa.nyaautils.Configuration; 11 | import cat.nyaa.nyaautils.I18n; 12 | import cat.nyaa.nyaautils.NyaaUtils; 13 | import org.bukkit.ChatColor; 14 | import org.bukkit.NamespacedKey; 15 | import org.bukkit.command.CommandSender; 16 | import org.bukkit.entity.Player; 17 | import org.bukkit.inventory.ItemStack; 18 | import org.bukkit.inventory.meta.ItemMeta; 19 | import org.bukkit.persistence.PersistentDataContainer; 20 | import org.bukkit.persistence.PersistentDataType; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | public class ExpCapsuleCommands extends CommandReceiver { 26 | private final NyaaUtils plugin; 27 | private final Configuration cfg; 28 | 29 | private static final NamespacedKey expcapKey = new NamespacedKey(NyaaUtils.instance, "expcap"); 30 | 31 | public ExpCapsuleCommands(NyaaUtils plugin, ILocalizer i18n) { 32 | super(plugin, i18n); 33 | this.plugin = plugin; 34 | cfg = plugin.cfg; 35 | } 36 | 37 | @Override 38 | public String getHelpPrefix() { 39 | return "expcap"; 40 | } 41 | 42 | @SubCommand(value = "store", permission = "nu.expcap.store") 43 | public void cmdStoreExp(CommandSender sender, Arguments args) { 44 | Player p = asPlayer(sender); 45 | int exp = ExperienceUtils.getExpPoints(p); 46 | p.sendMessage(I18n.format("user.expcap.current_exp", exp)); 47 | 48 | if (args.top() == null) return; 49 | int amount; 50 | if ("ALL".equalsIgnoreCase(args.top())) { 51 | amount = exp; 52 | if (amount <= 0) throw new BadCommandException("user.expcap.not_enough_exp"); 53 | } else { 54 | amount = args.nextInt(); 55 | if (amount <= 0) throw new BadCommandException("user.expcap.wrong_nbr"); 56 | if (exp < amount) throw new BadCommandException("user.expcap.not_enough_exp"); 57 | } 58 | 59 | ItemStack item = getItemInHand(sender); 60 | if (item.getType() != plugin.cfg.expCapsuleType) { 61 | throw new BadCommandException("user.expcap.wrong_cap_type"); 62 | } 63 | if (item.getAmount() > 1) { 64 | throw new BadCommandException("user.expcap.not_stackable"); 65 | } 66 | 67 | Long storedExpInt = getStoredExp(item); 68 | if (storedExpInt == null) storedExpInt = 0L; 69 | long storedExp = storedExpInt; 70 | int maxExp = cfg.expcap_max_stored_exp; 71 | if (storedExp > maxExp) { 72 | new Message(I18n.format("user.expcap.bottle_full", maxExp)) 73 | .send(p); 74 | } else { 75 | storedExp += amount; 76 | if (storedExp > maxExp){ 77 | new Message(I18n.format("user.expcap.bottle_full")) 78 | .send(p); 79 | amount = Math.toIntExact(amount - (storedExp - maxExp)); 80 | storedExp = maxExp; 81 | } 82 | new Message(I18n.format("user.expcap.stored_exp",amount, storedExp)) 83 | .send(p); 84 | setStoredExp(item, storedExp); 85 | ExperienceUtils.subtractExpPoints(p, amount); 86 | } 87 | } 88 | 89 | @SubCommand(value = "restore", permission = "nu.expcap.restore") 90 | public void cmdRestoreExp(CommandSender sender, Arguments args) { 91 | Player p = asPlayer(sender); 92 | ItemStack item = getItemInHand(sender); 93 | Long storedExp = getStoredExp(item); 94 | if (storedExp == null) throw new BadCommandException("user.expcap.not_enough_exp_cap"); 95 | if (item.getAmount() > 1) throw new BadCommandException("user.expcap.not_stackable"); 96 | 97 | Long amount; 98 | if (args.top() == null) throw new BadCommandException(); 99 | if ("ALL".equalsIgnoreCase(args.top())) { 100 | amount = storedExp; 101 | if (amount <= 0) throw new BadCommandException("user.expcap.not_enough_exp_cap"); 102 | } else { 103 | amount = args.nextLong(); 104 | if (amount <= 0) throw new BadCommandException("user.expcap.wrong_nbr"); 105 | if (amount > storedExp) throw new BadCommandException("user.expcap.not_enough_exp_cap"); 106 | } 107 | 108 | storedExp -= amount; 109 | p.giveExp(amount.intValue()); 110 | setStoredExp(item, storedExp); 111 | } 112 | 113 | @SubCommand(value = "set", permission = "nu.expcap.set") 114 | public void cmdSetExp(CommandSender sender, Arguments args) { 115 | Player p = asPlayer(sender); 116 | ItemStack item = getItemInHand(sender); 117 | int amount = args.nextInt(); 118 | setStoredExp(item, amount); 119 | } 120 | 121 | public static final String EXP_CAPSULE_MAGIC = ChatColor.translateAlternateColorCodes('&', "&e&c&a&r"); 122 | 123 | public static Long getStoredExp(ItemStack item) { 124 | if (!item.hasItemMeta()) return null; 125 | ItemMeta meta = item.getItemMeta(); 126 | PersistentDataContainer persistentDataContainer = meta.getPersistentDataContainer(); 127 | Long exp = persistentDataContainer.get(expcapKey, PersistentDataType.LONG); 128 | return exp; 129 | } 130 | 131 | public static void setStoredExp(ItemStack item, long exp) { 132 | ItemMeta meta = item.getItemMeta(); 133 | PersistentDataContainer persistentDataContainer = meta.getPersistentDataContainer(); 134 | persistentDataContainer.set(expcapKey, PersistentDataType.LONG, exp); 135 | 136 | List lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); 137 | List newLore = new ArrayList<>(); 138 | for (String str : lore) { 139 | if (str.contains(EXP_CAPSULE_MAGIC)) continue; 140 | newLore.add(str); 141 | } 142 | if (newLore.size() == 0 && exp > 0){ 143 | newLore.add(0, ""); 144 | } 145 | if (exp > 0) { 146 | newLore.set(0, I18n.format("user.expcap.contain_exp", Long.toString(exp))); 147 | }else { 148 | newLore.set(0, ""); 149 | } 150 | meta.setLore(newLore); 151 | item.setItemMeta(meta); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/extrabackpack/ExtraBackpackConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.extrabackpack; 2 | 3 | import cat.nyaa.nyaacore.orm.annotations.Column; 4 | import cat.nyaa.nyaacore.orm.annotations.Table; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.OfflinePlayer; 7 | 8 | import java.util.UUID; 9 | 10 | 11 | @Table("backpackconfig") 12 | public class ExtraBackpackConfig { 13 | @Column(name = "player_id", primary = true) 14 | public UUID playerId; 15 | 16 | @Column(name = "max_line") 17 | public int maxLine; 18 | 19 | public int getMaxLine() { 20 | return maxLine; 21 | } 22 | 23 | public void setMaxLine(int maxLine) { 24 | this.maxLine = maxLine; 25 | } 26 | 27 | public OfflinePlayer getPlayer() { 28 | return Bukkit.getOfflinePlayer(playerId); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/extrabackpack/ExtraBackpackInventory.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.extrabackpack; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.OfflinePlayer; 5 | import org.bukkit.inventory.Inventory; 6 | import org.bukkit.inventory.InventoryHolder; 7 | 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | 11 | public class ExtraBackpackInventory { 12 | int size = 0; 13 | List inventories; 14 | OfflinePlayer owner; 15 | InventoryHolder holder; 16 | ExtraBackpackGUI gui; 17 | 18 | ExtraBackpackInventory(InventoryHolder holder) { 19 | inventories = new LinkedList<>(); 20 | this.holder = holder; 21 | this.gui = gui; 22 | } 23 | 24 | @Override 25 | public ExtraBackpackInventory clone(){ 26 | ExtraBackpackInventory clone = new ExtraBackpackInventory(holder); 27 | clone.size = size; 28 | clone.owner = owner; 29 | boolean empty = inventories.isEmpty(); 30 | for (int i = 0; i < inventories.size(); i++) { 31 | Inventory inventory = inventories.get(i); 32 | // FIXME: Inventory inventory1 = Bukkit.createInventory(holder, inventory.getSize(), inventory.getTitle()); 33 | String title = holder instanceof ExtraBackpackGUI ? ((ExtraBackpackGUI) holder).getInventoryTitle(i):""; 34 | Inventory inventory1 = Bukkit.createInventory(holder, inventory.getSize(), title); 35 | inventory1.setContents(inventory.getContents()); 36 | clone.inventories.add(inventory1); 37 | } 38 | return clone; 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/extrabackpack/ExtraBackpackLine.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.extrabackpack; 2 | 3 | import cat.nyaa.nyaacore.orm.annotations.Column; 4 | import cat.nyaa.nyaacore.orm.annotations.Table; 5 | import cat.nyaa.nyaacore.utils.ItemStackUtils; 6 | import org.bukkit.Bukkit; 7 | import org.bukkit.OfflinePlayer; 8 | import org.bukkit.inventory.ItemStack; 9 | 10 | import java.util.List; 11 | import java.util.UUID; 12 | 13 | @Table("backpackline") 14 | public class ExtraBackpackLine { 15 | @Column(name = "id", primary = true) 16 | public UUID id = UUID.randomUUID(); 17 | @Column(name = "player_id") 18 | public UUID playerId; 19 | 20 | @Column(name = "line_no") 21 | public int lineNo; 22 | 23 | @Column(name = "items", columnDefinition = "MEDIUMTEXT") 24 | private String items; 25 | 26 | public String getId() { 27 | return id.toString(); 28 | } 29 | 30 | public String getItems() { 31 | return items; 32 | } 33 | 34 | public void setItems(String items) { 35 | this.items = items; 36 | } 37 | 38 | public int getLineNo() { 39 | return lineNo; 40 | } 41 | 42 | public void setLineNo(int lineNo) { 43 | this.lineNo = lineNo; 44 | } 45 | 46 | public void setPlayerId(String owner) { 47 | this.playerId = UUID.fromString(owner); 48 | } 49 | 50 | public OfflinePlayer getPlayer() { 51 | return Bukkit.getOfflinePlayer(playerId); 52 | } 53 | 54 | public List getItemStacks() { 55 | List itemStacks = ItemStackUtils.itemsFromBase64(getItems()); 56 | if (itemStacks.size() != 9) { 57 | throw new IllegalArgumentException("Invalid line: " + itemStacks.size() + " items."); 58 | } 59 | return itemStacks; 60 | } 61 | 62 | public void setItemStacks(List itemStacks) { 63 | if (itemStacks.size() != 9) { 64 | throw new IllegalArgumentException("Invalid line given: " + itemStacks.size() + " items."); 65 | } 66 | setItems(ItemStackUtils.itemsToBase64(itemStacks)); 67 | } 68 | } -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/extrabackpack/ExtraBackpackListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.extrabackpack; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.Listener; 6 | import org.bukkit.event.inventory.InventoryClickEvent; 7 | import org.bukkit.event.inventory.InventoryCloseEvent; 8 | import org.bukkit.event.inventory.InventoryDragEvent; 9 | 10 | public class ExtraBackpackListener implements Listener { 11 | private final NyaaUtils plugin; 12 | 13 | public ExtraBackpackListener(NyaaUtils plugin) { 14 | this.plugin = plugin; 15 | if (!plugin.cfg.bp_enable) { 16 | return; 17 | } 18 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 19 | } 20 | 21 | @EventHandler 22 | public void onInventoryDrag(InventoryDragEvent event) { 23 | if (event.getInventory().getHolder() instanceof ExtraBackpackGUI) { 24 | ((ExtraBackpackGUI) event.getInventory().getHolder()).taint(); 25 | ((ExtraBackpackGUI) event.getInventory().getHolder()).onInventoryDrag(event); 26 | } 27 | } 28 | 29 | @EventHandler 30 | public void onInventoryClick(InventoryClickEvent event) { 31 | if (event.getInventory().getHolder() instanceof ExtraBackpackGUI) { 32 | ((ExtraBackpackGUI) event.getInventory().getHolder()).taint(); 33 | ((ExtraBackpackGUI) event.getInventory().getHolder()).onInventoryClick(event); 34 | } 35 | } 36 | 37 | @EventHandler 38 | public void onInventoryClose(InventoryCloseEvent event){ 39 | if (event.getInventory().getHolder() instanceof ExtraBackpackGUI) { 40 | ((ExtraBackpackGUI) event.getInventory().getHolder()).onInventoryClose(event); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/lootprotect/LootProtectListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.lootprotect; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.enchantments.Enchantment; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.EventPriority; 9 | import org.bukkit.event.Listener; 10 | import org.bukkit.event.entity.EntityDeathEvent; 11 | import org.bukkit.event.entity.EntityPickupItemEvent; 12 | import org.bukkit.event.player.PlayerExpChangeEvent; 13 | import org.bukkit.inventory.ItemStack; 14 | import org.bukkit.inventory.meta.Damageable; 15 | import org.bukkit.inventory.meta.ItemMeta; 16 | 17 | import java.util.*; 18 | import java.util.stream.Collectors; 19 | 20 | public class LootProtectListener implements Listener { 21 | final private NyaaUtils plugin; 22 | final private Map bypassPlayer = new HashMap<>(); 23 | final private Map bypassVanillaPlayer = new HashMap<>(); 24 | 25 | public enum VanillaStrategy { 26 | IGNORE, 27 | REJECT, 28 | ACCEPT 29 | } 30 | 31 | public LootProtectListener(NyaaUtils pl) { 32 | plugin = pl; 33 | plugin.getServer().getPluginManager().registerEvents(this, pl); 34 | } 35 | 36 | /** 37 | * @return true: loot protect is enabled 38 | * false: loot protect is disabled 39 | */ 40 | public boolean toggleStatus(UUID uuid) { 41 | if (bypassPlayer.containsKey(uuid)) { 42 | bypassPlayer.remove(uuid); 43 | return true; 44 | } else { 45 | bypassPlayer.put(uuid, uuid); 46 | return false; 47 | } 48 | } 49 | 50 | public void setVanillaStrategy(UUID uuid, VanillaStrategy strategy) { 51 | switch (strategy) { 52 | case IGNORE: 53 | case REJECT: 54 | bypassVanillaPlayer.put(uuid, strategy); 55 | break; 56 | case ACCEPT: 57 | bypassVanillaPlayer.remove(uuid); 58 | break; 59 | } 60 | } 61 | 62 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 63 | public void onMobKilled(EntityDeathEvent ev) { 64 | if (plugin.cfg.lootProtectMode == LootProtectMode.OFF || ev.getEntity() instanceof Player) 65 | return; 66 | Player p = null; 67 | if (plugin.cfg.lootProtectMode == LootProtectMode.MAX_DAMAGE) { 68 | p = plugin.dsListener.getMaxDamagePlayer(ev.getEntity()); 69 | } else if (plugin.cfg.lootProtectMode == LootProtectMode.FINAL_DAMAGE) { 70 | p = ev.getEntity().getKiller(); 71 | } 72 | if (p == null) return; 73 | if (bypassPlayer.containsKey(p.getUniqueId())) return; 74 | if (bypassVanillaPlayer.get(p.getUniqueId()) != null) { 75 | List customItems = ev.getDrops().stream().filter(item -> item.hasItemMeta() && item.getItemMeta().hasLore()).collect(Collectors.toList()); 76 | ev.getDrops().removeAll(customItems); 77 | Map leftItem = 78 | p.getInventory().addItem(customItems.toArray(new ItemStack[0])); 79 | ev.getDrops().addAll(leftItem.values()); 80 | } else { 81 | Map leftItem = 82 | p.getInventory().addItem(ev.getDrops().toArray(new ItemStack[0])); 83 | ev.getDrops().clear(); 84 | ev.getDrops().addAll(leftItem.values()); 85 | } 86 | giveExp(p, ev.getDroppedExp()); 87 | ev.setDroppedExp(0); 88 | } 89 | 90 | @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) 91 | public void onPickup(EntityPickupItemEvent e) { 92 | if (plugin.cfg.lootProtectMode == LootProtectMode.OFF || !(e.getEntity() instanceof Player)) 93 | return; 94 | Player p = (Player) e.getEntity(); 95 | if (!p.isSneaking() && bypassVanillaPlayer.get(p.getUniqueId()) == VanillaStrategy.REJECT) { 96 | ItemStack item = e.getItem().getItemStack(); 97 | if (!(item.hasItemMeta() && item.getItemMeta().hasLore())) { 98 | e.setCancelled(true); 99 | } 100 | } 101 | } 102 | 103 | /* Give exp to player, take Mending enchant into account */ 104 | // TODO move into NyaaCore 105 | private static void giveExp(Player p, int amount) { 106 | if (amount <= 0) return; 107 | List candidate = new ArrayList<>(13); 108 | 109 | for (ItemStack item : new ItemStack[]{ 110 | p.getInventory().getHelmet(), 111 | p.getInventory().getChestplate(), 112 | p.getInventory().getLeggings(), 113 | p.getInventory().getBoots(), 114 | p.getInventory().getItemInMainHand(), 115 | p.getInventory().getItemInOffHand()}) { 116 | if (item != null && item.hasItemMeta() && item.getItemMeta().hasEnchant(Enchantment.MENDING)) { 117 | if (item.getType().getMaxDurability() > 0 && ((Damageable) item.getItemMeta()).getDamage() > 0) { 118 | candidate.add(item); 119 | } 120 | } 121 | } 122 | 123 | ItemStack repair = null; 124 | if (candidate.size() > 0) { 125 | candidate.sort(LootProtectListener::compareByDamagePercentage); 126 | repair = candidate.get(0); 127 | } 128 | 129 | if (repair != null) { 130 | Damageable itemMeta = (Damageable) repair.getItemMeta(); 131 | int durability = itemMeta.getDamage(); 132 | int repairPoint = durability; 133 | if (amount * 2 < repairPoint) repairPoint = amount * 2; 134 | int expConsumption = ((repairPoint % 2) == 1) ? (repairPoint + 1) / 2 : repairPoint / 2; 135 | itemMeta.setDamage(durability - repairPoint); 136 | repair.setItemMeta((ItemMeta) itemMeta); 137 | amount -= expConsumption; 138 | } 139 | 140 | if (amount > 0) p.giveExp(amount); 141 | PlayerExpChangeEvent event = new PlayerExpChangeEvent(p, amount); 142 | Bukkit.getServer().getPluginManager().callEvent(event); 143 | } 144 | 145 | private static int compareByDamagePercentage(ItemStack a, ItemStack b) { 146 | float delta = (float) ((Damageable) a.getItemMeta()).getDamage() / a.getType().getMaxDurability() - (float) ((Damageable) b.getItemMeta()).getDamage() / b.getType().getMaxDurability(); 147 | delta = -delta; 148 | if (delta > 0) return 1; 149 | if (delta < 0) return -1; 150 | return 0; 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/lootprotect/LootProtectMode.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.lootprotect; 2 | 3 | public enum LootProtectMode { 4 | OFF, 5 | MAX_DAMAGE, 6 | FINAL_DAMAGE; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/mailbox/MailboxListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.mailbox; 2 | 3 | import cat.nyaa.nyaautils.I18n; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import org.bukkit.Location; 6 | import org.bukkit.Material; 7 | import org.bukkit.block.Block; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.EventPriority; 11 | import org.bukkit.event.Listener; 12 | import org.bukkit.event.block.Action; 13 | import org.bukkit.event.player.PlayerInteractEvent; 14 | import org.bukkit.event.player.PlayerJoinEvent; 15 | import org.bukkit.event.player.PlayerQuitEvent; 16 | import org.bukkit.scheduler.BukkitRunnable; 17 | 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | import java.util.function.Consumer; 21 | 22 | public class MailboxListener implements Listener { 23 | private final NyaaUtils plugin; 24 | private final Map> callbackMap = new HashMap<>(); 25 | private final Map timeoutListener = new HashMap<>(); 26 | 27 | public MailboxListener(NyaaUtils plugin) { 28 | this.plugin = plugin; 29 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 30 | } 31 | 32 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) 33 | public void onPlayerJoin(PlayerJoinEvent ev) { 34 | plugin.cfg.mailbox.updateNameMapping(ev.getPlayer().getUniqueId(), ev.getPlayer().getName()); 35 | } 36 | 37 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) 38 | public void onPlayerQuit(PlayerQuitEvent ev) { 39 | plugin.cfg.mailbox.updateNameMapping(ev.getPlayer().getUniqueId(), ev.getPlayer().getName()); 40 | } 41 | 42 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) 43 | public void onRightClickChest(PlayerInteractEvent ev) { 44 | if (callbackMap.containsKey(ev.getPlayer()) && ev.hasBlock() && ev.getAction() == Action.RIGHT_CLICK_BLOCK) { 45 | Block b = ev.getClickedBlock(); 46 | if (b.getType() == Material.CHEST || b.getType() == Material.TRAPPED_CHEST) { 47 | callbackMap.remove(ev.getPlayer()).accept(b.getLocation()); 48 | if (timeoutListener.containsKey(ev.getPlayer())) 49 | timeoutListener.remove(ev.getPlayer()).cancel(); 50 | ev.setCancelled(true); 51 | } 52 | } 53 | 54 | } 55 | 56 | public void registerRightClickCallback(Player p, int timeout, Consumer callback) { 57 | callbackMap.put(p, callback); 58 | BukkitRunnable runnable = new BukkitRunnable() { 59 | @Override 60 | public void run() { 61 | callbackMap.remove(p); 62 | if (p.isOnline()) { 63 | p.sendMessage(I18n.format("user.mailbox.right_click_timeout")); 64 | } 65 | } 66 | }; 67 | runnable.runTaskLater(plugin, timeout); 68 | timeoutListener.put(p, runnable); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/mailbox/MailboxLocations.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.mailbox; 2 | 3 | import cat.nyaa.nyaacore.configuration.FileConfigure; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import com.google.common.collect.BiMap; 6 | import com.google.common.collect.HashBiMap; 7 | import org.apache.commons.lang.Validate; 8 | import org.bukkit.Bukkit; 9 | import org.bukkit.Location; 10 | import org.bukkit.configuration.ConfigurationSection; 11 | import org.bukkit.entity.Player; 12 | import org.bukkit.plugin.java.JavaPlugin; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.UUID; 18 | import java.util.stream.Collectors; 19 | 20 | public class MailboxLocations extends FileConfigure { 21 | public final static String CFG_FILE_NAME = "mailbox_location.yml"; 22 | private final NyaaUtils plugin; 23 | 24 | private final BiMap nameMap = HashBiMap.create(); 25 | private final Map locationMap = new HashMap<>(); 26 | 27 | public MailboxLocations(NyaaUtils plugin) { 28 | this.plugin = plugin; 29 | } 30 | 31 | public static List getLoadedWorldsName() { 32 | return Bukkit.getWorlds().stream().map(world -> world.getName().toLowerCase()).collect(Collectors.toList()); 33 | } 34 | 35 | @Override 36 | protected String getFileName() { 37 | return CFG_FILE_NAME; 38 | } 39 | 40 | @Override 41 | protected JavaPlugin getPlugin() { 42 | return plugin; 43 | } 44 | 45 | @Override 46 | public void deserialize(ConfigurationSection config) { 47 | locationMap.clear(); 48 | nameMap.clear(); 49 | List loadedWorlds = getLoadedWorldsName(); 50 | ConfigurationSection locations = config.getConfigurationSection("locations"); 51 | ConfigurationSection names = config.getConfigurationSection("names"); 52 | if (locations != null) { 53 | for (String uuid_s : locations.getKeys(false)) { 54 | ConfigurationSection section = locations.getConfigurationSection(uuid_s); 55 | if (section == null) { 56 | locationMap.put(UUID.fromString(uuid_s), (Location) locations.get(uuid_s)); 57 | } else { 58 | String worldName = section.getString("world", "").toLowerCase(); 59 | if (loadedWorlds.contains(worldName)) { 60 | locationMap.put(UUID.fromString(uuid_s), new Location(Bukkit.getWorld(worldName), section.getInt("x"), section.getInt("y"), section.getInt("z"))); 61 | } 62 | } 63 | } 64 | } 65 | if (names != null) { 66 | for (String uuid_s : names.getKeys(false)) { 67 | nameMap.put(UUID.fromString(uuid_s), names.getString(uuid_s).toLowerCase()); 68 | } 69 | } 70 | 71 | for (Player p : plugin.getServer().getOnlinePlayers()) { 72 | nameMap.remove(p.getUniqueId()); 73 | nameMap.put(p.getUniqueId(), p.getName().toLowerCase()); 74 | } 75 | } 76 | 77 | @Override 78 | public void serialize(ConfigurationSection config) { 79 | ConfigurationSection locationSection = config.createSection("locations"); 80 | for (UUID uuid : locationMap.keySet()) { 81 | Location loc = locationMap.get(uuid); 82 | if (loc != null && loc.getWorld() != null && loc.getWorld().getName() != null) { 83 | String uuid_str = uuid.toString(); 84 | ConfigurationSection section = locationSection.createSection(uuid_str); 85 | section.set("world", loc.getWorld().getName()); 86 | section.set("x", loc.getX()); 87 | section.set("y", loc.getY()); 88 | section.set("z", loc.getZ()); 89 | } 90 | } 91 | ConfigurationSection nameSection = config.createSection("names"); 92 | for (UUID uuid : nameMap.keySet()) { 93 | nameSection.set(uuid.toString(), nameMap.get(uuid)); 94 | } 95 | } 96 | 97 | public void updateNameMapping(UUID uuid, String name) { 98 | Validate.notNull(uuid); 99 | Validate.notEmpty(name); 100 | name = name.toLowerCase(); 101 | if (name.equals(nameMap.get(uuid))) return; 102 | if (nameMap.containsValue(name)) return; 103 | nameMap.forcePut(uuid, name); 104 | save(); 105 | } 106 | 107 | public void updateLocationMapping(UUID uuid, Location location) { 108 | Validate.notNull(uuid); 109 | if (location == null) { // unset 110 | if (locationMap.containsKey(uuid)) { 111 | locationMap.remove(uuid); 112 | save(); 113 | } 114 | } else { 115 | if (!location.equals(locationMap.get(uuid))) { 116 | locationMap.put(uuid, location); 117 | save(); 118 | } 119 | } 120 | } 121 | 122 | public Location getMailboxLocation(String name) { 123 | return getMailboxLocation(getUUIDbyName(name)); 124 | } 125 | 126 | public Location getMailboxLocation(UUID uuid) { 127 | if (uuid == null) return null; 128 | Location loc = locationMap.get(uuid); 129 | if (loc == null || loc.getWorld() == null || !getLoadedWorldsName().contains(loc.getWorld().getName().toLowerCase())) { 130 | return null; 131 | } 132 | loc.setWorld(Bukkit.getWorld(loc.getWorld().getName())); 133 | return loc; 134 | } 135 | 136 | public UUID getUUIDbyName(String name) { 137 | if (name == null) return null; 138 | return nameMap.inverse().get(name.toLowerCase()); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/mention/MentionListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.mention; 2 | 3 | import cat.nyaa.nyaacore.utils.HexColorUtils; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import com.google.common.collect.Lists; 6 | import net.md_5.bungee.api.ChatMessageType; 7 | import net.md_5.bungee.api.chat.TextComponent; 8 | import org.bukkit.Bukkit; 9 | import org.bukkit.ChatColor; 10 | import org.bukkit.entity.Player; 11 | import org.bukkit.event.EventHandler; 12 | import org.bukkit.event.EventPriority; 13 | import org.bukkit.event.Listener; 14 | import org.bukkit.event.player.AsyncPlayerChatEvent; 15 | import org.bukkit.scheduler.BukkitRunnable; 16 | 17 | import java.util.Iterator; 18 | import java.util.Set; 19 | import java.util.stream.Collectors; 20 | 21 | // see cat.nyaa.nyaautils.commandwarpper.EsschatCmdWarpper for /msg 22 | public class MentionListener implements Listener { 23 | final private NyaaUtils plugin; 24 | 25 | public MentionListener(NyaaUtils pl) { 26 | plugin = pl; 27 | plugin.getServer().getPluginManager().registerEvents(this, pl); 28 | } 29 | 30 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 31 | public void AsyncChatEvent(AsyncPlayerChatEvent e) { 32 | if (!plugin.cfg.mention_enable) return; 33 | Runnable r = () -> { // In case if we got an asynchronous event 34 | if (e.getMessage().contains("@")) { 35 | Player sender = e.getPlayer(); 36 | String raw = e.getMessage(); 37 | String rep = raw.replace("@ ", "@"); 38 | Set playersNotified = Bukkit.getOnlinePlayers().parallelStream() 39 | .filter(p -> rep.contains("@" + p.getName())) 40 | .collect(Collectors.toSet()); 41 | notify(sender, raw, playersNotified, plugin); 42 | } 43 | }; 44 | if (e.isAsynchronous()) { 45 | Bukkit.getScheduler().runTask(plugin, r); 46 | } else { 47 | r.run(); 48 | } 49 | } 50 | 51 | public static void notify(Player sender, String m, Set playersNotified, NyaaUtils plugin) { 52 | playersNotified.forEach(p -> { 53 | if (m != null) { 54 | String raw = HexColorUtils.hexColored(m); 55 | String msg = sender.getDisplayName() + ChatColor.RESET + ": " + raw; 56 | switch (plugin.cfg.mention_notification) { 57 | case TITLE: 58 | if (plugin.cfg.mention_blink) { 59 | new BukkitRunnable() { 60 | int c = 3; 61 | 62 | @Override 63 | public void run() { 64 | p.sendTitle(msg, "", 3, 5, 2); 65 | if (--c == 0) this.cancel(); 66 | } 67 | }.runTaskTimer(plugin, 0, 10); 68 | } else { 69 | p.sendTitle(msg, "", 10, 20, 10); 70 | } 71 | break; 72 | case SUBTITLE: 73 | if (plugin.cfg.mention_blink) { 74 | new BukkitRunnable() { 75 | int c = 3; 76 | 77 | @Override 78 | public void run() { 79 | p.sendTitle("", msg, 3, 5, 2); 80 | if (--c == 0) this.cancel(); 81 | } 82 | }.runTaskTimer(plugin, 0, 10); 83 | } else { 84 | p.sendTitle("", msg, 10, 40, 10); 85 | } 86 | break; 87 | case ACTION_BAR: 88 | if (plugin.cfg.mention_blink) { 89 | new BukkitRunnable() { 90 | final Iterator color = Lists.charactersOf(plugin.cfg.mention_blink_char).listIterator(); 91 | 92 | @Override 93 | public void run() { 94 | p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(sender.getDisplayName() + ChatColor.RESET + ": " + ChatColor.COLOR_CHAR + color.next() + HexColorUtils.stripEssentialsFormat(raw))); 95 | if (!color.hasNext()) this.cancel(); 96 | } 97 | }.runTaskTimer(plugin, 0, 20); 98 | } else { 99 | p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(sender.getDisplayName() + ChatColor.RESET + ": " + raw)); 100 | } 101 | break; 102 | case NONE: 103 | break; 104 | } 105 | } 106 | new BukkitRunnable() { 107 | final Iterator sound = plugin.cfg.mention_sound.iterator(); 108 | final Iterator pitch = plugin.cfg.mention_pitch.iterator(); 109 | 110 | @Override 111 | public void run() { 112 | p.playSound(p.getEyeLocation(), sound.next(), 1, pitch.next().floatValue()); 113 | if (!sound.hasNext() || !pitch.hasNext()) this.cancel(); 114 | } 115 | }.runTaskTimer(plugin, 0, 5); 116 | }); 117 | } 118 | 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/mention/MentionNotification.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.mention; 2 | 3 | public enum MentionNotification { 4 | TITLE, 5 | SUBTITLE, 6 | ACTION_BAR, 7 | NONE 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/messagequeue/MessageQueue.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.messagequeue; 2 | 3 | import cat.nyaa.nyaacore.Message; 4 | import cat.nyaa.nyaacore.component.IMessageQueue; 5 | import cat.nyaa.nyaautils.I18n; 6 | import cat.nyaa.nyaautils.NyaaUtils; 7 | import net.ess3.api.events.AfkStatusChangeEvent; 8 | import net.md_5.bungee.chat.ComponentSerializer; 9 | import org.bukkit.OfflinePlayer; 10 | import org.bukkit.entity.Player; 11 | import org.bukkit.event.EventHandler; 12 | import org.bukkit.event.Listener; 13 | import org.bukkit.event.player.PlayerJoinEvent; 14 | 15 | import java.text.DateFormat; 16 | import java.time.Instant; 17 | import java.util.*; 18 | import java.util.stream.Collectors; 19 | 20 | public class MessageQueue implements IMessageQueue, Listener { 21 | 22 | final private NyaaUtils plugin; 23 | private Map messages; 24 | 25 | public MessageQueue(NyaaUtils pl) { 26 | plugin = pl; 27 | plugin.getServer().getPluginManager().registerEvents(this, pl); 28 | messages = new HashMap<>(); 29 | } 30 | 31 | @Override 32 | public void send(OfflinePlayer player, Message message, long timestamp) { 33 | if (!plugin.cfg.message_queue_enable) return; 34 | UUID uuid = player.getUniqueId(); 35 | String msg = messages.get(uuid); 36 | String current = timestamp + ":" + message.toString() + "\n"; 37 | msg = msg == null ? current : msg + current; 38 | messages.put(uuid, msg); 39 | } 40 | 41 | @Override 42 | public void send(OfflinePlayer player, Message message) { 43 | send(player, message, System.currentTimeMillis()); 44 | } 45 | 46 | @EventHandler 47 | public void onPlayerJoin(PlayerJoinEvent event) { 48 | if (!plugin.cfg.message_queue_enable) return; 49 | Player player = event.getPlayer(); 50 | sendQueue(player); 51 | } 52 | 53 | @EventHandler 54 | public void onPlayerAfkBack(AfkStatusChangeEvent event) { 55 | if (!plugin.cfg.message_queue_enable) return; 56 | if (event.getValue()) return; 57 | Player player = event.getAffected().getBase(); 58 | sendQueue(player); 59 | } 60 | 61 | private void sendQueue(Player player) { 62 | UUID uniqueId = player.getUniqueId(); 63 | String msg = messages.remove(uniqueId); 64 | if (msg == null) return; 65 | Map> map = 66 | Arrays.stream(msg.split("\n")).map(s -> s.split(":", 2)).collect(Collectors.groupingBy( 67 | s -> Long.parseLong(s[0]), 68 | Collectors.mapping(s -> s[1], Collectors.toList()) 69 | )); 70 | map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach( 71 | p -> { 72 | Date time = Date.from(Instant.ofEpochMilli(p.getKey())); 73 | p.getValue().forEach(msgJson -> { 74 | Message message = new Message("").append(I18n.format("user.mq.deliver", DateFormat.getDateTimeInstance().format(time)), Collections.singletonMap("{message}", ComponentSerializer.parse(msgJson)[0])); 75 | message.send(player); 76 | } 77 | ); 78 | } 79 | ); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaacore.configuration.FileConfigure; 4 | import cat.nyaa.nyaacore.configuration.ISerializable; 5 | import cat.nyaa.nyaautils.NyaaUtils; 6 | import org.bukkit.configuration.ConfigurationSection; 7 | import org.bukkit.plugin.java.JavaPlugin; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | import java.util.UUID; 12 | 13 | public class ParticleConfig extends FileConfigure { 14 | private final NyaaUtils plugin; 15 | @Serializable(manualSerialization = true) 16 | public Map particleSets = new HashMap<>(); 17 | @Serializable(manualSerialization = true) 18 | public Map playerSettings = new HashMap<>(); 19 | @Serializable 20 | public int index = 1; 21 | 22 | public ParticleConfig(NyaaUtils pl) { 23 | this.plugin = pl; 24 | } 25 | 26 | @Override 27 | protected String getFileName() { 28 | return "particles.yml"; 29 | } 30 | 31 | @Override 32 | protected JavaPlugin getPlugin() { 33 | return this.plugin; 34 | } 35 | 36 | @Override 37 | public void deserialize(ConfigurationSection config) { 38 | particleSets.clear(); 39 | playerSettings.clear(); 40 | ISerializable.deserialize(config, this); 41 | if (config.isConfigurationSection("particles")) { 42 | ConfigurationSection list = config.getConfigurationSection("particles"); 43 | for (String index : list.getKeys(false)) { 44 | ParticleSet p = new ParticleSet(); 45 | p.deserialize(list.getConfigurationSection(index)); 46 | particleSets.put(p.getId(), p); 47 | } 48 | } 49 | if (config.isConfigurationSection("playerSettings")) { 50 | ConfigurationSection list = config.getConfigurationSection("playerSettings"); 51 | for (String index : list.getKeys(false)) { 52 | PlayerSetting p = new PlayerSetting(index); 53 | p.deserialize(list.getConfigurationSection(index)); 54 | playerSettings.put(p.getUUID(), p); 55 | } 56 | } 57 | } 58 | 59 | @Override 60 | public void serialize(ConfigurationSection config) { 61 | ISerializable.serialize(config, this); 62 | config.set("particles", null); 63 | ConfigurationSection c = config.createSection("particles"); 64 | for (Integer k : particleSets.keySet()) { 65 | particleSets.get(k).serialize(c.createSection(k.toString())); 66 | } 67 | config.set("playerSettings", null); 68 | ConfigurationSection settings = config.createSection("playerSettings"); 69 | for (UUID k : playerSettings.keySet()) { 70 | playerSettings.get(k).serialize(settings.createSection(k.toString())); 71 | } 72 | } 73 | 74 | public PlayerSetting getPlayerSetting(UUID uuid) { 75 | if (!playerSettings.containsKey(uuid)) { 76 | playerSettings.put(uuid, new PlayerSetting(uuid, -1, -1, -1)); 77 | } 78 | return playerSettings.get(uuid); 79 | } 80 | 81 | public void setParticleSet(UUID uuid, ParticleType type, int id) { 82 | PlayerSetting setting = getPlayerSetting(uuid); 83 | if (type == ParticleType.PLAYER) { 84 | setting.setPlayer(id); 85 | } else if (type == ParticleType.ELYTRA) { 86 | setting.setElytra(id); 87 | } else if (type == ParticleType.OTHER) { 88 | setting.setOther(id); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleData.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import org.bukkit.*; 6 | import org.bukkit.block.data.BlockData; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.UUID; 14 | 15 | public class ParticleData implements ISerializable { 16 | @Serializable 17 | public int dustOptions_color = 0; 18 | @Serializable 19 | public double dustOptions_size = 0; 20 | @Serializable 21 | private Particle particle; 22 | @Serializable 23 | private int count; 24 | @Serializable 25 | private double offsetX; 26 | @Serializable 27 | private double offsetY; 28 | @Serializable 29 | private double offsetZ; 30 | @Serializable 31 | private double extra; 32 | @Serializable 33 | private long freq; 34 | @Serializable 35 | private Material material; 36 | private Map lastSend = new HashMap<>(); 37 | private Object data = null; 38 | 39 | public ParticleData() { 40 | 41 | } 42 | 43 | public Particle getParticle() { 44 | return particle; 45 | } 46 | 47 | public void setParticle(Particle particle) { 48 | this.particle = particle; 49 | } 50 | 51 | public int getCount() { 52 | return count; 53 | } 54 | 55 | public void setCount(int count) { 56 | this.count = count; 57 | } 58 | 59 | public double getOffsetX() { 60 | return offsetX; 61 | } 62 | 63 | public void setOffsetX(double offsetX) { 64 | this.offsetX = offsetX; 65 | } 66 | 67 | public double getOffsetY() { 68 | return offsetY; 69 | } 70 | 71 | public void setOffsetY(double offsetY) { 72 | this.offsetY = offsetY; 73 | } 74 | 75 | public double getOffsetZ() { 76 | return offsetZ; 77 | } 78 | 79 | public void setOffsetZ(double offsetZ) { 80 | this.offsetZ = offsetZ; 81 | } 82 | 83 | public double getExtra() { 84 | return extra; 85 | } 86 | 87 | public void setExtra(double extra) { 88 | this.extra = extra; 89 | } 90 | 91 | public long getFreq() { 92 | return freq; 93 | } 94 | 95 | public void setFreq(long freq) { 96 | this.freq = freq; 97 | } 98 | 99 | public void sendParticle(UUID uuid, Location loc, ParticleLimit limit, long time) { 100 | if (!lastSend.containsKey(uuid)) { 101 | lastSend.put(uuid, 0L); 102 | } 103 | if (time - lastSend.get(uuid) >= (freq < limit.getFreq() ? limit.getFreq() : freq) && 104 | NyaaUtils.instance.cfg.particles_enabled.contains(particle.name())) { 105 | lastSend.put(uuid, time); 106 | double distance = Bukkit.getViewDistance() * 16; 107 | distance *= distance; 108 | for (Player player : loc.getWorld().getPlayers()) { 109 | if (player.isValid() && !NyaaUtils.instance.particleTask.bypassPlayers.contains(player.getUniqueId()) 110 | && loc.distanceSquared(player.getLocation()) <= distance) { 111 | player.spawnParticle(particle, loc, 112 | count > limit.getAmount() ? limit.getAmount() : count, 113 | offsetX > limit.getOffsetX() ? limit.getOffsetX() : offsetX, 114 | offsetY > limit.getOffsetY() ? limit.getOffsetY() : offsetY, 115 | offsetZ > limit.getOffsetZ() ? limit.getOffsetZ() : offsetZ, 116 | extra > limit.getExtra() ? limit.getExtra() : extra, 117 | getData()); 118 | } 119 | } 120 | } 121 | } 122 | 123 | public Material getMaterial() { 124 | return material; 125 | } 126 | 127 | public void setMaterial(Material material) { 128 | this.material = material; 129 | } 130 | 131 | private Object getData() { 132 | if (data != null || particle.getDataType().equals(Void.class)) { 133 | return data; 134 | } else if (particle.getDataType().equals(ItemStack.class) && material != null && material.isItem()) { 135 | data = new ItemStack(material); 136 | } else if (particle.getDataType().equals(BlockData.class) && material != null && material.isBlock()) { 137 | data = material.createBlockData(); 138 | } else if (particle.getDataType().equals(Particle.DustOptions.class)) { 139 | data = new Particle.DustOptions(Color.fromRGB(dustOptions_color), (float) dustOptions_size); 140 | } 141 | return data; 142 | } 143 | 144 | @Override 145 | public void serialize(ConfigurationSection config) { 146 | ISerializable.serialize(config, this); 147 | config.set("version", Bukkit.getVersion()); 148 | } 149 | 150 | @SuppressWarnings("deprecation") 151 | @Override 152 | public void deserialize(ConfigurationSection config) { 153 | if (config.getString("version", "").length() == 0) { 154 | String materialName = config.getString("material", null); 155 | if (materialName != null) { 156 | Material m = Material.matchMaterial(materialName, true); 157 | if (m.isBlock() && config.isInt("dataValue")) { 158 | config.set("material", Bukkit.getUnsafe().fromLegacy(m, (byte) config.getInt("dataValue")).getMaterial().name()); 159 | } else { 160 | config.set("material", Bukkit.getUnsafe().fromLegacy(m).name()); 161 | } 162 | } 163 | } 164 | ISerializable.deserialize(config, this); 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleLimit.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | 5 | public class ParticleLimit implements ISerializable { 6 | @Serializable 7 | private double offsetX = 1.5; 8 | @Serializable 9 | private double offsetY = 1.5; 10 | @Serializable 11 | private double offsetZ = 1.5; 12 | @Serializable 13 | private int set = 3; 14 | @Serializable 15 | private int amount = 10; 16 | @Serializable 17 | private int freq = 3; 18 | @Serializable 19 | private double extra = 0.3D; 20 | 21 | public ParticleLimit() { 22 | 23 | } 24 | 25 | public double getOffsetX() { 26 | return offsetX; 27 | } 28 | 29 | public void setOffsetX(double offsetX) { 30 | this.offsetX = offsetX; 31 | } 32 | 33 | public double getOffsetY() { 34 | return offsetY; 35 | } 36 | 37 | public void setOffsetY(double offsetY) { 38 | this.offsetY = offsetY; 39 | } 40 | 41 | public double getOffsetZ() { 42 | return offsetZ; 43 | } 44 | 45 | public void setOffsetZ(double offsetZ) { 46 | this.offsetZ = offsetZ; 47 | } 48 | 49 | public int getSet() { 50 | return set; 51 | } 52 | 53 | public void setSet(int set) { 54 | this.set = set; 55 | } 56 | 57 | public int getAmount() { 58 | return amount; 59 | } 60 | 61 | public void setAmount(int amount) { 62 | this.amount = amount; 63 | } 64 | 65 | public int getFreq() { 66 | return freq; 67 | } 68 | 69 | public void setFreq(int freq) { 70 | this.freq = freq; 71 | } 72 | 73 | public double getExtra() { 74 | return extra; 75 | } 76 | 77 | public void setExtra(double extra) { 78 | this.extra = extra; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.EventPriority; 7 | import org.bukkit.event.Listener; 8 | import org.bukkit.event.entity.ProjectileLaunchEvent; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.UUID; 13 | 14 | public class ParticleListener implements Listener { 15 | public static List projectiles = new ArrayList<>(); 16 | public NyaaUtils plugin; 17 | 18 | public ParticleListener(NyaaUtils pl) { 19 | plugin = pl; 20 | plugin.getServer().getPluginManager().registerEvents(this, pl); 21 | } 22 | 23 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 24 | public void onProjectileLaunch(ProjectileLaunchEvent event) { 25 | if (plugin.cfg.particles_type_other && event.getEntity() != null && event.getEntity().getShooter() instanceof Player) { 26 | if (!plugin.particleTask.bypassPlayers.contains(((Player) event.getEntity().getShooter()).getUniqueId())) { 27 | projectiles.add(event.getEntity().getUniqueId()); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleSet.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import org.bukkit.Location; 6 | import org.bukkit.configuration.ConfigurationSection; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.UUID; 11 | 12 | public class ParticleSet implements ISerializable { 13 | @Serializable(manualSerialization = true) 14 | public List contents = new ArrayList<>(); 15 | @Serializable 16 | private int id; 17 | @Serializable 18 | private String name; 19 | @Serializable 20 | private String author; 21 | @Serializable 22 | private ParticleType type; 23 | 24 | @Override 25 | public void deserialize(ConfigurationSection config) { 26 | contents.clear(); 27 | ISerializable.deserialize(config, this); 28 | if (config.isConfigurationSection("contents")) { 29 | ConfigurationSection list = config.getConfigurationSection("contents"); 30 | for (String index : list.getKeys(false)) { 31 | ParticleData p = new ParticleData(); 32 | p.deserialize(list.getConfigurationSection(index)); 33 | contents.add(p); 34 | } 35 | } 36 | } 37 | 38 | @Override 39 | public void serialize(ConfigurationSection config) { 40 | ISerializable.serialize(config, this); 41 | config.set("contents", null); 42 | ConfigurationSection c = config.createSection("contents"); 43 | int i = 0; 44 | for (ParticleData p : contents) { 45 | p.serialize(c.createSection(String.valueOf(i))); 46 | i++; 47 | } 48 | } 49 | 50 | public int getId() { 51 | return id; 52 | } 53 | 54 | public void setId(int id) { 55 | this.id = id; 56 | } 57 | 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | public void setName(String name) { 63 | this.name = name; 64 | } 65 | 66 | public UUID getAuthor() { 67 | return UUID.fromString(author); 68 | } 69 | 70 | public void setAuthor(UUID author) { 71 | this.author = author.toString(); 72 | } 73 | 74 | public ParticleType getType() { 75 | return type; 76 | } 77 | 78 | public void setType(ParticleType type) { 79 | this.type = type; 80 | } 81 | 82 | public void sendParticle(UUID sender, Location loc, long time) { 83 | int i = 0; 84 | ParticleLimit limit = NyaaUtils.instance.cfg.particlesLimits.get(type); 85 | for (ParticleData data : contents) { 86 | if (i < limit.getSet()) { 87 | data.sendParticle(sender, loc, limit, time); 88 | } else { 89 | return; 90 | } 91 | i++; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleTask.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.GameMode; 6 | import org.bukkit.entity.Entity; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.entity.Projectile; 9 | import org.bukkit.scheduler.BukkitRunnable; 10 | 11 | import java.util.*; 12 | 13 | public class ParticleTask extends BukkitRunnable { 14 | public List bypassPlayers = new ArrayList<>(); 15 | private NyaaUtils plugin; 16 | 17 | public ParticleTask(NyaaUtils pl) { 18 | plugin = pl; 19 | runTaskTimer(plugin, 1, 1); 20 | } 21 | 22 | @Override 23 | public void run() { 24 | Collection vanishedPlayers = plugin.ess.getVanishedPlayersNew(); 25 | long time = System.currentTimeMillis() / 50; 26 | for (Player p : Bukkit.getOnlinePlayers()) { 27 | if (p.isValid() && p.getGameMode() != GameMode.SPECTATOR && !vanishedPlayers.contains(p.getName()) && 28 | !bypassPlayers.contains(p.getUniqueId())) { 29 | ParticleType type = null; 30 | if (!p.isGliding() && plugin.cfg.particles_type_player) { 31 | type = ParticleType.PLAYER; 32 | } else if (p.isGliding() && plugin.cfg.particles_type_elytra) { 33 | type = ParticleType.ELYTRA; 34 | } else { 35 | continue; 36 | } 37 | ParticleSet set = getParticleSet(p.getUniqueId(), type); 38 | if (set != null) { 39 | set.sendParticle(p.getUniqueId(), p.getLocation(), time); 40 | } 41 | } 42 | } 43 | Iterator iterator = ParticleListener.projectiles.iterator(); 44 | while (iterator.hasNext()) { 45 | UUID uuid = iterator.next(); 46 | Entity entity = Bukkit.getEntity(uuid); 47 | if (entity instanceof Projectile && entity.isValid() && !entity.isOnGround() && entity.getTicksLived() < 100) { 48 | if (((Projectile) entity).getShooter() instanceof Player) { 49 | UUID player = ((Player) ((Projectile) entity).getShooter()).getUniqueId(); 50 | ParticleSet set = getParticleSet(player, ParticleType.OTHER); 51 | if (set != null) { 52 | set.sendParticle(player, entity.getLocation(), time); 53 | } 54 | } 55 | } else { 56 | iterator.remove(); 57 | } 58 | } 59 | } 60 | 61 | public ParticleSet getParticleSet(UUID uuid, ParticleType type) { 62 | PlayerSetting setting = plugin.cfg.particleConfig.playerSettings.get(uuid); 63 | if (setting == null) { 64 | return null; 65 | } 66 | switch (type) { 67 | case PLAYER: 68 | return plugin.cfg.particleConfig.particleSets.get(setting.getPlayer()); 69 | case ELYTRA: 70 | return plugin.cfg.particleConfig.particleSets.get(setting.getElytra()); 71 | default: 72 | return plugin.cfg.particleConfig.particleSets.get(setting.getOther()); 73 | } 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/ParticleType.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | public enum ParticleType { 4 | PLAYER, ELYTRA, OTHER 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/particle/PlayerSetting.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.particle; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | 5 | import java.util.UUID; 6 | 7 | public class PlayerSetting implements ISerializable { 8 | @Serializable 9 | private int player; 10 | @Serializable 11 | private int elytra; 12 | @Serializable 13 | private int other; 14 | 15 | private UUID uuid; 16 | 17 | public PlayerSetting() { 18 | } 19 | 20 | public PlayerSetting(String uuid) { 21 | this.uuid = UUID.fromString(uuid); 22 | } 23 | 24 | public PlayerSetting(UUID uuid, int player, int elytra, int other) { 25 | setUUID(uuid); 26 | setPlayer(player); 27 | setElytra(elytra); 28 | setOther(other); 29 | } 30 | 31 | public int getPlayer() { 32 | return player; 33 | } 34 | 35 | public void setPlayer(int player) { 36 | this.player = player; 37 | } 38 | 39 | public int getElytra() { 40 | return elytra; 41 | } 42 | 43 | public void setElytra(int elytra) { 44 | this.elytra = elytra; 45 | } 46 | 47 | public int getOther() { 48 | return other; 49 | } 50 | 51 | public void setOther(int other) { 52 | this.other = other; 53 | } 54 | 55 | public UUID getUUID() { 56 | return uuid; 57 | } 58 | 59 | public void setUUID(UUID uuid) { 60 | this.uuid = uuid; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/realm/Realm.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.realm; 2 | 3 | 4 | import cat.nyaa.nyaacore.configuration.ISerializable; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.Location; 7 | import org.bukkit.OfflinePlayer; 8 | 9 | import java.util.UUID; 10 | 11 | public class Realm implements ISerializable { 12 | public static final String __DEFAULT__ = "__DEFAULT__"; 13 | @Serializable 14 | private String owner = ""; 15 | @Serializable 16 | private RealmType type = RealmType.PUBLIC; 17 | @Serializable 18 | private int priority = 0; 19 | @Serializable 20 | private String name = ""; 21 | @Serializable 22 | private String world; 23 | @Serializable 24 | private int maxX; 25 | @Serializable 26 | private int maxY; 27 | @Serializable 28 | private int maxZ; 29 | @Serializable 30 | private int minX; 31 | @Serializable 32 | private int minY; 33 | @Serializable 34 | private int minZ; 35 | public Realm() { 36 | 37 | } 38 | 39 | public Realm(Location pos1, Location pos2, RealmType type, OfflinePlayer owner) { 40 | world = pos1.getWorld().getName(); 41 | this.maxX = Math.max(pos1.getBlockX(), pos2.getBlockX()); 42 | this.maxY = Math.max(pos1.getBlockY(), pos2.getBlockY()); 43 | this.maxZ = Math.max(pos1.getBlockZ(), pos2.getBlockZ()); 44 | this.minX = Math.min(pos2.getBlockX(), pos1.getBlockX()); 45 | this.minY = Math.min(pos2.getBlockY(), pos1.getBlockY()); 46 | this.minZ = Math.min(pos2.getBlockZ(), pos1.getBlockZ()); 47 | setType(type); 48 | if (owner != null) { 49 | setOwner(owner); 50 | } 51 | } 52 | 53 | public int getPriority() { 54 | return priority; 55 | } 56 | 57 | public void setPriority(int priority) { 58 | this.priority = priority; 59 | } 60 | 61 | public int getMaxX() { 62 | return maxX; 63 | } 64 | 65 | public void setMaxX(int maxX) { 66 | this.maxX = maxX; 67 | } 68 | 69 | public int getMaxY() { 70 | return maxY; 71 | } 72 | 73 | public void setMaxY(int maxY) { 74 | this.maxY = maxY; 75 | } 76 | 77 | public int getMaxZ() { 78 | return maxZ; 79 | } 80 | 81 | public void setMaxZ(int maxZ) { 82 | this.maxZ = maxZ; 83 | } 84 | 85 | public int getMinX() { 86 | return minX; 87 | } 88 | 89 | public void setMinX(int minX) { 90 | this.minX = minX; 91 | } 92 | 93 | public int getMinY() { 94 | return minY; 95 | } 96 | 97 | public void setMinY(int minY) { 98 | this.minY = minY; 99 | } 100 | 101 | public int getMinZ() { 102 | return minZ; 103 | } 104 | 105 | public void setMinZ(int minZ) { 106 | this.minZ = minZ; 107 | } 108 | 109 | public OfflinePlayer getOwner() { 110 | if (owner != null && owner.length() > 0) { 111 | return Bukkit.getOfflinePlayer(UUID.fromString(owner)); 112 | } 113 | return null; 114 | } 115 | 116 | public void setOwner(OfflinePlayer player) { 117 | this.owner = player.getUniqueId().toString(); 118 | } 119 | 120 | public RealmType getType() { 121 | return type; 122 | } 123 | 124 | public void setType(RealmType type) { 125 | this.type = type; 126 | } 127 | 128 | public String getName() { 129 | return name; 130 | } 131 | 132 | public void setName(String name) { 133 | this.name = name; 134 | } 135 | 136 | public String getWorld() { 137 | return world; 138 | } 139 | 140 | public void setWorld(String world) { 141 | this.world = world; 142 | } 143 | 144 | public Location getMaxPos() { 145 | return new Location(Bukkit.getWorld(world), maxX, maxY, maxZ); 146 | } 147 | 148 | public void setMaxPos(Location pos1) { 149 | this.world = pos1.getWorld().getName(); 150 | this.maxX = pos1.getBlockX(); 151 | this.maxY = pos1.getBlockY(); 152 | this.maxZ = pos1.getBlockZ(); 153 | } 154 | 155 | public void setMaxPos(int x, int y, int z) { 156 | this.maxX = x; 157 | this.maxY = y; 158 | this.maxZ = z; 159 | } 160 | 161 | public Location getMinPos() { 162 | return new Location(Bukkit.getWorld(world), minX, minY, minZ); 163 | } 164 | 165 | public void setMinPos(Location pos2) { 166 | this.world = pos2.getWorld().getName(); 167 | this.minX = pos2.getBlockX(); 168 | this.minY = pos2.getBlockY(); 169 | this.minZ = pos2.getBlockZ(); 170 | } 171 | 172 | public void setMinPos(int x, int y, int z) { 173 | this.minX = x; 174 | this.minY = y; 175 | this.minZ = z; 176 | } 177 | 178 | public boolean inArea(Location loc) { 179 | if (loc.getWorld().getName().equals(world)) { 180 | if (maxX >= loc.getBlockX() && minX <= loc.getBlockX()) { 181 | if (maxY >= loc.getBlockY() && minY <= loc.getBlockY()) { 182 | if (maxZ >= loc.getBlockZ() && minZ <= loc.getBlockZ()) { 183 | return true; 184 | } 185 | } 186 | } 187 | } 188 | return false; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/realm/RealmCommands.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.realm; 2 | 3 | import cat.nyaa.nyaacore.LanguageRepository; 4 | import cat.nyaa.nyaacore.cmdreceiver.Arguments; 5 | import cat.nyaa.nyaacore.cmdreceiver.CommandReceiver; 6 | import cat.nyaa.nyaacore.cmdreceiver.SubCommand; 7 | import cat.nyaa.nyaautils.I18n; 8 | import cat.nyaa.nyaautils.NyaaUtils; 9 | import com.sk89q.worldedit.bukkit.BukkitAdapter; 10 | import com.sk89q.worldedit.regions.Region; 11 | import org.bukkit.Location; 12 | import org.bukkit.OfflinePlayer; 13 | import org.bukkit.command.CommandSender; 14 | import org.bukkit.entity.Player; 15 | 16 | public class RealmCommands extends CommandReceiver { 17 | private NyaaUtils plugin; 18 | 19 | public RealmCommands(Object plugin, LanguageRepository i18n) { 20 | super((NyaaUtils) plugin, i18n); 21 | this.plugin = (NyaaUtils) plugin; 22 | } 23 | 24 | @Override 25 | public String getHelpPrefix() { 26 | return "realm"; 27 | } 28 | 29 | @SubCommand(value = "create", permission = "nu.realm.admin") 30 | public void commandCreate(CommandSender sender, Arguments args) { 31 | if (args.length() < 4) { 32 | msg(sender, "manual.realm.create.usage"); 33 | return; 34 | } 35 | Player player = asPlayer(sender); 36 | String name = args.nextString(); 37 | if (plugin.cfg.realmConfig.realmList.containsKey(name)) { 38 | msg(sender, "user.realm.exist", name); 39 | return; 40 | } 41 | RealmType realmType = args.nextEnum(RealmType.class); 42 | Location pos1 = null; 43 | Location pos2 = null; 44 | if (args.remains() >= 6) { 45 | pos1 = new Location(player.getWorld(), args.nextInt(), args.nextInt(), args.nextInt()); 46 | pos2 = new Location(player.getWorld(), args.nextInt(), args.nextInt(), args.nextInt()); 47 | } else if (plugin.worldEditPlugin != null) { 48 | try { 49 | Region selection = plugin.worldEditPlugin.getSession(player).getSelection(BukkitAdapter.adapt(player.getWorld())); 50 | if (selection != null) { 51 | pos1 = BukkitAdapter.adapt(player.getWorld(), selection.getMinimumPoint()); 52 | pos2 = BukkitAdapter.adapt(player.getWorld(), selection.getMaximumPoint()); 53 | } 54 | } catch (Exception e) { 55 | //e.printStackTrace(); 56 | } 57 | } 58 | if (pos1 == null) { 59 | msg(sender, "user.realm.select"); 60 | return; 61 | } 62 | OfflinePlayer owner = null; 63 | if (realmType == RealmType.PRIVATE) { 64 | if (args.length() == 5) { 65 | owner = args.nextOfflinePlayer(); 66 | } else { 67 | msg(sender, "manual.realm.create.usage"); 68 | return; 69 | } 70 | } 71 | Realm realm = new Realm(pos1, pos2, realmType, owner); 72 | realm.setName(name); 73 | plugin.cfg.realmConfig.realmList.put(name, realm); 74 | plugin.cfg.save(); 75 | msg(sender, "user.realm.create"); 76 | } 77 | 78 | @SubCommand(value = "info", permission = "nu.realm.info") 79 | public void commandInfo(CommandSender sender, Arguments args) { 80 | Player player = asPlayer(sender); 81 | Realm realm = plugin.realmListener.getRealm(player.getLocation()); 82 | msg(sender, "user.realm.current_location", player.getLocation().getWorld().getName(), 83 | player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); 84 | if (realm == null || realm.getName().equals(Realm.__DEFAULT__)) { 85 | msg(sender, "user.realm.no_realm"); 86 | return; 87 | } 88 | String type = I18n.format("user.realm.realmtype." + realm.getType().name()); 89 | String owner = realm.getOwner() == null ? "" : I18n.format("user.realm.owner", realm.getOwner().getName()); 90 | msg(sender, "user.realm.info_0", realm.getName(), type, realm.getPriority(), owner); 91 | msg(sender, "user.realm.info_1", realm.getWorld(), 92 | realm.getMaxPos().getBlockX(), realm.getMaxPos().getBlockY(), realm.getMaxPos().getBlockZ(), 93 | realm.getMinPos().getBlockX(), realm.getMinPos().getBlockY(), realm.getMinPos().getBlockZ()); 94 | } 95 | 96 | @SubCommand(value = "remove", permission = "nu.realm.admin") 97 | public void commandRemove(CommandSender sender, Arguments args) { 98 | if (args.length() != 3) { 99 | msg(sender, "manual.realm.remove.usage"); 100 | return; 101 | } 102 | String name = args.next(); 103 | if (plugin.cfg.realmConfig.realmList.containsKey(name)) { 104 | plugin.cfg.realmConfig.realmList.remove(name); 105 | msg(sender, "user.realm.remove", name); 106 | plugin.cfg.save(); 107 | } else { 108 | msg(sender, "user.realm.not_found", name); 109 | return; 110 | } 111 | } 112 | 113 | @SubCommand(value = "list", permission = "nu.realm.admin") 114 | public void commandList(CommandSender sender, Arguments args) { 115 | int page = 1; 116 | if (args.length() == 3) { 117 | page = args.nextInt(); 118 | } 119 | int pageCount = (plugin.cfg.realmConfig.realmList.size() + 20 - 1) / 20; 120 | if (page < 1 || page > pageCount) { 121 | page = 1; 122 | } 123 | int i = 0; 124 | msg(sender, "user.realm.list.info_0", page, pageCount); 125 | for (Realm realm : plugin.cfg.realmConfig.realmList.values()) { 126 | i++; 127 | if (i > (page - 1) * 20 && i <= (page * 20)) { 128 | msg(sender, "user.realm.list.info_1", 129 | realm.getName(), 130 | I18n.format("user.realm.realmtype." + realm.getType().name()), realm.getPriority(), 131 | (realm.getOwner() == null ? "" : realm.getOwner().getName()), realm.getWorld(), 132 | realm.getMaxX(), realm.getMaxY(), realm.getMaxZ(), 133 | realm.getMinX(), realm.getMinY(), realm.getMinZ()); 134 | } 135 | } 136 | } 137 | 138 | @SubCommand(value = "setpriority", permission = "nu.realm.admin") 139 | public void commandSetPriority(CommandSender sender, Arguments args) { 140 | if (args.length() != 4) { 141 | msg(sender, "manual.realm.setpriority.usage"); 142 | return; 143 | } 144 | String name = args.next(); 145 | if (plugin.cfg.realmConfig.realmList.containsKey(name)) { 146 | int priority = args.nextInt(); 147 | plugin.cfg.realmConfig.realmList.get(name).setPriority(priority); 148 | msg(sender, "user.realm.setpriority", priority); 149 | plugin.cfg.save(); 150 | } else { 151 | msg(sender, "user.realm.not_found", name); 152 | return; 153 | } 154 | } 155 | 156 | @SubCommand(value = "mute", permission = "nu.realm.mute") 157 | public void commandMute(CommandSender sender, Arguments args) { 158 | Player player = asPlayer(sender); 159 | msg(sender, "user.realm.mute"); 160 | if (!this.plugin.realmListener.muteList.contains(player.getUniqueId())) { 161 | this.plugin.realmListener.muteList.add(player.getUniqueId()); 162 | } 163 | } 164 | 165 | @SubCommand(value = "unmute", permission = "nu.realm.mute") 166 | public void commandUnmute(CommandSender sender, Arguments args) { 167 | Player player = asPlayer(sender); 168 | this.plugin.realmListener.muteList.remove(player.getUniqueId()); 169 | msg(sender, "user.realm.unmute"); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/realm/RealmConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.realm; 2 | 3 | 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import cat.nyaa.nyaacore.configuration.FileConfigure; 6 | import cat.nyaa.nyaacore.configuration.ISerializable; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.plugin.java.JavaPlugin; 9 | 10 | import java.util.HashMap; 11 | 12 | public class RealmConfig extends FileConfigure { 13 | private final NyaaUtils plugin; 14 | public HashMap realmList = new HashMap<>(); 15 | 16 | public RealmConfig(NyaaUtils pl) { 17 | this.plugin = pl; 18 | } 19 | 20 | @Override 21 | protected String getFileName() { 22 | return "realm.yml"; 23 | } 24 | 25 | @Override 26 | protected JavaPlugin getPlugin() { 27 | return this.plugin; 28 | } 29 | 30 | @Override 31 | public void deserialize(ConfigurationSection config) { 32 | realmList.clear(); 33 | ISerializable.deserialize(config, this); 34 | if (config.isConfigurationSection("realms")) { 35 | ConfigurationSection list = config.getConfigurationSection("realms"); 36 | for (String k : list.getKeys(false)) { 37 | Realm realm = new Realm(); 38 | realm.deserialize(list.getConfigurationSection(k)); 39 | realmList.put(realm.getName(), realm); 40 | } 41 | } 42 | Realm realm = new Realm(); 43 | realm.setWorld("world"); 44 | realm.setMaxPos(0, 0, 0); 45 | realm.setMinPos(0, 0, 0); 46 | realm.setName(Realm.__DEFAULT__); 47 | realm.setPriority(-65535); 48 | realmList.put(realm.getName(), realm); 49 | } 50 | 51 | @Override 52 | public void serialize(ConfigurationSection config) { 53 | ISerializable.serialize(config, this); 54 | config.set("realms", null); 55 | if (!realmList.isEmpty()) { 56 | ConfigurationSection list = config.createSection("realms"); 57 | for (String k : realmList.keySet()) { 58 | realmList.get(k).serialize(list.createSection(k)); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/realm/RealmListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.realm; 2 | 3 | 4 | import cat.nyaa.nyaacore.utils.HexColorUtils; 5 | import cat.nyaa.nyaautils.I18n; 6 | import cat.nyaa.nyaautils.NyaaUtils; 7 | import cat.nyaa.nyaacore.Message; 8 | import cat.nyaa.nyaacore.Message.MessageType; 9 | import org.bukkit.ChatColor; 10 | import org.bukkit.Location; 11 | import org.bukkit.entity.Player; 12 | import org.bukkit.event.EventHandler; 13 | import org.bukkit.event.EventPriority; 14 | import org.bukkit.event.Listener; 15 | import org.bukkit.event.player.PlayerJoinEvent; 16 | import org.bukkit.event.player.PlayerMoveEvent; 17 | 18 | import java.util.ArrayList; 19 | import java.util.HashMap; 20 | import java.util.UUID; 21 | 22 | public class RealmListener implements Listener { 23 | public NyaaUtils plugin; 24 | public HashMap currentRealm = new HashMap<>(); 25 | public ArrayList muteList = new ArrayList<>(); 26 | 27 | public RealmListener(NyaaUtils pl) { 28 | plugin = pl; 29 | plugin.getServer().getPluginManager().registerEvents(this, pl); 30 | } 31 | 32 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 33 | public void onPlayerJoin(PlayerJoinEvent event) { 34 | if (!currentRealm.containsKey(event.getPlayer().getUniqueId())) { 35 | currentRealm.put(event.getPlayer().getUniqueId(), Realm.__DEFAULT__); 36 | } 37 | } 38 | 39 | @EventHandler 40 | public void onPlayerMove(PlayerMoveEvent event) { 41 | Player player = event.getPlayer(); 42 | UUID id = player.getUniqueId(); 43 | if(muteList.contains(id)){ 44 | return; 45 | } 46 | String currentRealmName = currentRealm.getOrDefault(id, ""); 47 | Realm realm = getRealm(player.getLocation()); 48 | if (realm == null) { 49 | return; 50 | } 51 | if (currentRealmName.equals(realm.getName()) && realm.inArea(player.getLocation())) { 52 | return; 53 | } 54 | if (!currentRealmName.equals(realm.getName()) && !Realm.__DEFAULT__.equals(realm.getName())) { 55 | currentRealm.put(id, realm.getName()); 56 | if(plugin.cfg.realm_notification_type == MessageType.TITLE){ 57 | String title, subtitle; 58 | if (realm.getType().equals(RealmType.PUBLIC)) { 59 | title = I18n.format("user.realm.notification.public_title", realm.getName()); 60 | subtitle = I18n.format("user.realm.notification.public_subtitle"); 61 | } else { 62 | title = I18n.format("user.realm.notification.private_title", realm.getName()); 63 | subtitle = I18n.format("user.realm.notification.private_subtitle", realm.getOwner().getName()); 64 | } 65 | Message.sendTitle(player, 66 | new Message(title).inner, 67 | new Message(subtitle).inner, 68 | plugin.cfg.realm_notification_title_fadein_tick, 69 | plugin.cfg.realm_notification_title_stay_tick, 70 | plugin.cfg.realm_notification_title_fadeout_tick 71 | ); 72 | }else{ 73 | if (realm.getType().equals(RealmType.PUBLIC)) { 74 | new Message(I18n.format("user.realm.notification.public", realm.getName())). 75 | send(player, plugin.cfg.realm_notification_type); 76 | } else { 77 | new Message(I18n.format("user.realm.notification.private", realm.getName(), 78 | realm.getOwner().getName())).send(player, plugin.cfg.realm_notification_type); 79 | } 80 | } 81 | return; 82 | } else if (!currentRealm.containsKey(id) || !Realm.__DEFAULT__.equals(currentRealmName)) { 83 | currentRealm.put(id, Realm.__DEFAULT__); 84 | new Message(HexColorUtils.hexColored( plugin.cfg.realm_default_name)) 85 | .send(player, plugin.cfg.realm_notification_type); 86 | } 87 | return; 88 | } 89 | 90 | public Realm getRealm(Location loc) { 91 | Realm realm = plugin.cfg.realmConfig.realmList.get(Realm.__DEFAULT__); 92 | for (Realm r : plugin.cfg.realmConfig.realmList.values()) { 93 | if (r.getName().equals(Realm.__DEFAULT__)) { 94 | continue; 95 | } 96 | if (r.inArea(loc) && (realm == null || realm.getPriority() < r.getPriority())) { 97 | realm = r; 98 | } 99 | } 100 | return realm; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/realm/RealmType.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.realm; 2 | 3 | public enum RealmType {PUBLIC, PRIVATE} 4 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/redstonecontrol/RedstoneControlListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.redstonecontrol; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import com.google.common.cache.Cache; 5 | import com.google.common.cache.CacheBuilder; 6 | import org.bukkit.Location; 7 | import org.bukkit.Material; 8 | import org.bukkit.block.Block; 9 | import org.bukkit.block.data.Lightable; 10 | import org.bukkit.block.data.type.RedstoneWire; 11 | import org.bukkit.event.EventHandler; 12 | import org.bukkit.event.EventPriority; 13 | import org.bukkit.event.Listener; 14 | import org.bukkit.event.block.Action; 15 | import org.bukkit.event.block.BlockRedstoneEvent; 16 | import org.bukkit.event.player.PlayerInteractEvent; 17 | import org.bukkit.inventory.EquipmentSlot; 18 | 19 | import java.util.concurrent.TimeUnit; 20 | 21 | public class RedstoneControlListener implements Listener { 22 | final private NyaaUtils plugin; 23 | final private Cache redstoneTorch; 24 | 25 | public RedstoneControlListener(NyaaUtils pl) { 26 | plugin = pl; 27 | plugin.getServer().getPluginManager().registerEvents(this, pl); 28 | redstoneTorch = CacheBuilder.newBuilder().expireAfterWrite(8, TimeUnit.SECONDS).build(); 29 | } 30 | 31 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) 32 | public void onRightClickRedstone(PlayerInteractEvent ev) { 33 | if (plugin.cfg.redstoneControl 34 | && ev.hasBlock() 35 | && ev.getAction() == Action.RIGHT_CLICK_BLOCK 36 | && ev.getHand() == EquipmentSlot.HAND 37 | && ev.getPlayer().hasPermission("nu.redstonecontrol") 38 | && ev.getPlayer().getInventory().getItemInMainHand().getType() == plugin.cfg.redstoneControlMaterial) { 39 | Block b = ev.getClickedBlock(); 40 | if (b.getType() == Material.REDSTONE_LAMP) { 41 | if (!ev.getPlayer().hasPermission("nu.redstonecontrol.lamp")) { 42 | return; 43 | } 44 | Lightable lightable = (Lightable) b.getBlockData(); 45 | lightable.setLit(!lightable.isLit()); 46 | b.setBlockData(lightable, false); 47 | ev.setCancelled(true); 48 | } else if (b.getType() == Material.REDSTONE_TORCH || b.getType() == Material.REDSTONE_WALL_TORCH) { 49 | if (!ev.getPlayer().hasPermission("nu.redstonecontrol.torch")) { 50 | return; 51 | } 52 | 53 | Lightable lightable = (Lightable) b.getBlockData(); 54 | lightable.setLit(!lightable.isLit()); 55 | b.setBlockData(lightable, false); 56 | redstoneTorch.put(b.getLocation(), lightable); 57 | ev.setCancelled(true); 58 | } else if (b.getType() == Material.REDSTONE_WIRE) { 59 | if (!ev.getPlayer().hasPermission("nu.redstonecontrol.wire")) { 60 | return; 61 | } 62 | RedstoneWire wire = (RedstoneWire) b.getBlockData(); 63 | wire.setPower((wire.getPower() + 1) % (wire.getMaximumPower() + 1)); 64 | b.setBlockData(wire, false); 65 | ev.setCancelled(true); 66 | } 67 | } 68 | } 69 | 70 | // See BlockRedstoneTorch 71 | // public static void a(IBlockData iblockdata, World world, BlockPosition blockposition, Random random, boolean flag) 72 | // if ((Boolean)iblockdata.get(LIT)) { 73 | // if (flag) { 74 | @EventHandler(priority = EventPriority.HIGHEST) 75 | public void onBlockRedstoneEvent(BlockRedstoneEvent event) { 76 | if (!plugin.cfg.redstoneControl) { 77 | return; 78 | } 79 | 80 | Block block = event.getBlock(); 81 | Lightable blockData = redstoneTorch.getIfPresent(block.getLocation()); 82 | if (blockData != null) { 83 | if (block.getBlockData().getClass() != blockData.getClass()) return; 84 | event.setNewCurrent(blockData.isLit() ? 15 : 0); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/repair/RepairConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.repair; 2 | 3 | import cat.nyaa.nyaacore.configuration.FileConfigure; 4 | import cat.nyaa.nyaacore.configuration.ISerializable; 5 | import cat.nyaa.nyaautils.NyaaUtils; 6 | import org.bukkit.Material; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.plugin.java.JavaPlugin; 9 | 10 | import java.util.HashMap; 11 | import java.util.HashSet; 12 | import java.util.Map; 13 | import java.util.Set; 14 | 15 | public class RepairConfig extends FileConfigure { 16 | public static class RepairConfigItem implements ISerializable { 17 | @Serializable 18 | Material material = Material.STONE; 19 | @Serializable 20 | int fullRepairCost = 1; 21 | @Serializable 22 | int expCost = 0; 23 | @Serializable 24 | double enchantCostPerLv = 0; 25 | @Serializable 26 | int repairLimit = 0; 27 | 28 | public RepairConfigItem normalize() { 29 | if (material == null) material = Material.STONE; 30 | if (fullRepairCost <= 0) fullRepairCost = 1; 31 | if (expCost < 0) expCost = 0; 32 | if (enchantCostPerLv < 0) enchantCostPerLv = 0; 33 | if (repairLimit <= 0) repairLimit = 0; 34 | return this; 35 | } 36 | } 37 | 38 | private final NyaaUtils plugin; 39 | 40 | private final Map repairMap = new HashMap<>(); 41 | 42 | public RepairConfig(NyaaUtils plugin) { 43 | this.plugin = plugin; 44 | } 45 | 46 | @Override 47 | protected String getFileName() { 48 | return "repair.yml"; 49 | } 50 | 51 | @Override 52 | protected JavaPlugin getPlugin() { 53 | return plugin; 54 | } 55 | 56 | @Override 57 | public void deserialize(ConfigurationSection config) { 58 | repairMap.clear(); 59 | for (String key : config.getKeys(false)) { 60 | Material m; 61 | try { 62 | m = Material.valueOf(key); 63 | } catch (IllegalArgumentException ex) { 64 | continue; 65 | } 66 | if (!config.isConfigurationSection(key)) continue; 67 | RepairConfigItem item = new RepairConfigItem(); 68 | item.deserialize(config.getConfigurationSection(key)); 69 | repairMap.put(m, item.normalize()); 70 | } 71 | } 72 | 73 | @Override 74 | public void serialize(ConfigurationSection config) { 75 | Set tmp = new HashSet<>(config.getKeys(false)); 76 | for (String key : tmp) { // clear section 77 | config.set(key, null); 78 | } 79 | 80 | for (Map.Entry pair : repairMap.entrySet()) { 81 | ConfigurationSection section = config.createSection(pair.getKey().name()); 82 | pair.getValue().normalize().serialize(section); 83 | } 84 | } 85 | 86 | public void addItem(Material m, RepairConfigItem item) { 87 | repairMap.put(m, item); 88 | save(); 89 | } 90 | 91 | public RepairConfigItem getRepairConfig(Material toolMaterial) { 92 | return repairMap.get(toolMaterial); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/repair/RepairInstance.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.repair; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.Material; 5 | import org.bukkit.enchantments.Enchantment; 6 | import org.bukkit.inventory.ItemStack; 7 | import org.bukkit.inventory.meta.Damageable; 8 | import org.bukkit.inventory.meta.Repairable; 9 | 10 | public class RepairInstance { 11 | public enum RepairStat { 12 | UNREPAIRABLE, 13 | UNREPAIRABLE_REPAIRED, 14 | UNREPAIRABLE_UNBREAKABLE, 15 | UNREPAIRABLE_RLE,// RepairLimitExceeded 16 | UNREPAIRABLE_LOWRECOVER, 17 | REPAIRABLE; 18 | } 19 | 20 | public RepairStat stat = RepairStat.UNREPAIRABLE; 21 | public Material repairMaterial; 22 | public int expConsumption; 23 | public int durRecovered; 24 | public int repairLimit; 25 | 26 | public RepairInstance(ItemStack item, RepairConfig config, NyaaUtils plugin) { 27 | if (item == null || item.getType() == Material.AIR) return; 28 | RepairConfig.RepairConfigItem cfg = config.getRepairConfig(item.getType()); 29 | if (cfg == null) return; 30 | if (!(item.getItemMeta() instanceof Repairable)) return; 31 | if (item.hasItemMeta() && item.getItemMeta().hasLore()) { 32 | if (!plugin.cfg.globalLoreBlacklist.canRepair(item.getItemMeta().getLore())) { 33 | stat = RepairStat.UNREPAIRABLE; 34 | return; 35 | } 36 | } 37 | stat = RepairStat.REPAIRABLE; 38 | if (item.getItemMeta().isUnbreakable()) { 39 | stat = RepairStat.UNREPAIRABLE_UNBREAKABLE; 40 | } 41 | Repairable repairableMeta = (Repairable) item.getItemMeta(); 42 | Damageable damageableMeta = (Damageable) item.getItemMeta(); 43 | repairLimit = cfg.repairLimit; 44 | if (repairLimit > 0 && repairableMeta.getRepairCost() >= repairLimit) { 45 | stat = RepairStat.UNREPAIRABLE_RLE; 46 | } 47 | 48 | Material toolMaterial = item.getType(); 49 | repairMaterial = cfg.material; 50 | int currentDurability = damageableMeta.getDamage(); 51 | if (currentDurability <= 0) { 52 | stat = RepairStat.UNREPAIRABLE_REPAIRED; 53 | } 54 | 55 | int enchLevel = 0; 56 | for (Enchantment ench : Enchantment.values()) { 57 | enchLevel += Math.max(item.getEnchantmentLevel(ench), 0); 58 | } 59 | 60 | int fullDurability = toolMaterial.getMaxDurability(); 61 | durRecovered = (int) Math.floor((double) fullDurability / ((double) cfg.fullRepairCost + (double) enchLevel * cfg.enchantCostPerLv)); 62 | expConsumption = (int) Math.floor(cfg.expCost + cfg.enchantCostPerLv * enchLevel); 63 | if (durRecovered <= 0) { 64 | stat = RepairStat.UNREPAIRABLE_LOWRECOVER; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/signedit/SignContent.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.signedit; 2 | 3 | import org.bukkit.block.Sign; 4 | import org.bukkit.inventory.ItemStack; 5 | import org.bukkit.inventory.meta.BlockStateMeta; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Arrays; 9 | import java.util.List; 10 | 11 | public class SignContent { 12 | private List content = new ArrayList<>(Arrays.asList("", "", "", "")); 13 | 14 | public SignContent() { 15 | 16 | } 17 | 18 | public static SignContent fromItemStack(ItemStack item) { 19 | SignContent content = new SignContent(); 20 | if (item.hasItemMeta() && item.getItemMeta() instanceof BlockStateMeta) { 21 | BlockStateMeta blockStateMeta = (BlockStateMeta) item.getItemMeta(); 22 | if (blockStateMeta.hasBlockState() && blockStateMeta.getBlockState() instanceof Sign) { 23 | Sign sign = ((Sign) blockStateMeta.getBlockState()); 24 | for (int i = 0; i < 4; i++) { 25 | content.setLine(i, sign.getLine(i)); 26 | } 27 | } 28 | } 29 | return content; 30 | } 31 | 32 | public void setLine(int line, String text) { 33 | if (line >= content.size()) { 34 | content.add(text); 35 | return; 36 | } 37 | content.set(line, text); 38 | } 39 | 40 | public String getLine(int line) { 41 | if (line >= content.size()) { 42 | return ""; 43 | } 44 | return content.get(line); 45 | } 46 | 47 | public List getContent() { 48 | return content; 49 | } 50 | 51 | public ItemStack toItemStack(ItemStack item) { 52 | if (item.getItemMeta() instanceof BlockStateMeta) { 53 | BlockStateMeta blockStateMeta = (BlockStateMeta) item.getItemMeta(); 54 | if (blockStateMeta.getBlockState() instanceof Sign) { 55 | Sign sign = ((Sign) blockStateMeta.getBlockState()); 56 | for (int i = 0; i < 4; i++) { 57 | sign.setLine(i, getLine(i)); 58 | } 59 | blockStateMeta.setBlockState(sign); 60 | } 61 | item.setItemMeta(blockStateMeta); 62 | } 63 | return item; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/signedit/SignEditCommands.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.signedit; 2 | 3 | import cat.nyaa.nyaacore.LanguageRepository; 4 | import cat.nyaa.nyaacore.Message; 5 | import cat.nyaa.nyaacore.cmdreceiver.Arguments; 6 | import cat.nyaa.nyaacore.cmdreceiver.BadCommandException; 7 | import cat.nyaa.nyaacore.cmdreceiver.CommandReceiver; 8 | import cat.nyaa.nyaacore.cmdreceiver.SubCommand; 9 | import cat.nyaa.nyaacore.utils.HexColorUtils; 10 | import cat.nyaa.nyaacore.utils.RayTraceUtils; 11 | import cat.nyaa.nyaautils.I18n; 12 | import cat.nyaa.nyaautils.NyaaUtils; 13 | import net.md_5.bungee.api.chat.ClickEvent; 14 | import org.bukkit.ChatColor; 15 | import org.bukkit.block.Block; 16 | import org.bukkit.block.Sign; 17 | import org.bukkit.command.CommandSender; 18 | import org.bukkit.entity.Player; 19 | import org.bukkit.inventory.ItemStack; 20 | 21 | public class SignEditCommands extends CommandReceiver { 22 | private final NyaaUtils plugin; 23 | 24 | public SignEditCommands(Object plugin, LanguageRepository i18n) { 25 | super((NyaaUtils) plugin, i18n); 26 | this.plugin = (NyaaUtils) plugin; 27 | } 28 | 29 | public static void printSignContent(Player player, SignContent content) { 30 | player.sendMessage(I18n.format("user.signedit.content")); 31 | for (int i = 0; i < 4; i++) { 32 | Message msg = new Message(I18n.format("user.signedit.content_line", i, content.getLine(i))); 33 | msg.inner.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND,"/nu se sign "+i+" "+content.getLine(i).replace('§','&'))); 34 | msg.send(player, Message.MessageType.CHAT); 35 | } 36 | } 37 | 38 | @Override 39 | public String getHelpPrefix() { 40 | return "se"; 41 | } 42 | 43 | @SubCommand(value = "edit", permission = "nu.se.admin") 44 | public void commandEdit(CommandSender sender, Arguments args) { 45 | Player player = asPlayer(sender); 46 | int line = args.nextInt(); 47 | if (line >= 0 && line < 4) { 48 | Block block = null; 49 | block = RayTraceUtils.rayTraceBlock(player); 50 | if (block != null && block.getState() instanceof Sign) { 51 | String text = args.nextString(); 52 | text = HexColorUtils.hexColored(text); 53 | if (HexColorUtils.stripEssentialsFormat(text).length() > plugin.cfg.signedit_max_length) { 54 | throw new BadCommandException("user.signedit.too_long", plugin.cfg.signedit_max_length); 55 | } 56 | if ("CLEAR".equalsIgnoreCase(text)) { 57 | text = ""; 58 | } 59 | Sign sign = (Sign) block.getState(); 60 | sign.setLine(line, text); 61 | sign.update(); 62 | } else { 63 | msg(sender, "user.signedit.not_sign"); 64 | } 65 | } else { 66 | msg(sender, "user.signedit.invalid_line"); 67 | } 68 | } 69 | 70 | @SubCommand(value = "sign", permission = "nu.se.player") 71 | public void commandSign(CommandSender sender, Arguments args) { 72 | Player player = asPlayer(sender); 73 | ItemStack item = getItemInHand(sender).clone(); 74 | if (!SignEditListener.isSign(item.getType())) { 75 | msg(sender, "user.signedit.need_sign"); 76 | return; 77 | } 78 | if (args.length() == 4) { 79 | int line = args.nextInt(); 80 | String text = args.nextString(); 81 | checkFormatCodes(text); 82 | text = HexColorUtils.hexColored( text); 83 | if (HexColorUtils.stripEssentialsFormat(text).length() > plugin.cfg.signedit_max_length) { 84 | throw new BadCommandException("user.signedit.too_long", plugin.cfg.signedit_max_length); 85 | } 86 | if (line >= 0 && line < 4) { 87 | SignContent signContent = SignContent.fromItemStack(item); 88 | if ("CLEAR".equalsIgnoreCase(text)) { 89 | text = ""; 90 | } 91 | signContent.setLine(line, text); 92 | printSignContent(player, signContent); 93 | player.getInventory().setItemInMainHand(signContent.toItemStack(item)); 94 | } else { 95 | msg(sender, "user.signedit.invalid_line"); 96 | } 97 | } else { 98 | printSignContent(player, SignContent.fromItemStack(item)); 99 | } 100 | } 101 | 102 | public void checkFormatCodes(String text) { 103 | for (String k : plugin.cfg.signedit_disabledFormattingCodes) { 104 | if (text.toUpperCase().contains("&" + k.toUpperCase())) { 105 | throw new BadCommandException("user.warn.blocked_format_codes", "&" + k); 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/signedit/SignEditListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.signedit; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import org.bukkit.GameMode; 5 | import org.bukkit.Material; 6 | import org.bukkit.Tag; 7 | import org.bukkit.block.Block; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.EventPriority; 11 | import org.bukkit.event.Listener; 12 | import org.bukkit.event.block.BlockPlaceEvent; 13 | import org.bukkit.event.block.SignChangeEvent; 14 | import org.bukkit.inventory.ItemStack; 15 | import org.bukkit.inventory.meta.BlockStateMeta; 16 | 17 | import java.util.*; 18 | 19 | public class SignEditListener implements Listener { 20 | private final NyaaUtils plugin; 21 | private Map signContents = new HashMap<>(); 22 | 23 | public SignEditListener(NyaaUtils pl) { 24 | plugin = pl; 25 | plugin.getServer().getPluginManager().registerEvents(this, plugin); 26 | } 27 | 28 | public static boolean isSign(Material m) { 29 | return Tag.SIGNS.isTagged(m); 30 | } 31 | 32 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) 33 | public void onBlockPlace(BlockPlaceEvent event) { 34 | Block block = event.getBlock(); 35 | ItemStack item = event.getItemInHand(); 36 | if (block != null && item != null && 37 | isSign(item.getType()) && 38 | isSign(block.getType())) { 39 | Player player = event.getPlayer(); 40 | if ((player.isOp() && player.getGameMode().equals(GameMode.CREATIVE)) || 41 | !item.hasItemMeta() || !(item.getItemMeta() instanceof BlockStateMeta) || 42 | !player.hasPermission("nu.se.player")) { 43 | return; 44 | } 45 | SignContent c = SignContent.fromItemStack(item); 46 | if (!c.getContent().isEmpty()) { 47 | signContents.put(event.getPlayer().getUniqueId(), c); 48 | } 49 | } 50 | } 51 | 52 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) 53 | public void onSignChange(SignChangeEvent event) { 54 | UUID uuid = event.getPlayer().getUniqueId(); 55 | if (signContents.containsKey(uuid)) { 56 | SignContent c = signContents.get(uuid); 57 | for (int i = 0; i < 4; i++) { 58 | event.setLine(i, c.getLine(i)); 59 | } 60 | signContents.remove(uuid); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/sit/SitLocation.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.sit; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class SitLocation implements ISerializable { 9 | @Serializable 10 | public List blocks = new ArrayList<>(); 11 | @Serializable 12 | public Double x; 13 | @Serializable 14 | public Double y; 15 | @Serializable 16 | public Double z; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/Checkpoint.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | 4 | import cat.nyaa.nyaacore.configuration.ISerializable; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.Location; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | 9 | public class Checkpoint implements ISerializable { 10 | @Serializable 11 | private String world; 12 | @Serializable 13 | private int max_x; 14 | @Serializable 15 | private int max_y; 16 | @Serializable 17 | private int max_z; 18 | @Serializable 19 | private int min_x; 20 | @Serializable 21 | private int min_y; 22 | @Serializable 23 | private int min_z; 24 | private String timerName = ""; 25 | private int checkpointID = 0; 26 | 27 | public Checkpoint() { 28 | 29 | } 30 | 31 | public Checkpoint(Location pos1, Location pos2) { 32 | this.world = pos1.getWorld().getName(); 33 | this.max_x = Math.max(pos1.getBlockX(), pos2.getBlockX()); 34 | this.max_y = Math.max(pos1.getBlockY(), pos2.getBlockY()); 35 | this.max_z = Math.max(pos1.getBlockZ(), pos2.getBlockZ()); 36 | this.min_x = Math.min(pos2.getBlockX(), pos1.getBlockX()); 37 | this.min_y = Math.min(pos2.getBlockY(), pos1.getBlockY()); 38 | this.min_z = Math.min(pos2.getBlockZ(), pos1.getBlockZ()); 39 | } 40 | 41 | public String getWorld() { 42 | return world; 43 | } 44 | 45 | public void setWorld(String world) { 46 | this.world = world; 47 | } 48 | 49 | public String getTimerName() { 50 | return timerName; 51 | } 52 | 53 | public void setTimerName(String timerName) { 54 | this.timerName = timerName; 55 | } 56 | 57 | public int getCheckpointID() { 58 | return checkpointID; 59 | } 60 | 61 | public void setCheckpointID(int checkpointID) { 62 | this.checkpointID = checkpointID; 63 | } 64 | 65 | public Location getMaxPos() { 66 | return new Location(Bukkit.getWorld(world), max_x, max_y, max_z); 67 | } 68 | 69 | public void setMaxPos(Location pos1) { 70 | this.world = pos1.getWorld().getName(); 71 | this.max_x = pos1.getBlockX(); 72 | this.max_y = pos1.getBlockY(); 73 | this.max_z = pos1.getBlockZ(); 74 | } 75 | 76 | public void setMaxPos(int x, int y, int z) { 77 | this.max_x = x; 78 | this.max_y = y; 79 | this.max_z = z; 80 | } 81 | 82 | public Location getMinPos() { 83 | return new Location(Bukkit.getWorld(world), min_x, min_y, min_z); 84 | } 85 | 86 | public void setMinPos(Location pos2) { 87 | this.min_x = pos2.getBlockX(); 88 | this.min_y = pos2.getBlockY(); 89 | this.min_z = pos2.getBlockZ(); 90 | } 91 | 92 | public void setMinPos(int x, int y, int z) { 93 | this.min_x = x; 94 | this.min_y = y; 95 | this.min_z = z; 96 | } 97 | 98 | public Checkpoint clone() { 99 | Checkpoint checkpoint = new Checkpoint(); 100 | checkpoint.setWorld(getWorld()); 101 | checkpoint.setMaxPos(max_x, max_y, max_z); 102 | checkpoint.setMinPos(min_x, min_y, min_z); 103 | checkpoint.setTimerName(getTimerName()); 104 | checkpoint.setCheckpointID(getCheckpointID()); 105 | return checkpoint; 106 | } 107 | 108 | public boolean inArea(Location loc) { 109 | if (loc.getWorld().getName().equals(world)) { 110 | if (max_x >= loc.getBlockX() && min_x <= loc.getBlockX()) { 111 | if (max_y >= loc.getBlockY() && min_y <= loc.getBlockY()) { 112 | if (max_z >= loc.getBlockZ() && min_z <= loc.getBlockZ()) { 113 | return true; 114 | } 115 | } 116 | } 117 | } 118 | return false; 119 | } 120 | 121 | @Override 122 | public void deserialize(ConfigurationSection config) { 123 | ISerializable.deserialize(config, this); 124 | } 125 | 126 | @Override 127 | public void serialize(ConfigurationSection config) { 128 | ISerializable.serialize(config, this); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/PlayerStats.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | import java.util.ArrayList; 6 | import java.util.UUID; 7 | 8 | public class PlayerStats { 9 | public ArrayList time = new ArrayList<>(); 10 | private UUID playerUUID; 11 | 12 | public PlayerStats(Player player) { 13 | playerUUID = player.getUniqueId(); 14 | } 15 | 16 | public UUID getPlayerUUID() { 17 | return playerUUID; 18 | } 19 | 20 | public void setPlayerUUID(UUID playerUUID) { 21 | this.playerUUID = playerUUID; 22 | } 23 | 24 | public void updateCheckpointTime(int checkpointID) { 25 | if (checkpointID < time.size()) { 26 | time.set(checkpointID, System.currentTimeMillis()); 27 | } else { 28 | time.add(checkpointID, System.currentTimeMillis()); 29 | } 30 | 31 | } 32 | 33 | public double getCheckpointTime(int checkpointID, int checkpoint2) { 34 | if (checkpointID < time.size()) { 35 | return ((time.get(checkpointID) - (double) time.get(checkpoint2)) / 1000); 36 | } 37 | return -1; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/Timer.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | import cat.nyaa.nyaacore.configuration.ISerializable; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.Location; 6 | import org.bukkit.configuration.ConfigurationSection; 7 | import org.bukkit.entity.Player; 8 | 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.UUID; 12 | 13 | public class Timer implements ISerializable { 14 | @Serializable 15 | public boolean point_broadcast = false; 16 | @Serializable 17 | public boolean finish_broadcast = true; 18 | public HashMap currentCheckpoint = new HashMap<>(); 19 | public HashMap playerStats = new HashMap<>(); 20 | @Serializable 21 | private String name = ""; 22 | @Serializable 23 | private boolean enable = false; 24 | private ArrayList checkpointList = new ArrayList<>(); 25 | 26 | public ArrayList getCheckpointList() { 27 | return checkpointList; 28 | } 29 | 30 | public void setCheckpointList(ArrayList checkpointList) { 31 | this.checkpointList = checkpointList; 32 | } 33 | 34 | public void updateCheckpointList() { 35 | ArrayList tmp = new ArrayList<>(); 36 | for (int i = 0; i < checkpointList.size(); i++) { 37 | Checkpoint checkpoint = checkpointList.get(i); 38 | checkpoint.setCheckpointID(i); 39 | tmp.add(checkpoint.clone()); 40 | } 41 | checkpointList = tmp; 42 | } 43 | 44 | public Checkpoint getCheckpoint(int id) { 45 | if (id < checkpointList.size()) { 46 | return checkpointList.get(id); 47 | } 48 | return null; 49 | } 50 | 51 | public String getName() { 52 | return name; 53 | } 54 | 55 | public void setName(String name) { 56 | this.name = name; 57 | } 58 | 59 | public boolean togglePointBroadcast() { 60 | point_broadcast = !point_broadcast; 61 | return point_broadcast; 62 | } 63 | 64 | public boolean toggleFinishBroadcast(){ 65 | finish_broadcast = !finish_broadcast; 66 | return finish_broadcast; 67 | } 68 | 69 | public int addCheckpoint(Location pos1, Location pos2) { 70 | Checkpoint checkpoint = new Checkpoint(pos1, pos2); 71 | checkpoint.setTimerName(getName()); 72 | checkpoint.setCheckpointID(checkpointList.size()); 73 | checkpointList.add(checkpoint.clone()); 74 | updateCheckpointList(); 75 | return checkpointList.size() - 1; 76 | } 77 | 78 | public int addCheckpoint(int index, Location pos1, Location pos2) { 79 | if (index <= checkpointList.size()) { 80 | Checkpoint checkpoint = new Checkpoint(pos1, pos2); 81 | checkpoint.setTimerName(getName()); 82 | checkpoint.setCheckpointID(index); 83 | checkpointList.add(index, checkpoint.clone()); 84 | updateCheckpointList(); 85 | return index; 86 | } else { 87 | Checkpoint checkpoint = new Checkpoint(pos1, pos2); 88 | checkpoint.setTimerName(getName()); 89 | checkpointList.add(checkpoint.clone()); 90 | updateCheckpointList(); 91 | return checkpointList.size() - 1; 92 | } 93 | } 94 | 95 | public int removeCheckpoint(int id) { 96 | if (getCheckpoint(id) != null) { 97 | checkpointList.remove(id); 98 | updateCheckpointList(); 99 | return checkpointList.size(); 100 | } 101 | return -1; 102 | } 103 | 104 | public void addPlayer(Player player) { 105 | playerStats.put(player.getUniqueId(), new PlayerStats(player)); 106 | setPlayerCurrentCheckpoint(player, 0); 107 | } 108 | 109 | public boolean containsPlayer(Player player) { 110 | return currentCheckpoint.containsKey(player.getUniqueId()); 111 | } 112 | 113 | public void removePlayer(Player player) { 114 | if (!containsPlayer(player)) { 115 | return; 116 | } 117 | playerStats.remove(player.getUniqueId()); 118 | currentCheckpoint.remove(player.getUniqueId()); 119 | } 120 | 121 | public void setPlayerCurrentCheckpoint(Player player, int checkpointID) { 122 | currentCheckpoint.put(player.getUniqueId(), checkpointID); 123 | getPlayerStats(player).updateCheckpointTime(checkpointID); 124 | } 125 | 126 | public int getPlayerCurrentCheckpoint(Player player) { 127 | if (!currentCheckpoint.containsKey(player.getUniqueId())) { 128 | return -1; 129 | } 130 | return currentCheckpoint.get(player.getUniqueId()); 131 | } 132 | 133 | public int getPlayerNextCheckpoint(Player player) { 134 | if (!currentCheckpoint.containsKey(player.getUniqueId())) { 135 | return -1; 136 | } 137 | return currentCheckpoint.get(player.getUniqueId()) + 1; 138 | } 139 | 140 | public PlayerStats getPlayerStats(Player player) { 141 | if (!playerStats.containsKey(player.getUniqueId())) { 142 | playerStats.put(player.getUniqueId(), new PlayerStats(player)); 143 | } 144 | return playerStats.get(player.getUniqueId()); 145 | } 146 | 147 | public void broadcast(Player player, String msg, CheckPointType type) { 148 | if(type== CheckPointType.NORMAL){ 149 | if(point_broadcast){ 150 | Bukkit.broadcastMessage(msg); 151 | }else{ 152 | player.sendMessage(msg); 153 | } 154 | }else{ 155 | if(finish_broadcast){ 156 | Bukkit.broadcastMessage(msg); 157 | }else{ 158 | player.sendMessage(msg); 159 | } 160 | } 161 | } 162 | 163 | public boolean isEnabled() { 164 | return (enable && (checkpointList.size() > 1)); 165 | } 166 | 167 | public void setEnable(boolean status) { 168 | enable = status; 169 | } 170 | 171 | public Timer clone() { 172 | Timer timer = new Timer(); 173 | timer.setName(getName()); 174 | timer.setCheckpointList(getCheckpointList()); 175 | timer.point_broadcast = point_broadcast; 176 | timer.finish_broadcast = finish_broadcast; 177 | timer.enable = enable; 178 | return timer; 179 | } 180 | 181 | public enum CheckPointType { 182 | NORMAL,FINISH 183 | } 184 | 185 | @Override 186 | public void deserialize(ConfigurationSection config) { 187 | ISerializable.deserialize(config, this); 188 | if (config.isConfigurationSection("checkpoint")) { 189 | ConfigurationSection list = config.getConfigurationSection("checkpoint"); 190 | for (String k : list.getKeys(false)) { 191 | Checkpoint checkpoint = new Checkpoint(); 192 | checkpoint.deserialize(list.getConfigurationSection(String.valueOf(k))); 193 | checkpoint.setTimerName(getName()); 194 | checkpoint.setCheckpointID(Integer.valueOf(k)); 195 | checkpointList.add(checkpoint.clone()); 196 | } 197 | } 198 | } 199 | 200 | @Override 201 | public void serialize(ConfigurationSection config) { 202 | ISerializable.serialize(config, this); 203 | config.set("checkpoint", null); 204 | if (!checkpointList.isEmpty()) { 205 | ConfigurationSection list = config.createSection("checkpoint"); 206 | for (int i = 0; i < checkpointList.size(); i++) { 207 | checkpointList.get(i).serialize(list.createSection(String.valueOf(i))); 208 | } 209 | } 210 | } 211 | 212 | } 213 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/TimerConfig.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | 4 | import cat.nyaa.nyaautils.NyaaUtils; 5 | import cat.nyaa.nyaacore.configuration.FileConfigure; 6 | import cat.nyaa.nyaacore.configuration.ISerializable; 7 | import org.bukkit.configuration.ConfigurationSection; 8 | import org.bukkit.plugin.java.JavaPlugin; 9 | 10 | import java.util.HashMap; 11 | 12 | public class TimerConfig extends FileConfigure { 13 | private final NyaaUtils plugin; 14 | public HashMap timers = new HashMap<>(); 15 | 16 | public TimerConfig(NyaaUtils pl) { 17 | this.plugin = pl; 18 | } 19 | 20 | @Override 21 | protected String getFileName() { 22 | return "timers.yml"; 23 | } 24 | 25 | @Override 26 | protected JavaPlugin getPlugin() { 27 | return this.plugin; 28 | } 29 | 30 | @Override 31 | public void deserialize(ConfigurationSection config) { 32 | timers.clear(); 33 | ISerializable.deserialize(config, this); 34 | if (config.isConfigurationSection("timers")) { 35 | ConfigurationSection list = config.getConfigurationSection("timers"); 36 | for (String k : list.getKeys(false)) { 37 | Timer timer = new Timer(); 38 | timer.deserialize(list.getConfigurationSection(k)); 39 | timers.put(timer.getName(), timer.clone()); 40 | } 41 | } 42 | } 43 | 44 | @Override 45 | public void serialize(ConfigurationSection config) { 46 | ISerializable.serialize(config, this); 47 | config.set("timers", null); 48 | if (!timers.isEmpty()) { 49 | ConfigurationSection list = config.createSection("timers"); 50 | for (String k : timers.keySet()) { 51 | timers.get(k).serialize(list.createSection(k)); 52 | } 53 | } 54 | 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/TimerListener.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | 4 | import cat.nyaa.nyaautils.I18n; 5 | import cat.nyaa.nyaautils.NyaaUtils; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.EventPriority; 9 | import org.bukkit.event.Listener; 10 | import org.bukkit.event.player.PlayerMoveEvent; 11 | 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.UUID; 15 | 16 | public class TimerListener implements Listener { 17 | public NyaaUtils plugin; 18 | public HashMap lastCheck = new HashMap<>(); 19 | public HashMap messageCooldown = new HashMap<>(); 20 | 21 | public TimerListener(NyaaUtils pl) { 22 | plugin = pl; 23 | plugin.getServer().getPluginManager().registerEvents(this, pl); 24 | } 25 | 26 | @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) 27 | public void playerMove(PlayerMoveEvent e) { 28 | Player p = e.getPlayer(); 29 | if (plugin.cfg.timerCheckInterval != -1) { 30 | if (lastCheck.containsKey(p.getUniqueId()) && 31 | !(System.currentTimeMillis() - lastCheck.get(p.getUniqueId()) >= plugin.cfg.timerCheckInterval)) { 32 | return; 33 | } else { 34 | lastCheck.put(p.getUniqueId(), System.currentTimeMillis()); 35 | } 36 | } 37 | ArrayList checkpointList = plugin.timerManager.getCheckpoint(p, true); 38 | if (!checkpointList.isEmpty()) { 39 | for (Checkpoint checkpoint : checkpointList) { 40 | Timer timer = plugin.timerManager.getTimer(checkpoint.getTimerName()); 41 | if (timer == null || !timer.isEnabled()) { 42 | continue; 43 | } 44 | if (checkpoint.getCheckpointID() == 0) { 45 | if (timer.getPlayerCurrentCheckpoint(p) == -1 || 46 | System.currentTimeMillis() - timer.getPlayerStats(p).time.get(0) > 5000) { 47 | timer.addPlayer(p); 48 | timer.setPlayerCurrentCheckpoint(p, 0); 49 | p.sendMessage(I18n.format("user.timer.start", checkpoint.getTimerName())); 50 | return; 51 | } 52 | } else if (timer.containsPlayer(p)) { 53 | if (timer.getPlayerCurrentCheckpoint(p) == checkpoint.getCheckpointID()) { 54 | return; 55 | } else if (timer.getPlayerNextCheckpoint(p) == checkpoint.getCheckpointID()) { 56 | timer.setPlayerCurrentCheckpoint(p, timer.getPlayerNextCheckpoint(p)); 57 | if (timer.getPlayerCurrentCheckpoint(p) == timer.getCheckpointList().size() - 1) { 58 | timer.broadcast(p, I18n.format("user.timer.finish_0", p.getName(), timer.getName()), Timer.CheckPointType.FINISH); 59 | PlayerStats stats = timer.getPlayerStats(p); 60 | stats.updateCheckpointTime(timer.getPlayerCurrentCheckpoint(p)); 61 | for (int i = 1; i < stats.time.size(); i++) { 62 | double time = stats.getCheckpointTime(i, i - 1); 63 | int minute = (int) (time / 60); 64 | double second = time % 60; 65 | timer.broadcast(p, I18n.format("user.timer.finish_1", i, minute, second), Timer.CheckPointType.FINISH); 66 | } 67 | double time = stats.getCheckpointTime(timer.getPlayerCurrentCheckpoint(p), 0); 68 | int minute = (int) (time / 60); 69 | double second = time % 60; 70 | timer.broadcast(p, I18n.format("user.timer.finish_2", minute, second), Timer.CheckPointType.FINISH); 71 | timer.removePlayer(p); 72 | } else { 73 | timer.setPlayerCurrentCheckpoint(p, checkpoint.getCheckpointID()); 74 | PlayerStats stats = timer.getPlayerStats(p); 75 | double time = stats.getCheckpointTime(timer.getPlayerCurrentCheckpoint(p), checkpoint.getCheckpointID() - 1); 76 | int minute = (int) (time / 60); 77 | double second = time % 60; 78 | timer.broadcast(p, I18n.format("user.timer.checkpoint_broadcast", 79 | checkpoint.getTimerName(), p.getName(), checkpoint.getCheckpointID(), minute, second), Timer.CheckPointType.NORMAL); 80 | return; 81 | } 82 | } else { 83 | if (!messageCooldown.containsKey(p.getUniqueId()) || 84 | System.currentTimeMillis() - messageCooldown.get(p.getUniqueId()) > 2000) { 85 | p.sendMessage(I18n.format("user.timer.invalid", timer.getName(), timer.getPlayerNextCheckpoint(p))); 86 | messageCooldown.put(p.getUniqueId(), System.currentTimeMillis()); 87 | return; 88 | } 89 | } 90 | } 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/timer/TimerManager.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.timer; 2 | 3 | import cat.nyaa.nyaautils.NyaaUtils; 4 | import com.sk89q.worldedit.bukkit.WorldEditPlugin; 5 | import org.bukkit.Location; 6 | import org.bukkit.entity.Player; 7 | 8 | import java.util.ArrayList; 9 | 10 | public class TimerManager { 11 | private final NyaaUtils plugin; 12 | 13 | public TimerManager(NyaaUtils pl) { 14 | plugin = pl; 15 | } 16 | 17 | public boolean createTimer(String name) { 18 | if (!plugin.cfg.timerConfig.timers.containsKey(name)) { 19 | Timer timer = new Timer(); 20 | timer.setName(name); 21 | plugin.cfg.timerConfig.timers.put(name, timer.clone()); 22 | return true; 23 | } 24 | return false; 25 | } 26 | 27 | public Timer getTimer(String name) { 28 | if (plugin.cfg.timerConfig.timers.containsKey(name)) { 29 | return plugin.cfg.timerConfig.timers.get(name); 30 | } 31 | return null; 32 | } 33 | 34 | public ArrayList getCheckpoint(Player player, boolean checkEnable) { 35 | return getCheckpoint(player.getLocation(), checkEnable); 36 | } 37 | 38 | public ArrayList getCheckpoint(Location loc, boolean checkEnable) { 39 | ArrayList list = new ArrayList<>(); 40 | if (!plugin.cfg.timerConfig.timers.isEmpty()) { 41 | for (Timer timer : plugin.cfg.timerConfig.timers.values()) { 42 | if (checkEnable && !timer.isEnabled()) { 43 | continue; 44 | } 45 | for (Checkpoint checkpoint : timer.getCheckpointList()) { 46 | if (checkpoint.inArea(loc)) { 47 | list.add(checkpoint.clone()); 48 | break; 49 | } 50 | } 51 | } 52 | } 53 | return list; 54 | } 55 | 56 | public boolean removeTimer(String name) { 57 | if (plugin.cfg.timerConfig.timers.containsKey(name)) { 58 | plugin.cfg.timerConfig.timers.remove(name); 59 | return true; 60 | } 61 | return false; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/tpsping/TpsPingTask.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.tpsping; 2 | 3 | import cat.nyaa.nyaacore.Pair; 4 | import cat.nyaa.nyaacore.utils.PlayerUtils; 5 | import cat.nyaa.nyaautils.NyaaUtils; 6 | import org.bukkit.Bukkit; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.scheduler.BukkitRunnable; 9 | import org.bukkit.scoreboard.DisplaySlot; 10 | import org.bukkit.scoreboard.Objective; 11 | import org.bukkit.scoreboard.Scoreboard; 12 | 13 | import java.util.*; 14 | import java.util.concurrent.ArrayBlockingQueue; 15 | import java.util.concurrent.ConcurrentHashMap; 16 | import java.util.concurrent.LinkedBlockingDeque; 17 | import java.util.function.Predicate; 18 | 19 | public class TpsPingTask extends BukkitRunnable { 20 | 21 | private final NyaaUtils plugin; 22 | private final Queue> tickMillisNano1200t = new ArrayBlockingQueue<>(1200); 23 | private final Queue tps600s = new ArrayBlockingQueue<>(600); 24 | 25 | private final Map> playerPing30s = new ConcurrentHashMap<>(); 26 | private long lastTickNano = System.nanoTime(); 27 | private byte lastSecondTick = 0; 28 | private long lastSecond = System.currentTimeMillis() / 1000L; 29 | 30 | public TpsPingTask(NyaaUtils plugin) { 31 | this.plugin = plugin; 32 | Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); 33 | Objective pingObj = mainScoreboard.getObjective("nyaautilsping"); 34 | if (plugin.cfg.ping_tab) { 35 | if (pingObj == null) { 36 | pingObj = mainScoreboard.registerNewObjective("nyaautilsping", "dummy", "Ping"); 37 | } 38 | pingObj.setDisplaySlot(DisplaySlot.PLAYER_LIST); 39 | } else if (pingObj != null) { 40 | pingObj.setDisplaySlot(null); 41 | } 42 | } 43 | 44 | @Override 45 | public void run() { 46 | long currentTimeMillis = System.currentTimeMillis(); 47 | 48 | if (plugin.cfg.tps_enable) { 49 | refreshTickTime(currentTimeMillis); 50 | } 51 | 52 | long currentSecond = currentTimeMillis / 1000L; 53 | if (currentSecond != lastSecond) { 54 | if (plugin.cfg.tps_enable) { 55 | refreshTps(currentSecond); 56 | } 57 | 58 | if (plugin.cfg.ping_enable) { 59 | refreshPing(); 60 | } 61 | } 62 | ++lastSecondTick; 63 | } 64 | 65 | private void refreshTickTime(long currentTimeMillis) { 66 | long nanoTime = System.nanoTime(); 67 | if (tickMillisNano1200t.size() == 1200) tickMillisNano1200t.poll(); 68 | long nanoInterval = nanoTime - lastTickNano; 69 | tickMillisNano1200t.add(new Pair<>(currentTimeMillis, nanoInterval)); 70 | lastTickNano = nanoTime; 71 | } 72 | 73 | private void refreshTps(long currentSecond) { 74 | while (++lastSecond < currentSecond) { 75 | if (tps600s.size() == 600) tps600s.poll(); 76 | tps600s.add((byte) 0); 77 | } 78 | if (tps600s.size() == 600) tps600s.poll(); 79 | tps600s.add(lastSecondTick); 80 | lastSecondTick = 0; 81 | } 82 | 83 | private void refreshPing() { 84 | Set offlined = new HashSet<>(); 85 | Bukkit.getOnlinePlayers().stream().filter(((Predicate) playerPing30s::containsKey).negate()).forEach(l -> playerPing30s.put(l, new LinkedBlockingDeque<>(30))); 86 | playerPing30s.forEach((player, pings) -> { 87 | if (!player.isOnline()) { 88 | offlined.add(player); 89 | return; 90 | } 91 | if (pings.size() == 30) pings.poll(); 92 | int playerPing = PlayerUtils.getPing(player); 93 | pings.add(playerPing); 94 | if (plugin.cfg.ping_tab) { 95 | Scoreboard scoreboard = player.getScoreboard(); 96 | Objective playerPingObj = scoreboard.getObjective("nyaautilsping"); 97 | if (playerPingObj != null) { 98 | playerPingObj.getScore(player.getName()).setScore(playerPing); 99 | } 100 | } 101 | }); 102 | offlined.forEach(playerPing30s::remove); 103 | } 104 | 105 | public Pair getTickNanoMax() { 106 | return tickMillisNano1200t.stream().max(Comparator.comparingLong(Pair::getValue)).orElse(null); 107 | } 108 | 109 | public long getTickNanoAvg() { 110 | long[] avg = tickMillisNano1200t.stream().mapToLong(Pair::getValue).collect(() -> new long[2], 111 | (ll, i) -> { 112 | ll[0]++; 113 | ll[1] += i; 114 | }, 115 | (ll, rr) -> { 116 | ll[0] += rr[0]; 117 | ll[1] += rr[1]; 118 | }); 119 | 120 | return avg[0] > 0 121 | ? avg[1] / avg[0] 122 | : 50 * 1000; 123 | } 124 | 125 | public List> getTickMillisNano() { 126 | return Collections.unmodifiableList(new ArrayList<>(tickMillisNano1200t)); 127 | } 128 | 129 | public List tpsHistory() { 130 | return Collections.unmodifiableList(new ArrayList<>(tps600s)); 131 | } 132 | 133 | public Map> getPlayerPing30s() { 134 | return Collections.unmodifiableMap(playerPing30s); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/cat/nyaa/nyaautils/vote/VoteTask.java: -------------------------------------------------------------------------------- 1 | package cat.nyaa.nyaautils.vote; 2 | 3 | import cat.nyaa.nyaacore.Message; 4 | import cat.nyaa.nyaautils.I18n; 5 | import net.md_5.bungee.api.chat.ClickEvent; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.scheduler.BukkitRunnable; 8 | 9 | import java.util.*; 10 | 11 | public class VoteTask extends BukkitRunnable { 12 | public String voteSubject = ""; 13 | public Map voteOptions = new HashMap<>(); 14 | public Map voteResults = new HashMap<>(); 15 | public Set votedPlayers = new HashSet<>(); 16 | public int timeout; 17 | public int ticks = 0; 18 | public int broadcastInterval = 0; 19 | 20 | public VoteTask(String subject, int timeout, int broadcast, Set options) { 21 | this.voteSubject = subject; 22 | this.timeout = timeout; 23 | this.broadcastInterval = broadcast; 24 | int i = 1; 25 | for (String option : options) { 26 | voteOptions.put(i, option); 27 | voteResults.put(i, 0); 28 | i++; 29 | } 30 | } 31 | 32 | @Override 33 | public void run() { 34 | ticks++; 35 | if (ticks == timeout) { 36 | cancel(); 37 | printOptions(true); 38 | } else if (ticks == 1 || (broadcastInterval > 0 && ticks % broadcastInterval == 0)) { 39 | printOptions(false); 40 | } 41 | } 42 | 43 | public void vote(Player player, int option) { 44 | if (voteOptions.containsKey(option)) { 45 | if (!votedPlayers.contains(player.getUniqueId())) { 46 | votedPlayers.add(player.getUniqueId()); 47 | voteResults.put(option, voteResults.get(option) + 1); 48 | player.sendMessage(I18n.format("user.vote.success", voteOptions.get(option))); 49 | } else { 50 | player.sendMessage(I18n.format("user.vote.repeat")); 51 | } 52 | } else { 53 | player.sendMessage(I18n.format("user.vote.unknown", option)); 54 | } 55 | } 56 | 57 | 58 | public void printOptions(boolean end) { 59 | if (!end) { 60 | new Message(I18n.format("user.vote.options_header", voteSubject)).broadcast(); 61 | } else { 62 | new Message(I18n.format("user.vote.result", voteSubject)).broadcast(); 63 | } 64 | for (Integer id : voteOptions.keySet()) { 65 | Message msg = new Message(I18n.format("user.vote.option", id, voteOptions.get(id), voteResults.get(id))); 66 | if (!end) { 67 | msg.inner.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/nu vote " + id)); 68 | } 69 | msg.broadcast(); 70 | } 71 | if (!end) { 72 | new Message(I18n.format("user.vote.options_footer", (timeout - ticks) / 20)).broadcast(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | database: 2 | extrabackpack: 3 | provider: sqlite 4 | sqlite_file: Backpack.db 5 | mysql_url: 6 | mysql_username: 7 | mysql_password: 8 | mysql_jdbc_driver: -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: NyaaUtils 2 | main: cat.nyaa.nyaautils.NyaaUtils 3 | description: "Helper/utilities plugin for Nyaacat Minecraft Server" 4 | version: ${version} 5 | depend: [Essentials,NyaaCore] 6 | softdepend: [LockettePro,HamsterEcoHelper,WorldEdit] 7 | authors: [RecursiveG,Cylin,Librazy] 8 | website: "https://github.com/NyaaCat/nyaautils" 9 | api-version: 1.15 10 | commands: 11 | nyaautils: 12 | description: The command for NyaaUtils 13 | aliases: nu 14 | permission: nu.command 15 | permission-message: "You do not have the required permission: " 16 | usage: "/ [SubCommand...] [Arguments...] or / help" 17 | 18 | permissions: 19 | nu.command: 20 | description: Base permission node for commands 21 | default: true 22 | nu.enchant: 23 | description: Permission node for self-serve enchanting 24 | default: true 25 | nu.show: 26 | description: Permission node for show item 27 | default: true 28 | nu.reload: 29 | description: Reload permission 30 | default: op 31 | nu.addenchsrc: 32 | description: Add item as enchantment source 33 | default: op 34 | nu.launch: 35 | description: Launch player into sky 36 | default: op 37 | nu.lootprotect: 38 | description: Toggle loot protect status 39 | default: true 40 | nu.dropprotect: 41 | description: Toggle drop protect status 42 | default: true 43 | nu.exhibition.set: 44 | description: Exhibition modification 45 | default: true 46 | nu.exhibition.unset: 47 | description: Exhibition modification 48 | default: true 49 | nu.exhibition.inv: 50 | description: Exhibition modification 51 | default: op 52 | nu.exhibition.uninv: 53 | description: Exhibition modification 54 | default: op 55 | nu.exhibition.desc: 56 | description: Exhibition modification 57 | default: true 58 | nu.exhibition.forceUnset: 59 | description: Exhibition modification 60 | default: op 61 | nu.prefix: 62 | default: true 63 | nu.suffix: 64 | default: true 65 | nu.format: 66 | default: true 67 | nu.project: 68 | description: Set player velocity 69 | default: op 70 | nu.enchantinfo: 71 | default: true 72 | nu.addfuel: 73 | default: op 74 | nu.givefuel: 75 | default: op 76 | nu.elytratoggle: 77 | default: true 78 | nu.mailbox: 79 | description: Basic permission requied for mailbox 80 | default: true 81 | nu.mailadmin: 82 | description: Administrative commands for mailbox 83 | default: op 84 | nu.repair: 85 | description: Repair item 86 | default: true 87 | nu.addrepair: 88 | description: Add repairable item 89 | default: op 90 | nu.createtimer: 91 | description: Add and remove timer 92 | default: op 93 | nu.rename: 94 | description: Rename item 95 | default: op 96 | nu.rename.blacklist: 97 | description: Bypass blacklist in renaming item 98 | default: false 99 | nu.setlore: 100 | description: Set or append item lore 101 | default: op 102 | nu.setbook: 103 | description: Set book author, title or unsign book 104 | default: op 105 | nu.realm.info: 106 | description: View realm info 107 | default: true 108 | nu.realm.mute: 109 | description: mute and unmute realm notification 110 | default: true 111 | nu.realm.admin: 112 | description: Create and remove realm 113 | default: op 114 | nu.particles.player: 115 | description: Select particle set 116 | default: true 117 | nu.particles.editor: 118 | description: Create and remove particle set 119 | default: op 120 | nu.particles.admin: 121 | description: Create and remove particle set 122 | default: op 123 | nu.se.player: 124 | description: Edit sign in your hand 125 | default: true 126 | nu.se.admin: 127 | description: Edit a sign 128 | default: op 129 | nu.expcap.store: 130 | description: Store experience 131 | default: true 132 | nu.expcap.restore: 133 | description: Restore experience 134 | default: true 135 | nu.expcap.set: 136 | description: Modify exp capsule 137 | default: op 138 | nu.vote: 139 | description: Start a vote 140 | default: true 141 | nu.redstonecontrol: 142 | description: Control redstone stuff by right click 143 | default: true 144 | nu.redstonecontrol.lamp: 145 | description: Light/off redstone lamp 146 | default: true 147 | nu.redstonecontrol.torch: 148 | description: Light/off redstone torch 149 | default: op 150 | nu.redstonecontrol.wire: 151 | description: Cycle through each level of power for redstone wire 152 | default: op 153 | nu.tps: 154 | description: Show TPS graph 155 | default: true 156 | nu.tps.verbose: 157 | description: Show TPS statics 158 | default: op 159 | nu.tps.tick: 160 | description: Show tick time record 161 | default: op 162 | nu.ping: 163 | description: Show player's ping 164 | default: true 165 | nu.ping.top: 166 | description: Show players' ping 167 | default: op 168 | nu.ping.others: 169 | description: Show other player's ping 170 | default: op 171 | nu.sit: 172 | description: allow player sit on blocks 173 | default: true 174 | nu.tpall: 175 | description: teleport all players to you 176 | default: op 177 | nu.bp.use: 178 | description: use extra backpack 179 | default: op 180 | nu.bp.admin: 181 | description: admin extra backpack 182 | default: op 183 | --------------------------------------------------------------------------------