Added Bukkit project for Minecraft Beta 1.7.3 and split out the source tree for code sharing.

This commit is contained in:
flash 2024-02-23 00:27:29 +01:00
parent db8be56f18
commit c0caca3349
30 changed files with 601 additions and 45 deletions

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
* text=auto

3
.gitignore vendored
View file

@ -38,3 +38,6 @@ hs_err_*.log
replay_*.log replay_*.log
*.hprof *.hprof
*.jfr *.jfr
# bukkit
craftbukkit-0.0.1-SNAPSHOT.jar

38
bukkit173/build.gradle Normal file
View file

@ -0,0 +1,38 @@
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
implementation files('craftbukkit-0.0.1-SNAPSHOT.jar')
}
tasks.withType(JavaCompile).configureEach {
it.options.encoding = "UTF-8"
it.options.release = 8
it.options.compilerArgs += ['-Xlint:deprecation', '-Xlint:unchecked']
}
java {
withSourcesJar()
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
sourceSets {
main {
java {
srcDirs = [
'../src/shared',
'../src/rpc-simple',
'../src/bukkitb173',
]
resources {
srcDirs = ['../src']
include 'plugin.yml'
}
}
}
}

View file

@ -0,0 +1,3 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
bukkit173/gradlew vendored Normal file
View file

@ -0,0 +1,248 @@
#!/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
# 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
if ! command -v java >/dev/null 2>&1
then
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
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
# 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"'
# 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" "$@"

92
bukkit173/gradlew.bat vendored Normal file
View file

@ -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

View file

@ -49,7 +49,11 @@ jar {
sourceSets { sourceSets {
main { main {
java { java {
srcDirs = ['../src/fabric'] srcDirs = [
'../src/shared',
'../src/rpc-gson',
'../src/fabric',
]
resources { resources {
srcDirs = ['../src'] srcDirs = ['../src']
include 'fabric.mod.json' include 'fabric.mod.json'

View file

@ -9,6 +9,6 @@ yarn_mappings=1.20.1+build.10
loader_version=0.14.22 loader_version=0.14.22
# Mod Properties # Mod Properties
mod_version=1.0.1 mod_version=1.1.0
maven_group=net.flashii.mcexts maven_group=net.flashii.mcexts
archives_base_name=flashii-extensions archives_base_name=flashii-extensions

View file

@ -0,0 +1,20 @@
package net.flashii.mcexts;
import java.io.File;
import java.nio.file.Path;
public class ConfigPath {
private static Path configPath = null;
public static Path getPath() {
return configPath;
}
public static Path getPath(String name) {
return configPath.resolve(name);
}
public static void setPath(File path) {
configPath = path.toPath().toAbsolutePath();
}
}

View file

@ -0,0 +1,48 @@
package net.flashii.mcexts;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
public class JoinListener extends PlayerListener {
@Override
public void onPlayerLogin(PlayerLoginEvent ev) {
if(ev.getResult() != Result.ALLOWED)
return;
String authText = null;
try {
RPCPayload payload = RPC.postAuth(ev.getPlayer().getDisplayName(), ev.getKickMessage());
if(!payload.is("auth:ok")) {
if(payload.is("error")) {
authText = payload.getAttrStr(payload.hasAttr("text") ? "text" : "code");
} else if(payload.is("auth:authorise")) {
String userName = payload.getAttrStr("user_name");
String url = payload.getAttrStr("url");
if(userName.length() > 20)
userName = userName.substring(0, 20);
authText = "Welcome back, " + userName + "! Go to " + url + " to verify yourself.";
} else if(payload.is("auth:link")) {
String code = payload.getAttrStr("code");
String url = payload.getAttrStr("url");
authText = "Visit " + url + " to connect your Flashii ID. Link code: " + code;
} else {
authText = "Flashii server returned unknown response, yell at flashwave about this.";
}
}
} catch(Exception ex) {
authText = "There was a serious problem during authentication, yell at flashwave about this.";
ex.printStackTrace();
}
if(authText == null)
ev.allow();
else
ev.disallow(Result.KICK_OTHER, authText);
}
}

View file

@ -0,0 +1,26 @@
package net.flashii.mcexts;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.java.JavaPlugin;
public class PluginMain extends JavaPlugin {
public final static Logger logger = Logger.getLogger("FIIEXTS");
private final JoinListener joinListener = new JoinListener();
@Override
public void onEnable() {
logger.info("Flashii extensions enabled!");
ConfigPath.setPath(getDataFolder());
Bukkit.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_LOGIN, joinListener, Priority.Highest, this);
}
@Override
public void onDisable() {
logger.info("Flashii extensions disabled!");
}
}

View file

@ -0,0 +1,18 @@
package net.flashii.mcexts;
import java.nio.file.Path;
import net.fabricmc.loader.api.FabricLoader;
public class ConfigPath {
private static Path configPath = null;
public static Path getPath() {
if(configPath == null)
configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts");
return configPath;
}
public static Path getPath(String name) {
return getPath().resolve(name);
}
}

View file

@ -1,8 +1,6 @@
package net.flashii.mcexts.mixin; package net.flashii.mcexts.mixin;
import java.io.IOException;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.security.GeneralSecurityException;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.flashii.mcexts.RPC; import net.flashii.mcexts.RPC;
import net.flashii.mcexts.RPCPayload; import net.flashii.mcexts.RPCPayload;
@ -54,11 +52,8 @@ public abstract class PlayerManagerMixin {
authText = Text.literal("Flashii authentication server returned an unknown response, yell at flashwave about this.").formatted(Formatting.RED); authText = Text.literal("Flashii authentication server returned an unknown response, yell at flashwave about this.").formatted(Formatting.RED);
} }
} }
} catch(IOException ex) { } catch(Exception ex) {
authText = Text.literal("Flashii authentication server failed to respond, yell at flashwave about this.").formatted(Formatting.RED); authText = Text.literal("There was a serious problem during authentication, yell at flashwave about this.").formatted(Formatting.RED);
ex.printStackTrace();
} catch(GeneralSecurityException ex) {
authText = Text.literal("Problem with request verification, yell at flashwave about this.").formatted(Formatting.RED);
ex.printStackTrace(); ex.printStackTrace();
} }

3
src/plugin.yml Normal file
View file

@ -0,0 +1,3 @@
name: fiiexts
main: net.flashii.mcexts.PluginMain
version: 1.1.0

View file

@ -0,0 +1,18 @@
package net.flashii.mcexts;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class RPCPayloadParser {
private final Gson gson;
public RPCPayloadParser() {
gson = new GsonBuilder()
.registerTypeAdapter(RPCPayload.class, new RPCPayloadDeserialiser())
.create();
}
public RPCPayload parse(String body) {
return gson.fromJson(body, RPCPayload.class);
}
}

View file

@ -0,0 +1,31 @@
package net.flashii.mcexts;
import java.util.HashMap;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
public class RPCPayloadParser {
private final JSONParser parser = new JSONParser();
public RPCPayload parse(String body)
throws ParseException {
JSONObject root = (JSONObject)parser.parse(body);
String name = (String)root.get("name");
HashMap<String, Object> attrs = new HashMap<>();
@SuppressWarnings("unchecked")
Iterator<JSONObject> attrsIterator = ((JSONArray)root.get("attrs")).iterator();
while(attrsIterator.hasNext()) {
JSONObject attrInfo = attrsIterator.next();
attrs.put(
(String)attrInfo.get("name"),
attrInfo.get("value")
);
}
return new RPCPayload(name, attrs);
}
}

View file

@ -3,9 +3,7 @@ package net.flashii.mcexts;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap; import java.util.HashMap;
import net.fabricmc.loader.api.FabricLoader;
public class Config { public class Config {
static class ConfigCache { static class ConfigCache {
@ -24,25 +22,14 @@ public class Config {
} }
} }
private static Path configPath = null;
private static HashMap<String, ConfigCache> cache = new HashMap<>(); private static HashMap<String, ConfigCache> cache = new HashMap<>();
private static Path getConfigPath() {
if(configPath == null)
configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts");
return configPath;
}
private static Path getConfigPath(String name) {
return getConfigPath().resolve(name);
}
public static String getValue(String name) { public static String getValue(String name) {
return getValue(name, null); return getValue(name, null);
} }
public static String getValue(String name, String fallback) { public static String getValue(String name, String fallback) {
return getFileContentsCached(getConfigPath(name), fallback); return getFileContentsCached(ConfigPath.getPath(name), fallback);
} }
private static String getFileContentsCached(Path path, String fallback) { private static String getFileContentsCached(Path path, String fallback) {
@ -57,7 +44,7 @@ public class Config {
if(output == null) { if(output == null) {
try { try {
output = Files.exists(path) ? Files.readString(path).trim() : fallback; output = Files.exists(path) ? new String(Files.readAllBytes(path)).trim() : fallback;
} catch(IOException ex) { } catch(IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
output = fallback; output = fallback;

View file

@ -2,8 +2,8 @@ package net.flashii.mcexts;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -11,25 +11,20 @@ import java.net.SocketAddress;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64; import java.util.Base64;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class RPC { public class RPC {
private static final String DEFAULT_SECRET = "meow"; private static final String DEFAULT_SECRET = "meow";
private static Gson gson = null; private static RPCPayloadParser parser = null;
public static Gson getGson() { public static RPCPayloadParser getParser() {
if(gson == null) if(parser == null)
gson = new GsonBuilder() parser = new RPCPayloadParser();
.registerTypeAdapter(RPCPayload.class, new RPCPayloadDeserialiser()) return parser;
.create();
return gson;
} }
public static String getSecretKey() { public static String getSecretKey() {
@ -46,7 +41,9 @@ public class RPC {
params.forEach((key, value) -> { params.forEach((key, value) -> {
sb.append(key); sb.append(key);
sb.append('='); sb.append('=');
sb.append(URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)); try {
sb.append(URLEncoder.encode(value.toString(), "UTF-8"));
} catch(UnsupportedEncodingException ex) {}
sb.append('&'); sb.append('&');
}); });
@ -59,7 +56,7 @@ public class RPC {
} }
public static String createRequestSignature(String time, String path, String params) public static String createRequestSignature(String time, String path, String params)
throws GeneralSecurityException { throws Exception {
return Base64.getEncoder().encodeToString(HMAC.calculate( return Base64.getEncoder().encodeToString(HMAC.calculate(
HMAC.SHA256, getSecretKey(), String.format("%s#%s?%s", time, path, params) HMAC.SHA256, getSecretKey(), String.format("%s#%s?%s", time, path, params)
)); ));
@ -67,7 +64,7 @@ public class RPC {
// sigStr and bodyStr because sigStr must also include the query params if those are present // sigStr and bodyStr because sigStr must also include the query params if those are present
public static RPCPayload callRpc(String path, String sigStr, String bodyStr) public static RPCPayload callRpc(String path, String sigStr, String bodyStr)
throws GeneralSecurityException, IOException { throws Exception {
boolean hasBody = bodyStr != null; boolean hasBody = bodyStr != null;
String time = getRequestTimestamp(); String time = getRequestTimestamp();
String hash = createRequestSignature(time, URLs.getRpcPath(path), sigStr); String hash = createRequestSignature(time, URLs.getRpcPath(path), sigStr);
@ -94,31 +91,48 @@ public class RPC {
sb.append(line); sb.append(line);
} }
return getGson().fromJson(sb.toString(), RPCPayload.class); return getParser().parse(sb.toString());
} }
public static RPCPayload callRpc(String path, String paramStr) public static RPCPayload callRpc(String path, String paramStr)
throws GeneralSecurityException, IOException { throws Exception {
return callRpc(path, paramStr, paramStr); return callRpc(path, paramStr, paramStr);
} }
public static RPCPayload callRpc(String path, Map<String, Object> params) public static RPCPayload callRpc(String path, Map<String, Object> params)
throws GeneralSecurityException, IOException { throws Exception {
return callRpc(path, createParamString(params)); return callRpc(path, createParamString(params));
} }
public static RPCPayload postAuth(UUID id, String name, InetAddress remoteAddr) public static UUID createOfflinePlayerUUID(String name) {
throws GeneralSecurityException, IOException { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes());
}
public static RPCPayload postAuth(String name, String remoteAddr)
throws Exception {
return postAuth(
createOfflinePlayerUUID(name),
name, remoteAddr
);
}
public static RPCPayload postAuth(UUID id, String name, String remoteAddr)
throws Exception {
HashMap<String, Object> params = new HashMap<>(); HashMap<String, Object> params = new HashMap<>();
params.put("id", id); params.put("id", id);
params.put("name", name); params.put("name", name);
params.put("ip", remoteAddr.getHostAddress()); params.put("ip", remoteAddr);
return callRpc("/auth", params); return callRpc("/auth", params);
} }
public static RPCPayload postAuth(UUID id, String name, InetAddress remoteAddr)
throws Exception {
return postAuth(id, name, remoteAddr.getHostAddress());
}
public static RPCPayload postAuth(UUID id, String name, SocketAddress sockAddr) public static RPCPayload postAuth(UUID id, String name, SocketAddress sockAddr)
throws GeneralSecurityException, IOException { throws Exception {
InetAddress remoteAddr = sockAddr instanceof InetSocketAddress InetAddress remoteAddr = sockAddr instanceof InetSocketAddress
? ((InetSocketAddress)sockAddr).getAddress() ? ((InetSocketAddress)sockAddr).getAddress()
: InetAddress.getLoopbackAddress(); : InetAddress.getLoopbackAddress();