diff --git a/.gitignore b/.gitignore index 9154f4c..c14283d 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ hs_err_pid* replay_pid* +build/ \ No newline at end of file diff --git a/.gradle/7.6.1/checksums/checksums.lock b/.gradle/7.6.1/checksums/checksums.lock new file mode 100644 index 0000000..3ef1a95 Binary files /dev/null and b/.gradle/7.6.1/checksums/checksums.lock differ diff --git a/.gradle/7.6.1/dependencies-accessors/dependencies-accessors.lock b/.gradle/7.6.1/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..b46b7e6 Binary files /dev/null and b/.gradle/7.6.1/dependencies-accessors/dependencies-accessors.lock differ diff --git a/.gradle/7.6.1/dependencies-accessors/gc.properties b/.gradle/7.6.1/dependencies-accessors/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/7.6.1/executionHistory/executionHistory.bin b/.gradle/7.6.1/executionHistory/executionHistory.bin new file mode 100644 index 0000000..02947e3 Binary files /dev/null and b/.gradle/7.6.1/executionHistory/executionHistory.bin differ diff --git a/.gradle/7.6.1/executionHistory/executionHistory.lock b/.gradle/7.6.1/executionHistory/executionHistory.lock new file mode 100644 index 0000000..34c7b53 Binary files /dev/null and b/.gradle/7.6.1/executionHistory/executionHistory.lock differ diff --git a/.gradle/7.6.1/fileChanges/last-build.bin b/.gradle/7.6.1/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/7.6.1/fileChanges/last-build.bin differ diff --git a/.gradle/7.6.1/fileHashes/fileHashes.bin b/.gradle/7.6.1/fileHashes/fileHashes.bin new file mode 100644 index 0000000..112a6bf Binary files /dev/null and b/.gradle/7.6.1/fileHashes/fileHashes.bin differ diff --git a/.gradle/7.6.1/fileHashes/fileHashes.lock b/.gradle/7.6.1/fileHashes/fileHashes.lock new file mode 100644 index 0000000..50964fd Binary files /dev/null and b/.gradle/7.6.1/fileHashes/fileHashes.lock differ diff --git a/.gradle/7.6.1/fileHashes/resourceHashesCache.bin b/.gradle/7.6.1/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000..1c7c4da Binary files /dev/null and b/.gradle/7.6.1/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/7.6.1/gc.properties b/.gradle/7.6.1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..891751f Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000..6e4d8c8 --- /dev/null +++ b/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Sun Jun 11 10:46:54 CEST 2023 +gradle.version=7.6.1 diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 0000000..cd19529 Binary files /dev/null and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe new file mode 100644 index 0000000..17e7484 Binary files /dev/null and b/.gradle/file-system.probe differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b589d56 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/discord.xml b/.idea/discord.xml new file mode 100644 index 0000000..d8e9561 --- /dev/null +++ b/.idea/discord.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..ce1c62c --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,16 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..3fd2793 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..5ccf79a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..9b0b45e --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/Hubbit.main.iml b/.idea/modules/Hubbit.main.iml new file mode 100644 index 0000000..f5de878 --- /dev/null +++ b/.idea/modules/Hubbit.main.iml @@ -0,0 +1,13 @@ + + + + + + + PAPER + ADVENTURE + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..7d5263a --- /dev/null +++ b/build.gradle @@ -0,0 +1,49 @@ +plugins { + id 'java' +} + +group = 'me.theclashfruit' +version = '0.1.0+1.19.4-alpha' + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = "https://repo.papermc.io/repository/maven-public/" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/groups/public/" + } + +} + +dependencies { + compileOnly "io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT" +} + +def targetJavaVersion = 17 +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } +} + +tasks.withType(JavaCompile).configureEach { + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + options.release = targetJavaVersion + } +} + +processResources { + def props = [version: version] + inputs.properties props + filteringCharset 'UTF-8' + + filesMatching('plugin.yml') { + expand props + } +} diff --git a/build/classes/java/main/me/theclashfruit/hubbit/Hubbit.class b/build/classes/java/main/me/theclashfruit/hubbit/Hubbit.class new file mode 100644 index 0000000..bf91225 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/Hubbit.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedBarChart.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedBarChart.class new file mode 100644 index 0000000..bb8afe1 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedBarChart.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedPie.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedPie.class new file mode 100644 index 0000000..a479549 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$AdvancedPie.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$CustomChart.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$CustomChart.class new file mode 100644 index 0000000..904bcec Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$CustomChart.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$DrilldownPie.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$DrilldownPie.class new file mode 100644 index 0000000..a99a0f7 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$DrilldownPie.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder$JsonObject.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder$JsonObject.class new file mode 100644 index 0000000..f183eee Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder$JsonObject.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder.class new file mode 100644 index 0000000..dbcd299 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$JsonObjectBuilder.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MetricsBase.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MetricsBase.class new file mode 100644 index 0000000..87c001c Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MetricsBase.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MultiLineChart.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MultiLineChart.class new file mode 100644 index 0000000..73fa83a Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$MultiLineChart.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimpleBarChart.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimpleBarChart.class new file mode 100644 index 0000000..af8287d Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimpleBarChart.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimplePie.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimplePie.class new file mode 100644 index 0000000..8fe80ff Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SimplePie.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SingleLineChart.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SingleLineChart.class new file mode 100644 index 0000000..bd299f4 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics$SingleLineChart.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics.class b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics.class new file mode 100644 index 0000000..814cece Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/bstats/Metrics.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/commands/InfoCommand.class b/build/classes/java/main/me/theclashfruit/hubbit/commands/InfoCommand.class new file mode 100644 index 0000000..bb0c315 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/commands/InfoCommand.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/commands/MenuCommand.class b/build/classes/java/main/me/theclashfruit/hubbit/commands/MenuCommand.class new file mode 100644 index 0000000..1a7b374 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/commands/MenuCommand.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/events/MenuListener.class b/build/classes/java/main/me/theclashfruit/hubbit/events/MenuListener.class new file mode 100644 index 0000000..d6ec687 Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/events/MenuListener.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/features/cosmetics/CloudsParticle.class b/build/classes/java/main/me/theclashfruit/hubbit/features/cosmetics/CloudsParticle.class new file mode 100644 index 0000000..5a6510a Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/features/cosmetics/CloudsParticle.class differ diff --git a/build/classes/java/main/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.class b/build/classes/java/main/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.class new file mode 100644 index 0000000..302ae0a Binary files /dev/null and b/build/classes/java/main/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.class differ diff --git a/build/libs/Hubbit-0.1.0+1.19.4-alpha.jar b/build/libs/Hubbit-0.1.0+1.19.4-alpha.jar new file mode 100644 index 0000000..1509361 Binary files /dev/null and b/build/libs/Hubbit-0.1.0+1.19.4-alpha.jar differ diff --git a/build/resources/main/config.yml b/build/resources/main/config.yml new file mode 100644 index 0000000..4af592a --- /dev/null +++ b/build/resources/main/config.yml @@ -0,0 +1 @@ +yes: 'yes' \ No newline at end of file diff --git a/build/resources/main/menu/server_menu.yml b/build/resources/main/menu/server_menu.yml new file mode 100644 index 0000000..db0685e --- /dev/null +++ b/build/resources/main/menu/server_menu.yml @@ -0,0 +1,22 @@ +title: '&3Servers' +size: 54 + +border: + enabled: true + material: 'BLACK_STAINED_GLASS_PANE' + +pages: + - title: '&3Servers' + items: + - name: '&aGetting Started' + material: 'OAK_SIGN' + slot: 22 + count: 1 + lore: + - '&7Edit menu/server_menu.yml to change this menu.' + events: + - type: 'click' + action: 'send_message' + data: '&aYou clicked on Getting Started!' + +navigation: false \ No newline at end of file diff --git a/build/resources/main/plugin.yml b/build/resources/main/plugin.yml new file mode 100644 index 0000000..7216752 --- /dev/null +++ b/build/resources/main/plugin.yml @@ -0,0 +1,15 @@ +name: Hubbit +version: '0.1.0+1.19.4-alpha' +main: me.theclashfruit.hubbit.Hubbit +api-version: 1.19 +load: STARTUP + +commands: + hubbit: + description: About Hubbit + usage: / + permission: hubbit.general.about + servers: + description: Server Menu + usage: / + permission: hubbit.player.menu \ No newline at end of file diff --git a/build/tmp/compileJava/compileTransaction/stash-dir/Hubbit.class.uniqueId2 b/build/tmp/compileJava/compileTransaction/stash-dir/Hubbit.class.uniqueId2 new file mode 100644 index 0000000..bf91225 Binary files /dev/null and b/build/tmp/compileJava/compileTransaction/stash-dir/Hubbit.class.uniqueId2 differ diff --git a/build/tmp/compileJava/compileTransaction/stash-dir/MenuCommand.class.uniqueId1 b/build/tmp/compileJava/compileTransaction/stash-dir/MenuCommand.class.uniqueId1 new file mode 100644 index 0000000..3be6380 Binary files /dev/null and b/build/tmp/compileJava/compileTransaction/stash-dir/MenuCommand.class.uniqueId1 differ diff --git a/build/tmp/compileJava/compileTransaction/stash-dir/MenuListener.class.uniqueId0 b/build/tmp/compileJava/compileTransaction/stash-dir/MenuListener.class.uniqueId0 new file mode 100644 index 0000000..2493d68 Binary files /dev/null and b/build/tmp/compileJava/compileTransaction/stash-dir/MenuListener.class.uniqueId0 differ diff --git a/build/tmp/compileJava/previous-compilation-data.bin b/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..194032f Binary files /dev/null and b/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/build/tmp/jar/MANIFEST.MF b/build/tmp/jar/MANIFEST.MF new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/build/tmp/jar/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e69de29 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..943f0cb Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5083229 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..65dcd68 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..89c3889 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Hubbit' diff --git a/src/main/java/me/theclashfruit/hubbit/Hubbit.java b/src/main/java/me/theclashfruit/hubbit/Hubbit.java new file mode 100644 index 0000000..a57b503 --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/Hubbit.java @@ -0,0 +1,37 @@ +package me.theclashfruit.hubbit; + +import me.theclashfruit.hubbit.bstats.Metrics; +import me.theclashfruit.hubbit.commands.InfoCommand; +import me.theclashfruit.hubbit.commands.MenuCommand; +import me.theclashfruit.hubbit.events.MenuListener; +import me.theclashfruit.hubbit.utils.ConfigLoaderSingleton; +import org.bukkit.plugin.java.JavaPlugin; + +public final class Hubbit extends JavaPlugin { + + @Override + public void onEnable() { + // Register Commands + this.getCommand("hubbit").setExecutor(new InfoCommand()); + this.getCommand("servers").setExecutor(new MenuCommand()); + + // Register Events + this.getServer().getPluginManager().registerEvents(new MenuListener(), this); + + // Config + this.saveDefaultConfig(); + this.saveResource("menu/server_menu.yml", false); + + // Load Singletons + ConfigLoaderSingleton.getInstance(); + + // bStats + Metrics metrics = new Metrics(this, 18720); + } + + @Override + public void onDisable() { + // Unload Singletons + ConfigLoaderSingleton.destroyInstance(); + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/bstats/Metrics.java b/src/main/java/me/theclashfruit/hubbit/bstats/Metrics.java new file mode 100644 index 0000000..5a27ede --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/bstats/Metrics.java @@ -0,0 +1,881 @@ +/* + * This Metrics class was auto-generated and can be copied into your project if you are + * not using a build tool like Gradle or Maven for dependency management. + * + * IMPORTANT: You are not allowed to modify this class, except changing the package. + * + * Disallowed modifications include but are not limited to: + * - Remove the option for users to opt-out + * - Change the frequency for data submission + * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) + * - Reformat the code (if you use a linter, add an exception) + * + * Violations will result in a ban of your plugin and account from bStats. + */ +package me.theclashfruit.hubbit.bstats; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +public class Metrics { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** Shuts down the underlying scheduler service. */ + public void shutdown() { + metricsBase.shutdown(); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "3.0.2"; + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final ScheduledExecutorService scheduler; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics")); + // We want delayed tasks (non-periodic) that will execute in the future to be + // cancelled when the scheduler is shutdown. + // Otherwise, we risk preventing the server from shutting down even when + // MetricsBase#shutdown() is called + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.scheduler = scheduler; + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + // WARNING: Removing the option to opt-out will get your plugin banned from + // bStats + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + public void shutdown() { + scheduler.shutdown(); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven + // distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into + // the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the + // submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just + // don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong + // package names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public abstract static class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; + } + + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + /** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ + public static class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/commands/InfoCommand.java b/src/main/java/me/theclashfruit/hubbit/commands/InfoCommand.java new file mode 100644 index 0000000..1585fd2 --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/commands/InfoCommand.java @@ -0,0 +1,15 @@ +package me.theclashfruit.hubbit.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; + +public class InfoCommand implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + sender.sendMessage("hubbit lmao"); + + return true; + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/commands/MenuCommand.java b/src/main/java/me/theclashfruit/hubbit/commands/MenuCommand.java new file mode 100644 index 0000000..e484f59 --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/commands/MenuCommand.java @@ -0,0 +1,87 @@ +package me.theclashfruit.hubbit.commands; + +import me.theclashfruit.hubbit.Hubbit; +import me.theclashfruit.hubbit.utils.ConfigLoaderSingleton; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.util.List; +import java.util.Map; + +import static org.bukkit.Bukkit.getLogger; +import static org.bukkit.plugin.java.JavaPlugin.getPlugin; + +public class MenuCommand implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + FileConfiguration menuConfig = ConfigLoaderSingleton.getInstance().getMenuFileConfig(); + + if(sender instanceof Player) { + Player player = (Player) sender; + + Inventory menu = Bukkit.createInventory(player, menuConfig.getInt("size"), ChatColor.translateAlternateColorCodes('&', menuConfig.getString("title"))); + + int inventorySize = menuConfig.getInt("size"); + + getLogger().log(java.util.logging.Level.INFO, menuConfig.getMapList("pages").toString()); + + if (menuConfig.getBoolean("border.enabled") && menuConfig.getInt("size") >= 27) { + ItemStack borderItem = new ItemStack(Material.valueOf(menuConfig.getString("border.material")), 1); + + ItemMeta borderItemMeta = borderItem.getItemMeta(); + + borderItemMeta.setDisplayName(" "); + + borderItem.setItemMeta(borderItemMeta); + + for (int i = 0; i < inventorySize; i++) { + if (i < 9 || i > (inventorySize - 10) || i % 9 == 0 || i % 9 == 8) { + menu.setItem(i, borderItem); + } + } + } + + menuConfig.getMapList("pages").forEach(page -> { + List> items = (List>) page.get("items"); + + items.forEach(item -> { + ItemStack itemStack = new ItemStack(Material.valueOf((String) item.get("material")), (int) item.get("count")); + + ItemMeta itemMeta = itemStack.getItemMeta(); + + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', (String) item.get("name"))); + + List lore = (List) item.get("lore"); + + for (int i = 0; i < lore.size(); i++) { + lore.set(i, ChatColor.translateAlternateColorCodes('&', lore.get(i))); + } + + itemMeta.setLore(lore); + + itemStack.setItemMeta(itemMeta); + + menu.setItem((int) item.get("slot"), itemStack); + }); + }); + + player.openInventory(menu); + } else { + sender.sendMessage("You must be a player to use this command!"); + } + + return true; + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/events/MenuListener.java b/src/main/java/me/theclashfruit/hubbit/events/MenuListener.java new file mode 100644 index 0000000..56bb0b7 --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/events/MenuListener.java @@ -0,0 +1,19 @@ +package me.theclashfruit.hubbit.events; + +import me.theclashfruit.hubbit.utils.ConfigLoaderSingleton; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; + +public class MenuListener implements Listener { + @EventHandler + public void onClick(InventoryClickEvent event) { + FileConfiguration menuConfig = ConfigLoaderSingleton.getInstance().getMenuFileConfig(); + + if(event.getView().getTitle().equalsIgnoreCase(ChatColor.translateAlternateColorCodes('&', menuConfig.getString("title")))) { + event.setCancelled(true); + } + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.java b/src/main/java/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.java new file mode 100644 index 0000000..ca67faa --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/integrations/cosmetics/ParticleCosmetic.java @@ -0,0 +1,19 @@ +package me.theclashfruit.hubbit.integrations.cosmetics; + +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Player; + +import java.util.List; + +public interface ParticleCosmetic { + String name = "Example Particle"; + String description = "This is an example particle"; + Material item = Material.WHITE_WOOL; + String permission = "hubbit.particle.example"; + List particles = List.of(Particle.CLOUD); + + static boolean whileEquipped(Player player) { + return false; + } +} diff --git a/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoader.java b/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoader.java new file mode 100644 index 0000000..014d99e --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoader.java @@ -0,0 +1,15 @@ +package me.theclashfruit.hubbit.utils; + +import me.theclashfruit.hubbit.Hubbit; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; + +import static org.bukkit.plugin.java.JavaPlugin.getPlugin; + +public class ConfigLoader { + public @org.jetbrains.annotations.NotNull YamlConfiguration getMenuFileConfig() { + return YamlConfiguration.loadConfiguration(new File(getPlugin(Hubbit.class).getDataFolder() + "/menu/server_menu.yml")); + } +} + diff --git a/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoaderSingleton.java b/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoaderSingleton.java new file mode 100644 index 0000000..f654ced --- /dev/null +++ b/src/main/java/me/theclashfruit/hubbit/utils/ConfigLoaderSingleton.java @@ -0,0 +1,22 @@ +package me.theclashfruit.hubbit.utils; + +public class ConfigLoaderSingleton { + private static ConfigLoader instance = null; + + private ConfigLoaderSingleton() { + instance = new ConfigLoader(); + } + + public static ConfigLoader getInstance() { + if (instance == null) { + instance = new ConfigLoader(); + } + return instance; + } + + public static Boolean destroyInstance() { + instance = null; + + return true; + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..4af592a --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1 @@ +yes: 'yes' \ No newline at end of file diff --git a/src/main/resources/menu/server_menu.yml b/src/main/resources/menu/server_menu.yml new file mode 100644 index 0000000..db0685e --- /dev/null +++ b/src/main/resources/menu/server_menu.yml @@ -0,0 +1,22 @@ +title: '&3Servers' +size: 54 + +border: + enabled: true + material: 'BLACK_STAINED_GLASS_PANE' + +pages: + - title: '&3Servers' + items: + - name: '&aGetting Started' + material: 'OAK_SIGN' + slot: 22 + count: 1 + lore: + - '&7Edit menu/server_menu.yml to change this menu.' + events: + - type: 'click' + action: 'send_message' + data: '&aYou clicked on Getting Started!' + +navigation: false \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..0b8ed98 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,15 @@ +name: Hubbit +version: '${version}' +main: me.theclashfruit.hubbit.Hubbit +api-version: 1.19 +load: STARTUP + +commands: + hubbit: + description: About Hubbit + usage: / + permission: hubbit.general.about + servers: + description: Server Menu + usage: / + permission: hubbit.player.menu \ No newline at end of file