diff --git a/folia/build.gradle b/folia/build.gradle index 55335ee7..dbaa16c3 100644 --- a/folia/build.gradle +++ b/folia/build.gradle @@ -3,7 +3,7 @@ plugins { id 'maven-publish' id 'com.github.johnrengelman.shadow' version '7.1.2' } -version = "2.18.9" +version = "2.18.10" repositories { mavenCentral() @@ -44,7 +44,7 @@ dependencies { //compileOnly 'net.citizensnpcs:citizens-main:2.0.30-SNAPSHOT' // compileOnly fileTree(dir:'lib',include:['*.jar']) - implementation 'org.xerial:sqlite-jdbc:3.39.3.0' + //implementation 'org.xerial:sqlite-jdbc:3.39.3.0' implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.google.code.gson:gson:2.10' } diff --git a/link.cmd b/link.cmd index 407786d5..5d5aed0d 100644 --- a/link.cmd +++ b/link.cmd @@ -1,4 +1,5 @@ mklink /j "folia/src/main/java/coloryr/allmusic/core" "core" +mklink /j "server_top/src/main/java/coloryr/allmusic/core" "core" mklink /j "server/src/main/java/coloryr/allmusic/core" "core" mklink /j "forge_1_19_3/src/main/java/coloryr/allmusic/core" "core" mklink /j "forge_1_18_2/src/main/java/coloryr/allmusic/core" "core" @@ -9,6 +10,7 @@ mklink /j "fabric_1_18_2/src/main/java/coloryr/allmusic/core" "core" mklink /j "fabric_1_16_5/src/main/java/coloryr/allmusic/core" "core" mklink /j "folia/build" "build" +mklink /j "server_top/build" "build" mklink /j "server/build" "build" mklink /j "forge_1_19_3/build" "build" mklink /j "forge_1_18_2/build" "build" @@ -19,6 +21,7 @@ mklink /j "fabric_1_18_2/build" "build" mklink /j "fabric_1_16_5/build" "build" mklink /j "folia/.gradle" ".gradle" +mklink /j "server_top/.gradle" ".gradle" mklink /j "server/.gradle" ".gradle" mklink /j "forge_1_19_3/.gradle" ".gradle" mklink /j "forge_1_18_2/.gradle" ".gradle" diff --git a/remove.cmd b/remove.cmd index 42618ccf..b4a2af69 100644 --- a/remove.cmd +++ b/remove.cmd @@ -1,5 +1,6 @@ rmdir "folia/src/main/java/coloryr/allmusic/core" rmdir "server/src/main/java/coloryr/allmusic/core" +rmdir "server_top/src/main/java/coloryr/allmusic/core" rmdir "forge_1_19_3/src/main/java/coloryr/allmusic/core" rmdir "forge_1_18_2/src/main/java/coloryr/allmusic/core" rmdir "forge_1_16_5/src/main/java/coloryr/allmusic/core" @@ -10,6 +11,7 @@ rmdir "fabric_1_16_5/src/main/java/coloryr/allmusic/core" rmdir "folia/build" rmdir "server/build" +rmdir "server_top/build" rmdir "forge_1_19_3/build" rmdir "forge_1_18_2/build" rmdir "forge_1_16_5/build" @@ -20,6 +22,7 @@ rmdir "fabric_1_16_5/build" rmdir "folia/.gradle" rmdir "server/.gradle" +rmdir "server_top/.gradle" rmdir "forge_1_19_3/.gradle" rmdir "forge_1_18_2/.gradle" rmdir "forge_1_16_5/.gradle" diff --git a/server/build.gradle b/server/build.gradle index d4469cfd..88a932e8 100644 --- a/server/build.gradle +++ b/server/build.gradle @@ -3,7 +3,7 @@ plugins { id 'maven-publish' id 'com.github.johnrengelman.shadow' version '6.1.0' } -version = "2.18.9" +version = "2.18.10" repositories { mavenCentral() @@ -35,9 +35,9 @@ dependencies { //implementation 'mysql:mysql-connector-java:8.0.31' compileOnly 'org.spigotmc:spigot-api:1.19.2-R0.1-SNAPSHOT' - compileOnly 'net.md-5:bungeecord-api:1.19-R0.1-SNAPSHOT' + //compileOnly 'net.md-5:bungeecord-api:1.19-R0.1-SNAPSHOT' compileOnly "com.github.MilkBowl:VaultAPI:1.7.1" - compileOnly 'com.velocitypowered:velocity-api:3.0.0' + //compileOnly 'com.velocitypowered:velocity-api:3.0.0' compileOnly 'me.clip:placeholderapi:2.10.10' //compileOnly 'net.citizensnpcs:citizens-main:2.0.30-SNAPSHOT' // compileOnly fileTree(dir:'lib',include:['*.jar']) @@ -46,7 +46,7 @@ dependencies { compile 'com.squareup.okhttp3:okhttp:4.10.0' compile 'com.google.code.gson:gson:2.10' - annotationProcessor 'com.velocitypowered:velocity-api:3.0.0' + //annotationProcessor 'com.velocitypowered:velocity-api:3.0.0' } shadowJar { diff --git a/server_top/.gitattributes b/server_top/.gitattributes new file mode 100644 index 00000000..dfe07704 --- /dev/null +++ b/server_top/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/server_top/.gitignore b/server_top/.gitignore new file mode 100644 index 00000000..5dc2c82c --- /dev/null +++ b/server_top/.gitignore @@ -0,0 +1,27 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run + +# Files from Forge MDK +forge*changelog.txt + +lib diff --git a/server_top/build.gradle b/server_top/build.gradle new file mode 100644 index 00000000..5263abbe --- /dev/null +++ b/server_top/build.gradle @@ -0,0 +1,63 @@ +plugins { + id 'java' + id 'maven-publish' + id 'com.github.johnrengelman.shadow' version '6.1.0' +} +version = "2.18.10" + +repositories { + mavenCentral() + + maven { + name 'Spigot' + url 'https://hub.spigotmc.org/nexus/content/groups/public' + } + maven { + url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/' + } + maven { + url 'https://jitpack.io' + } + maven { + url ' https://mvnrepository.com/artifact/mysql/mysql-connector-java' + } + maven { + url 'https://maven.citizensnpcs.co/repo' + } + maven { + name 'velocity' + url 'https://nexus.velocitypowered.com/repository/maven-public/' + } +} + +dependencies { + //implementation "org.apache.commons:commons-dbcp2:2.9.0" + //implementation 'mysql:mysql-connector-java:8.0.31' + + //compileOnly 'org.spigotmc:spigot-api:1.19.2-R0.1-SNAPSHOT' + compileOnly 'net.md-5:bungeecord-api:1.19-R0.1-SNAPSHOT' + compileOnly "com.github.MilkBowl:VaultAPI:1.7.1" + compileOnly 'com.velocitypowered:velocity-api:3.0.0' + compileOnly 'me.clip:placeholderapi:2.10.10' + //compileOnly 'net.citizensnpcs:citizens-main:2.0.30-SNAPSHOT' +// compileOnly fileTree(dir:'lib',include:['*.jar']) + + implementation 'org.xerial:sqlite-jdbc:3.39.3.0' + compile 'com.squareup.okhttp3:okhttp:4.10.0' + compile 'com.google.code.gson:gson:2.10' + + annotationProcessor 'com.velocitypowered:velocity-api:3.0.0' +} + +shadowJar { + relocate 'okhttp3', 'coloryr.allmusic.lib.okhttp3' + relocate 'okio', 'coloryr.allmusic.lib.okio' + relocate 'kotlin', 'coloryr.allmusic.lib.kotlin' + relocate 'org.intellij', 'coloryr.allmusic.lib.org.intellij' + relocate 'org.jetbrains', 'coloryr.allmusic.lib.org.jetbrains' + relocate 'com.google.gson', 'coloryr.allmusic.lib.com.google.gson' +} + +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} \ No newline at end of file diff --git a/server_top/gradle/wrapper/gradle-wrapper.jar b/server_top/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..87b738cb Binary files /dev/null and b/server_top/gradle/wrapper/gradle-wrapper.jar differ diff --git a/server_top/gradle/wrapper/gradle-wrapper.properties b/server_top/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..da9702f9 --- /dev/null +++ b/server_top/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/server_top/gradlew b/server_top/gradlew new file mode 100644 index 00000000..4453ccea --- /dev/null +++ b/server_top/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/server_top/gradlew.bat b/server_top/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/server_top/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/server_top/settings.gradle b/server_top/settings.gradle new file mode 100644 index 00000000..f69c58ff --- /dev/null +++ b/server_top/settings.gradle @@ -0,0 +1,18 @@ +/* + * This settings file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/3.5/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'AllMusic_Server_Top' diff --git a/server/src/main/java/coloryr/allmusic/AllMusicBC.java b/server_top/src/main/java/coloryr/allmusic/AllMusicBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/AllMusicBC.java rename to server_top/src/main/java/coloryr/allmusic/AllMusicBC.java diff --git a/server/src/main/java/coloryr/allmusic/AllMusicVelocity.java b/server_top/src/main/java/coloryr/allmusic/AllMusicVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/AllMusicVelocity.java rename to server_top/src/main/java/coloryr/allmusic/AllMusicVelocity.java diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/MetricsBase.java b/server_top/src/main/java/coloryr/allmusic/bstats/MetricsBase.java new file mode 100644 index 00000000..df382d86 --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/MetricsBase.java @@ -0,0 +1,238 @@ +package coloryr.allmusic.bstats; + +import coloryr.allmusic.bstats.charts.CustomChart; +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.zip.GZIPOutputStream; + +public class MetricsBase { + + /** + * The version of the Metrics class. + */ + public static final String METRICS_VERSION = "3.0.1-SNAPSHOT"; + + private static final ScheduledExecutorService scheduler = + Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + 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 + ) { + 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(); + } + } + + /** + * 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 void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + 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!"); + } + } + } + +} diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedBarChart.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedBarChart.java new file mode 100644 index 00000000..376dcbbf --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedBarChart.java @@ -0,0 +1,48 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.Map; +import java.util.concurrent.Callable; + +public 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) { + continue; // Skip this invalid + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + + return new JsonObjectBuilder() + .appendField("values", valuesBuilder.build()) + .build(); + } +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedPie.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedPie.java new file mode 100644 index 00000000..90e33c55 --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/AdvancedPie.java @@ -0,0 +1,49 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.Map; +import java.util.concurrent.Callable; + +public 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) { + continue; // Skip this invalid + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + + return new JsonObjectBuilder() + .appendField("values", valuesBuilder.build()) + .build(); + } +} diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/CustomChart.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/CustomChart.java new file mode 100644 index 00000000..b73d8cee --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/CustomChart.java @@ -0,0 +1,40 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.function.BiConsumer; + +public abstract 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; + +} diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/DrilldownPie.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/DrilldownPie.java new file mode 100644 index 00000000..7d2d87e2 --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/DrilldownPie.java @@ -0,0 +1,54 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.Map; +import java.util.concurrent.Callable; + +public 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(); + } +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/MultiLineChart.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/MultiLineChart.java new file mode 100644 index 00000000..63d0f74d --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/MultiLineChart.java @@ -0,0 +1,50 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.Map; +import java.util.concurrent.Callable; + +public 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) { + continue; // Skip this invalid + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + + return new JsonObjectBuilder() + .appendField("values", valuesBuilder.build()) + .build(); + } + +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimpleBarChart.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimpleBarChart.java new file mode 100644 index 00000000..934de4df --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimpleBarChart.java @@ -0,0 +1,41 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.Map; +import java.util.concurrent.Callable; + +public 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(); + } + +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimplePie.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimplePie.java new file mode 100644 index 00000000..b7db8a8b --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SimplePie.java @@ -0,0 +1,33 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.concurrent.Callable; + +public 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(); + } +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/charts/SingleLineChart.java b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SingleLineChart.java new file mode 100644 index 00000000..6c23c33d --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/charts/SingleLineChart.java @@ -0,0 +1,34 @@ +package coloryr.allmusic.bstats.charts; + +import coloryr.allmusic.bstats.json.JsonObjectBuilder; + +import java.util.concurrent.Callable; + +public 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(); + } + +} \ No newline at end of file diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/config/MetricsConfig.java b/server_top/src/main/java/coloryr/allmusic/bstats/config/MetricsConfig.java new file mode 100644 index 00000000..a0b08fd1 --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/config/MetricsConfig.java @@ -0,0 +1,162 @@ +package coloryr.allmusic.bstats.config; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class MetricsConfig { + private final File file; + private final boolean defaultEnabled; + + private String serverUUID; + private boolean enabled; + private boolean logErrors; + private boolean logSentData; + private boolean logResponseStatusText; + + private boolean didExistBefore = true; + + public MetricsConfig(File file, boolean defaultEnabled) throws IOException { + this.file = file; + this.defaultEnabled = defaultEnabled; + + setupConfig(); + } + + public String getServerUUID() { + return serverUUID; + } + + public boolean isEnabled() { + return enabled; + } + + public boolean isLogErrorsEnabled() { + return logErrors; + } + + public boolean isLogSentDataEnabled() { + return logSentData; + } + + public boolean isLogResponseStatusTextEnabled() { + return logResponseStatusText; + } + + /** + * Checks whether the config file did exist before or not. + * + * @return If the config did exist before. + */ + public boolean didExistBefore() { + return didExistBefore; + } + + /** + * Creates the config file if it does not exist and read its content. + */ + private void setupConfig() throws IOException { + if (!file.exists()) { + didExistBefore = false; // Looks like it's the first time we create it (or someone deleted it). + writeConfig(); + } + readConfig(); + if (serverUUID == null) { + // Found a malformed config file with no UUID. Let's recreate it. + writeConfig(); + readConfig(); + } + } + + /** + * Creates a config file with teh default content. + */ + private void writeConfig() throws IOException { + List configContent = new ArrayList<>(); + configContent.add("# bStats (https://bStats.org) collects some basic information for plugin authors, like"); + configContent.add("# how many people use their plugin and their total player count. It's recommended to keep"); + configContent.add("# bStats enabled, but if you're not comfortable with this, you can turn this setting off."); + configContent.add("# There is no performance penalty associated with having metrics enabled, and data sent to"); + configContent.add("# bStats is fully anonymous."); + configContent.add("enabled=" + defaultEnabled); + configContent.add("server-uuid=" + UUID.randomUUID()); + configContent.add("log-errors=false"); + configContent.add("log-sent-data=false"); + configContent.add("log-response-status-text=false"); + writeFile(file, configContent); + } + + /** + * Reads the content of the config file. + */ + private void readConfig() throws IOException { + List lines = readFile(file); + if (lines == null) { + throw new AssertionError("Content of newly created file is null"); + } + + enabled = getConfigValue("enabled", lines).map("true"::equals).orElse(true); + serverUUID = getConfigValue("server-uuid", lines).orElse(null); + logErrors = getConfigValue("log-errors", lines).map("true"::equals).orElse(false); + logSentData = getConfigValue("log-sent-data", lines).map("true"::equals).orElse(false); + logResponseStatusText = getConfigValue("log-response-status-text", lines).map("true"::equals).orElse(false); + } + + /** + * Gets a config setting from the given list of lines of the file. + * + * @param key The key for the setting. + * @param lines The lines of the file. + * @return The value of the setting. + */ + private Optional getConfigValue(String key, List lines) { + return lines.stream() + .filter(line -> line.startsWith(key + "=")) + .map(line -> line.replaceFirst(Pattern.quote(key + "="), "")) + .findFirst(); + } + + /** + * Reads the text content of the given file. + * + * @param file The file to read. + * @return The lines of the given file. + */ + private List readFile(File file) throws IOException { + if (!file.exists()) { + return null; + } + try ( + FileReader fileReader = new FileReader(file); + BufferedReader bufferedReader = new BufferedReader(fileReader) + ) { + return bufferedReader.lines().collect(Collectors.toList()); + } + } + + /** + * Writes the given lines to the given file. + * + * @param file The file to write to. + * @param lines The lines to write. + */ + private void writeFile(File file, List lines) throws IOException { + if (!file.exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + try ( + FileWriter fileWriter = new FileWriter(file); + BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) + ) { + for (String line : lines) { + bufferedWriter.write(line); + bufferedWriter.newLine(); + } + } + } +} diff --git a/server_top/src/main/java/coloryr/allmusic/bstats/json/JsonObjectBuilder.java b/server_top/src/main/java/coloryr/allmusic/bstats/json/JsonObjectBuilder.java new file mode 100644 index 00000000..aa6b16d1 --- /dev/null +++ b/server_top/src/main/java/coloryr/allmusic/bstats/json/JsonObjectBuilder.java @@ -0,0 +1,211 @@ +package coloryr.allmusic.bstats.json; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** + * 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 class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * 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(); + } + + /** + * 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; + } + + /** + * 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; + } + } + +} \ No newline at end of file diff --git a/server/src/main/java/coloryr/allmusic/side/bc/CommandBC.java b/server_top/src/main/java/coloryr/allmusic/side/bc/CommandBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/CommandBC.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/CommandBC.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/ListenerBC.java b/server_top/src/main/java/coloryr/allmusic/side/bc/ListenerBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/ListenerBC.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/ListenerBC.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/LogBC.java b/server_top/src/main/java/coloryr/allmusic/side/bc/LogBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/LogBC.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/LogBC.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/MetricsBC.java b/server_top/src/main/java/coloryr/allmusic/side/bc/MetricsBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/MetricsBC.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/MetricsBC.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/SideBC.java b/server_top/src/main/java/coloryr/allmusic/side/bc/SideBC.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/SideBC.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/SideBC.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/event/MusicAddEvent.java b/server_top/src/main/java/coloryr/allmusic/side/bc/event/MusicAddEvent.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/event/MusicAddEvent.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/event/MusicAddEvent.java diff --git a/server/src/main/java/coloryr/allmusic/side/bc/event/MusicPlayEvent.java b/server_top/src/main/java/coloryr/allmusic/side/bc/event/MusicPlayEvent.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/bc/event/MusicPlayEvent.java rename to server_top/src/main/java/coloryr/allmusic/side/bc/event/MusicPlayEvent.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/CommandVelocity.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/CommandVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/CommandVelocity.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/CommandVelocity.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/ListenerVelocity.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/ListenerVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/ListenerVelocity.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/ListenerVelocity.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/LogVelocity.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/LogVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/LogVelocity.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/LogVelocity.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/MetricsVelocity.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/MetricsVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/MetricsVelocity.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/MetricsVelocity.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/SideVelocity.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/SideVelocity.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/SideVelocity.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/SideVelocity.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/event/MusicAddEvent.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/event/MusicAddEvent.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/event/MusicAddEvent.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/event/MusicAddEvent.java diff --git a/server/src/main/java/coloryr/allmusic/side/velocity/event/MusicPlayEvent.java b/server_top/src/main/java/coloryr/allmusic/side/velocity/event/MusicPlayEvent.java similarity index 100% rename from server/src/main/java/coloryr/allmusic/side/velocity/event/MusicPlayEvent.java rename to server_top/src/main/java/coloryr/allmusic/side/velocity/event/MusicPlayEvent.java diff --git a/server/src/main/resources/bungee.yml b/server_top/src/main/resources/bungee.yml similarity index 100% rename from server/src/main/resources/bungee.yml rename to server_top/src/main/resources/bungee.yml diff --git a/server_top/src/main/resources/config.json b/server_top/src/main/resources/config.json new file mode 100644 index 00000000..ec568863 --- /dev/null +++ b/server_top/src/main/resources/config.json @@ -0,0 +1,62 @@ +{ + "MaxList": 10, + "MinVote": 3, + "Delay": 0, + "KDelay": 0, + "Admin": ["CONSOLE","Color_yr"], + "LoginUser": "", + "NoMusicServer": [], + "NoMusicPlayer": [], + "BanMusic": [], + "PlayList": [], + "PlayListSwitch": true, + "PlayListRandom": true, + "SendLyric": true, + "NeedPermission": false, + "DefaultAddMusic": 0, + "TopPAPI": false, + "MessageLimit": false, + "MessageLimitSize": 40, + "MutePlayMessage": false, + "MuteAddMessage": false, + "ShowInBar": false, + "DefaultHud": { + "List": { + "x": 2, + "y": 74 + }, + "Lyric": { + "x": 74, + "y": 53 + }, + "Info": { + "x": 74, + "y": 2 + }, + "Pic": { + "x": 2, + "y": 2 + }, + "PicRotateSpeed": 10, + "EnablePicRotate": true, + "EnableList": true, + "EnableLyric": true, + "EnableInfo": true, + "EnablePic": true + }, + "Economys": { + "MysqlUrl": "jdbc:mysql://localhost:3306/minecraft?autoReconnect=true&autoReconnectForPools=true", + "Vault": true + }, + "UseCost": false, + "SearchCost": 20, + "AddMusicCost": 10, + "MaxMusicTime": 600, + "KtvMode": true, + "MusicBR": "320000", + "FunConfig": { + "Rain": true, + "RainRate": 10 + }, + "Version": "103" +} \ No newline at end of file diff --git a/server_top/src/main/resources/message.json b/server_top/src/main/resources/message.json new file mode 100644 index 00000000..dc41e64d --- /dev/null +++ b/server_top/src/main/resources/message.json @@ -0,0 +1,139 @@ +{ + "MusicPlay": { + "StopPlay": "§d[AllMusic]§e已停止你的音乐播放", + "NoMusic": "§d[AllMusic]§e无正在播放的歌曲", + "Play": "§d[AllMusic]§e正在播放:%MusicName% | %MusicAuthor% | %MusicAl% | %MusicAlia% | by: %PlayerName%", + "NoPlay": "§d[AllMusic]§e队列中无歌曲", + "ListMusic": { + "Head": "§d[AllMusic]§e队列中有歌曲数:&Count&", + "Item": "§e%index%->%MusicName% | %MusicAuthor% | %MusicAl% | %MusicAlia%", + "Get": "§d[AllMusic]§e歌曲列表%ListName%获取成功" + }, + "NoCanPlay": "§d[AllMusic]§c无法播放歌曲%MusicID%可能该歌曲为VIP歌曲", + "NoPlayMusic": "§d[AllMusic]§e你不会再收到点歌了!想要再次参与点歌就点一首歌或者参与切歌投票吧!", + "Switch": "§d[AllMusic]§e切换到玩家歌曲", + "AddMusic": "§d[AllMusic]§e音乐列表添加%MusicName% | %MusicAuthor% | %MusicAl% | %MusicAlia%", + "CheckMusic": "§d[AllMusic]§2正在解析歌曲%MusicID%", + "MusicInfo": "%MusicName% | %MusicAuthor% | %MusicAl% | %MusicAlia% | by: %PlayerName%", + "Trail": "§d[AllMusic]§e该音乐为试听音乐", + "Cancel": "§d[AllMusic]§e播放被取消" + }, + "AddMusic": { + "ListFull": "§d[AllMusic]§c错误,队列已满", + "BanMusic": "§d[AllMusic]§c错误,这首歌被禁点了", + "ExistMusic": "§d[AllMusic]§c错误,这首歌已经存在了", + "Success": "§d[AllMusic]§e点歌成功", + "NoPlayer": "§d[AllMusic]§c没有播放的玩家", + "NoID": "§d[AllMusic]§c错误,请输入歌曲数字ID", + "Cancel": "§d[AllMusic]§e点歌被取消", + "TimeOut": "§d[AllMusic]§e点歌被取消,音乐长度过长" + }, + "Page": { + "Choice": "§e%index%->%MusicName% | %MusicAuthor% | %MusicAl%", + "Next": "§e[§n点我下一页§r§e]", + "Last": "§e[§n点我上一页§r§e]" + }, + "Lyric": { + "Data": "%Lyric%", + "TData": "%Lyric%(%TLyric%)", + "Empty1": "没有歌词", + "Empty2": "没有翻译歌词", + "Empty3": "没有KTV歌词" + }, + "Vote": { + "NoPermission": "§d[AllMusic]§c你没有权限切歌", + "DoVote": "§d[AllMusic]§e已发起切歌投票", + "BQ": "§d[AllMusic]§e%PlayerName%发起了切歌投票,30秒后结束,输入/music vote 同意切歌。", + "Agree": "§d[AllMusic]§e你同意切歌", + "BQAgree": "§d[AllMusic]§e%PlayerName%同意切歌,共有%Count%名玩家同意切歌。", + "ARAgree": "§d[AllMusic]§e你已申请切歌", + "TimeOut": "§d[AllMusic]§e切歌时间结束", + "Do": "§d[AllMusic]§e已切歌" + }, + "Search": { + "StartSearch": "§d[AllMusic]§e正在排队搜歌", + "NoPer": "§d[AllMusic]§c你没有权限搜歌", + "CantSearch": "§d[AllMusic]§c无法搜索歌曲:%Music%", + "Res": "§d[AllMusic]§e搜索结果", + "NoSearch": "§d[AllMusic]§c你没有搜索音乐", + "ErrorNum": "§d[AllMusic]§c请输入正确的序号", + "Chose": "§d[AllMusic]§e你选择了序号%Num%", + "CantNext": "§d[AllMusic]§c无法下一页", + "CantLast": "§d[AllMusic]§c无法上一页" + }, + "Hud": { + "State": "§d[AllMusic]§e设置信息位置:%Hud%,状态:%State%", + "Set": "§d[AllMusic]§e已设置%Hud%的坐标为%x%, %y%", + "Reset": "§d[AllMusic]§eHud恢复至默认位置", + "NoMusic": "没有播放的音乐", + "NoList": "队列中无歌曲", + "NoLyric": "无歌词", + "PicSize": "§d[ALLMusic]§e设置图片尺寸为%Size%", + "PicRotate": "§d[AllMusic]§2设置图片旋转为%State%", + "PicRotateSpeed": "§d[AllMusic]§2设置图片旋转速度为%Size%", + "Music": "%Name% %AllTime%/%NowTime%\n%Author%\n%Alia%\n%Al%\nby: %Player%", + "Lyric": "%Lyric%\n%Tlyric%", + "Ktv": "§e%KLyric%§f%Lyric%§r\n%Tlyric%", + "List": "播放列表里面有%Size%首歌\n%List%" + }, + "Command": { + "Error": "§d[AllMusic]§c参数错误,请输入/music help获取帮助", + "NoPer": "§d[AllMusic]§c你没有权限点歌" + }, + "HudList": { + "List": "待播放列表", + "Lyric": "歌词", + "Info": "歌曲信息", + "Pic": "图片", + "All": "所有位置", + "PicRoute": "图片旋转", + "PicRouteSpeed": "图片旋转速度" + }, + "Custom": { + "Info": "自定义音乐" + }, + "PAPI": { + "NoMusic": "没有播放的音乐" + }, + "Cost": { + "Search": "§d[AllMusic]§e你搜歌花费了%Cost%", + "AddMusic": "§d[AllMusic]§e你点歌花费了%Cost%", + "NoMoney": "§d[AllMusic]§c你没有足够的钱", + "CostFail": "§d[ALLMusic]§c扣钱过程中错误" + }, + "Click": { + "This": "§b[§n点我选择§r§b]", + "Check": "§b[§n点我查看§r§b]" + }, + "Help": { + "Normal": { + "Head": "§d[AllMusic]§e帮助手册", + "Base": "§d[AllMusic]§e使用/music [音乐ID] 来点歌", + "Stop": "§d[AllMusic]§e使用/music stop 停止播放歌曲", + "List": "§d[AllMusic]§e使用/music list 查看歌曲队列", + "Vote": "§d[AllMusic]§e使用/music vote 投票切歌", + "NoMusic": "§d[AllMusic]§e使用/music nomusic 不再参与点歌", + "Search": "§d[AllMusic]§e使用/music search [歌名] 搜索歌曲", + "Select": "§d[AllMusic]§e使用/music select [序列] 选择歌曲", + "Hud1": "§d[AllMusic]§e使用/music hud enable [位置] 启用关闭Hud", + "Hud2": "§d[AllMusic]§e使用/music hud [位置] [x] [y] 设置某个Hud的位置", + "Hud3": "§d[AllMusic]§e使用/music hud picsize [尺寸] 设置图片尺寸", + "Hud4": "§d[AllMusic]§e使用/music hud picrotate [开关] 设置图片旋转模式", + "Hud5": "§d[AllMusic]§e使用/music hud picrotatespeed [数值] 设置图片旋转速度" + }, + "Admin": { + "Reload": "§d[AllMusic]§e使用/music reload 重读配置文件", + "Next": "§d[AllMusic]§e使用/music next 强制切歌", + "Ban": "§d[AllMusic]§e使用/music ban [ID] 禁止点这首歌", + "Url": "§d[AllMusic]§e使用/music url [url] 播放一首自定义歌曲", + "Delete": "§d[AllMusic]§e使用/music delete [序号] 删除队列中的歌曲", + "AddList": "§d[AllMusic]§e使用/music addlist [歌单ID] 添加歌单到空闲列表", + "ClearList": "§d[AllMusic]§e使用/music clearlist 清空空闲歌单", + "Login": "§d[AllMusic]§e使用/music login 重新登录账户" + } + }, + "Fun": { + "Rain": "§d[AllMusic]§e天空开始变得湿润" + }, + "Version": "104" +} \ No newline at end of file diff --git a/server_top/src/test/java/RunTest.java b/server_top/src/test/java/RunTest.java new file mode 100644 index 00000000..69920753 --- /dev/null +++ b/server_top/src/test/java/RunTest.java @@ -0,0 +1,41 @@ +import coloryr.allmusic.core.AllMusic; +import coloryr.allmusic.core.objs.CookieObj; +import coloryr.allmusic.core.objs.music.LyricItemObj; +import coloryr.allmusic.core.music.play.LyricSave; +import coloryr.allmusic.core.side.IMyLogger; + +public class RunTest implements IMyLogger { + public static void main(String[] arg) { + AllMusic.cookie = new CookieObj(); + AllMusic.log = new RunTest(); +// LyricSaveObj obj = AllMusic.getMusicApi().getLyric("2003496380"); +// if(obj.isHaveLyric()) +// { +// +// } + //https://music.163.com/song?id=1422767271&userid=124183854 + LyricSave obj = AllMusic.getMusicApi().getLyric("1449794087"); + if (obj.isHaveLyric()) { + int time = 0; + while (true) { + boolean res = obj.checkTime(time, true); + if (res) { + String temp = obj.getKly(); + if (temp != null) + System.out.println(temp); + } + time += 10; + } + } + } + + @Override + public void warning(String data) { + + } + + @Override + public void info(String data) { + + } +}