commit debdcb40e083785077492a7f0c93e851430abae7 Author: MiniDay <372403923@qq.com> Date: Mon Mar 11 19:36:44 2024 +0800 feat: 支持仓鼠球 1.5+ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95d951f --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +.gradle +.idea +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..7552fdd --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# hamster-ball-bridge + +将原 HamsterService 无缝转换为仓鼠球的API,让旧版插件无需修改代码也能兼容[仓鼠球](https://git.airgame.net/MiniDay/hamster-ball/) + +> 注意:这个插件的同一个 `.jar` 文件既可以安装在 BC 也可以安装在 子服 + +# 手动构建 + +1. 将源代码下载或克隆至本地 +2. 在源代码根目录中打开命令行窗口 +3. 命令行窗口中执行`./gradlew clean build` +4. 构建成品在 `build` 文件夹 + +也可访问我的[Jenkins网站](https://jenkins.airgame.net/job/opensource/job/hamster-ball-bridge/)获取最新版 + +# 前置插件 + +- [HamsterBall](https://git.airgame.net/MiniDay/hamster-ball/) + +# 安装步骤 + +1. 安装步骤 +2. 关闭服务器 +3. 下载插件后将其放置在`plugins`文件夹 +4. 启动服务器 diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..7d60d94 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,52 @@ +@file:Suppress("VulnerableLibrariesLocal") + +plugins { + id("java") +} + +group = "cn.hamster3.mc.plugin" +version = "1.4.4" + +repositories { + maven { + url = uri("https://maven.airgame.net/maven-public/") + } +} + +dependencies { + // https://mvnrepository.com/artifact/org.jetbrains/annotations + compileOnly("org.jetbrains:annotations:24.1.0") + + compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT") + compileOnly("net.md-5:bungeecord-api:1.20-R0.1-SNAPSHOT") + + compileOnly("cn.hamster3.mc.plugin:core-bukkit:1.2.2") + compileOnly("cn.hamster3.mc.plugin:ball-bukkit:1.5.7") + + compileOnly("me.clip:placeholderapi:2.11.2") +} + +tasks { + withType().configureEach { + options.encoding = "UTF-8" + } + withType().configureEach { + from(rootProject.file("LICENSE")) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } + java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + withSourcesJar() + } + jar { + archiveBaseName = "HamsterBall-Bridge" + destinationDirectory = rootProject.layout.buildDirectory + } + processResources { + filesMatching("plugin.yml") { + expand(project.properties) + } + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 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..7b6c47b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Mar 11 19:25:59 CST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&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*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 \ + "$@" + +# 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..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..2084b0f --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "hamster-ball-bridge" + diff --git a/src/main/java/cn/hamster3/service/bukkit/BallBridgePlugin.java b/src/main/java/cn/hamster3/service/bukkit/BallBridgePlugin.java new file mode 100644 index 0000000..54524e9 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/BallBridgePlugin.java @@ -0,0 +1,40 @@ +package cn.hamster3.service.bukkit; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.service.bukkit.command.ServiceCommand; +import cn.hamster3.service.bukkit.hook.ServicePlaceholderHook; +import cn.hamster3.service.bukkit.listener.ServiceMainListener; +import cn.hamster3.service.bukkit.listener.BridgeListener; +import cn.hamster3.service.common.util.ServiceLogUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +public class BallBridgePlugin extends JavaPlugin { + private static BallBridgePlugin instance; + + public static BallBridgePlugin getInstance() { + return instance; + } + + @Override + public void onLoad() { + instance = this; + ServiceLogUtils.setLogger(getLogger()); + } + + @Override + public void onEnable() { + ServiceCommand.INSTANCE.register(); + BallAPI.getInstance().getEventBus().register(BridgeListener.INSTANCE); + Bukkit.getPluginManager().registerEvents(ServiceMainListener.INSTANCE, this); + Bukkit.getScheduler().runTask(this, () -> { + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + ServicePlaceholderHook.INSTANCE.register(); + getLogger().info("已注册 PlaceholderAPI 占位符."); + } else { + getLogger().warning("未找到 PlaceholderAPI 插件, 取消注册占位符."); + } + }); + BallAPI.getInstance().subscribeIgnorePrefix("HamsterService"); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/api/ServiceInfoAPI.java b/src/main/java/cn/hamster3/service/bukkit/api/ServiceInfoAPI.java new file mode 100644 index 0000000..222480a --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/api/ServiceInfoAPI.java @@ -0,0 +1,141 @@ +package cn.hamster3.service.bukkit.api; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo; +import cn.hamster3.mc.plugin.ball.common.entity.BallServerInfo; +import cn.hamster3.mc.plugin.ball.common.entity.BallServerType; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceSenderInfo; +import cn.hamster3.service.common.entity.ServiceSenderType; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.UUID; +import java.util.stream.Collectors; + +@SuppressWarnings("unused") +public class ServiceInfoAPI { + /** + * 获取玩家信息,当玩家不在线时返回 null + * + * @param uuid 玩家的UUID + * @return 玩家信息 + */ + public static ServicePlayerInfo getPlayerInfo(@NotNull UUID uuid) { + return transfer(BallAPI.getInstance().getPlayerInfo(uuid)); + } + + /** + * 获取玩家信息,当玩家不在线时返回 null + * + * @param playerName 玩家ID + * @return 玩家信息 + */ + public static ServicePlayerInfo getPlayerInfo(@NotNull String playerName) { + return transfer(BallAPI.getInstance().getPlayerInfoExact(playerName)); + } + + /** + * 获取全部在线玩家的信息 + * + * @return 玩家们的信息 + */ + public static HashSet getOnlinePlayers() { + return BallAPI.getInstance().getAllPlayerInfo().values() + .stream() + .filter(BallPlayerInfo::isOnline) + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * 获取全部在线玩家的信息 + * + * @return 玩家们的信息 + */ + public static HashSet getAllPlayerInfo() { + return BallAPI.getInstance().getAllPlayerInfo().values() + .stream() + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * 获取服务端信息 + * + * @param senderName 服务端id + * @return 服务端信息 + */ + public static ServiceSenderInfo getSenderInfo(String senderName) { + return transfer(BallAPI.getInstance().getServerInfo(senderName)); + } + + /** + * 获取所有连接至服务中心的信息 + * + * @return 服务器信息 + */ + public static HashSet getAllSenderInfo() { + return BallAPI.getInstance().getAllServerInfo().values() + .stream() + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + + } + + /** + * 获取当前服务器的名称 + * + * @return 服务器id + */ + public static String getLocalServerName() { + return BallAPI.getInstance().getLocalServerId(); + } + + /** + * 获取当前服务器的别名 + * + * @return 服务器别名 + */ + public static String getLocalServerNickName() { + return BallAPI.getInstance().getLocalServerInfo().getName(); + } + + /** + * 获取当前服务器的SenderInfo对象 + * + * @return 当前服务器的发送者信息 + */ + public static ServiceSenderInfo getLocalSenderInfo() { + return new ServiceSenderInfo( + ServiceSenderType.BUKKIT, + BallAPI.getInstance().getLocalServerInfo().getId(), + BallAPI.getInstance().getLocalServerInfo().getName() + ); + } + + public static ServiceSenderInfo transfer(BallServerInfo info) { + if (info == null) { + return null; + } + return new ServiceSenderInfo( + info.getType() == BallServerType.PROXY ? ServiceSenderType.PROXY : ServiceSenderType.BUKKIT, + info.getId(), + info.getName() + ); + } + + public static ServicePlayerInfo transfer(BallPlayerInfo info) { + if (info == null) { + return null; + } + return new ServicePlayerInfo( + info.getUuid(), + info.getName(), + info.getGameServer(), + info.getProxyServer(), + info.isOnline() + ); + } + +} diff --git a/src/main/java/cn/hamster3/service/bukkit/api/ServiceMessageAPI.java b/src/main/java/cn/hamster3/service/bukkit/api/ServiceMessageAPI.java new file mode 100644 index 0000000..ef7b700 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/api/ServiceMessageAPI.java @@ -0,0 +1,356 @@ +package cn.hamster3.service.bukkit.api; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.mc.plugin.ball.common.data.BallMessage; +import cn.hamster3.service.bukkit.BallBridgePlugin; +import cn.hamster3.service.bukkit.data.BukkitLocation; +import cn.hamster3.service.common.data.ServiceLocation; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import cn.hamster3.service.common.util.ComponentUtils; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.UUID; + +@SuppressWarnings("unused") +public abstract class ServiceMessageAPI { + + /** + * 订阅某个标签的消息 + * + * @param tag 标签 + */ + public static void subscribeTag(String tag) { + BallAPI.getInstance().subscribe(tag); + } + + /** + * 取消订阅某个标签的消息 + * + * @param tag 标签 + */ + public static void unsubscribeTag(String tag) { + BallAPI.getInstance().unsubscribe(tag); + } + + /** + * 发送一条服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + */ + public static void sendServiceMessage(String tag, String action) { + BallAPI.getInstance().sendRawBallMessage(tag, action); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + */ + public static void sendServiceMessage(String tag, String action, String content) { + BallAPI.getInstance().sendRawBallMessage(tag, action, content); + } + + /** + * 发送一条有附加参数的服务消息,使用 String.format() 替换附加参数 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @param args 替换参数 + * @see String#format(String, Object...) + */ + public static void sendServiceMessage(String tag, String action, String content, Object... args) { + BallAPI.getInstance().sendRawBallMessage(tag, action, new JsonPrimitive(String.format(content, args))); + } + + /** + * 发送一条有附加参数的消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + */ + public static void sendServiceMessage(String tag, String action, JsonElement content) { + BallAPI.getInstance().sendBallMessage(tag, new BallMessage(action, content), false, false); + } + + /** + * 自定义服务消息信息并发送 + * + * @param info 消息内容 + * @param block 是否阻塞(即必须等待消息发送完成,该方法才会返回) + */ + public static void sendServiceMessage(ServiceMessageInfo info, boolean block) { + BallMessage message = new BallMessage( + info.getSenderInfo().getName(), + info.getToServer(), + null, + info.getAction(), + info.getContent() + ); + BallAPI.getInstance().sendBallMessage(info.getTag(), message, false, block); + } + + /** + * 强制玩家执行一个 bukkit 命令 + * + * @param uuid 玩家的uuid + * @param command 命令内容 + */ + public static void dispatchBukkitCommand(UUID uuid, String command) { + sendServiceMessage("HamsterService", "dispatchBukkitCommand", command); + } + + /** + * 强制玩家执行一个代理端(指BungeeCord等)命令 + * + * @param uuid 玩家的uuid + * @param command 命令内容 + */ + public static void dispatchProxyCommand(UUID uuid, String command) { + sendServiceMessage("HamsterService", "dispatchProxyCommand", command); + } + + /** + * 给玩家发送一条消息 + * + * @param uuid 玩家 + * @param message 消息 + */ + public static void sendPlayerMessage(UUID uuid, String message) { + JsonObject object = new JsonObject(); + object.addProperty("text", message); + sendPlayerMessage(uuid, object); + } + + /** + * 给玩家发送一条消息 + * + * @param uuid 玩家 + * @param message 消息 + */ + public static void sendPlayerMessage(UUID uuid, JsonElement message) { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + player.spigot().sendMessage(ComponentUtils.parseComponentFromJson(message)); + return; + } + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("message", message); + sendServiceMessage("HamsterService", "sendPlayerMessage", object); + } + + /** + * 给服务器的在线玩家广播一条消息 + * + * @param message 消息 + * @since 2.1.0 + */ + public static void broadcastMessage(String message) { + JsonObject object = new JsonObject(); + object.addProperty("text", message); + broadcastMessage(object); + } + + /** + * 给服务器的在线玩家广播一条消息 + * + * @param message 消息 + * @since 2.1.0 + */ + public static void broadcastMessage(JsonElement message) { + sendServiceMessage("HamsterService", "broadcastMessage", message); + } + + /** + * 把玩家传送到另一个玩家身边 + *

+ * 支持跨服传送 + * + * @param sendPlayer 被传送的玩家 + * @param toPlayer 传送的目标玩家 + * @since 2.1.0 + */ + public static void sendPlayerToPlayer(UUID sendPlayer, UUID toPlayer) { + Player player = Bukkit.getPlayer(toPlayer); + if (player != null) { + sendPlayerToLocation(sendPlayer, new BukkitLocation(player)); + return; + } + + ServicePlayerInfo sendPlayerInfo = ServiceInfoAPI.getPlayerInfo(sendPlayer); + // 如果被传送玩家不在线 + if (sendPlayerInfo == null || !sendPlayerInfo.isOnline()) { + return; + } + + ServicePlayerInfo toPlayerInfo = ServiceInfoAPI.getPlayerInfo(toPlayer); + // 如果目标玩家不在线 + if (toPlayerInfo == null || !toPlayerInfo.isOnline()) { + return; + } + + JsonObject object = new JsonObject(); + object.addProperty("sendPlayer", sendPlayer.toString()); + object.addProperty("toPlayer", toPlayer.toString()); + sendServiceMessage("HamsterService", "sendPlayerToPlayer", object); + } + + /** + * 把玩家传送到一个位置 + *

+ * 支持跨服传送 + * + * @param uuid 玩家的uuid + * @param location 坐标 + * @since 2.1.0 + */ + public static void sendPlayerToLocation(UUID uuid, ServiceLocation location) { + Player player = Bukkit.getPlayer(uuid); + + // 如果玩家在线且目标服务器为当前服务器,则直接传送 + if (player != null && ServiceInfoAPI.getLocalServerName().equals(location.getServerName())) { + Bukkit.getScheduler().runTaskLater( + BallBridgePlugin.getInstance(), + () -> player.teleport( + new BukkitLocation(location).toBukkitLocation(), + PlayerTeleportEvent.TeleportCause.UNKNOWN + ), + 1 + ); + return; + } + + ServicePlayerInfo playerInfo = ServiceInfoAPI.getPlayerInfo(uuid); + + // 如果玩家不在线则什么都不做 + if (playerInfo == null || !playerInfo.isOnline()) { + return; + } + // 如果目标服务器不在线则什么都不做 + if (ServiceInfoAPI.getSenderInfo(location.getServerName()) == null) { + return; + } + + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("location", location.saveToJson()); + sendServiceMessage("HamsterService", "sendPlayerToLocation", object); + } + + public static void kickPlayer(UUID uuid, String reason) { + kickPlayer(uuid, new JsonPrimitive(reason)); + } + + public static void kickPlayer(UUID uuid, JsonElement reason) { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + player.kickPlayer(new TextComponent(ComponentUtils.parseComponentFromJson(reason)).toLegacyText()); + return; + } + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("reason", reason); + sendServiceMessage("HamsterService", "kickPlayer", object); + } + + /** + * 开启/关闭 安全模式 + *

+ * 在安全模式开启时玩家将无法连接至服务器 + *

+ * 且根据 config 的配置不同,有可能会踢出全部在线玩家 + * + * @param enable 是否启用 + */ + public static void setSafeMode(boolean enable) { + sendServiceMessage("HamsterService", "setSafeMode", new JsonPrimitive(enable)); + } + + /** + * 发送一条服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action) { + sendServiceMessage(tag, action); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, String content) { + sendServiceMessage(tag, action, content); + } + + /** + * 发送一条有附加参数的服务消息,使用 String.format() 替换附加参数 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @param args 替换参数 + * @see String#format(String, Object...) + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, String content, Object... args) { + sendServiceMessage(tag, action, content, args); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, JsonElement content) { + sendServiceMessage(tag, action, content); + } + + /** + * 自定义服务消息信息并发送 + * + * @param info 消息内容 + * @param block 是否阻塞(即必须等待消息发送完成,该方法才会返回) + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(ServiceMessageInfo info, boolean block) { + sendServiceMessage(info, block); + } + +} diff --git a/src/main/java/cn/hamster3/service/bukkit/command/ServiceCommand.java b/src/main/java/cn/hamster3/service/bukkit/command/ServiceCommand.java new file mode 100644 index 0000000..b0b43d3 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/command/ServiceCommand.java @@ -0,0 +1,35 @@ +package cn.hamster3.service.bukkit.command; + +import cn.hamster3.mc.plugin.core.bukkit.command.ParentCommand; +import cn.hamster3.service.bukkit.BallBridgePlugin; +import cn.hamster3.service.bukkit.command.sub.PlayerInfoCommand; +import cn.hamster3.service.bukkit.command.sub.ServerInfoCommand; +import cn.hamster3.service.bukkit.command.sub.SudoConsoleCommand; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +public class ServiceCommand extends ParentCommand { + public static final ServiceCommand INSTANCE = new ServiceCommand(); + + private ServiceCommand() { + addChildCommand(PlayerInfoCommand.INSTANCE); + addChildCommand(ServerInfoCommand.INSTANCE); + addChildCommand(SudoConsoleCommand.INSTANCE); + } + + @Override + public @NotNull JavaPlugin getPlugin() { + return BallBridgePlugin.getInstance(); + } + + @Override + public @NotNull String getName() { + return "hamster-service"; + } + + @Override + public boolean hasPermission(@NotNull CommandSender sender) { + return sender.hasPermission("hamster.service.admin"); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/command/sub/PlayerInfoCommand.java b/src/main/java/cn/hamster3/service/bukkit/command/sub/PlayerInfoCommand.java new file mode 100644 index 0000000..e7b0bf0 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/command/sub/PlayerInfoCommand.java @@ -0,0 +1,71 @@ +package cn.hamster3.service.bukkit.command.sub; + +import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand; +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class PlayerInfoCommand extends ChildCommand { + public static final PlayerInfoCommand INSTANCE = new PlayerInfoCommand(); + + private PlayerInfoCommand() { + } + + @Override + public @NotNull String getName() { + return "player-info"; + } + + @Override + public @NotNull String getUsage() { + return "player-info <玩家名>"; + } + + @Override + public boolean hasPermission(@NotNull CommandSender sender) { + return sender.hasPermission("hamster.service.admin"); + } + + @Override + public @NotNull String getDescription() { + return "查看玩家的信息"; + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length < 1) { + sender.sendMessage("§a/service player-info <玩家名>"); + return true; + } + ServicePlayerInfo playerInfo = ServiceInfoAPI.getPlayerInfo(args[0]); + if (playerInfo == null) { + sender.sendMessage("§c未找到玩家 " + args[0] + " 的信息!"); + return true; + } + sender.sendMessage("§a玩家UUID: " + playerInfo.getUuid()); + sender.sendMessage("§a玩家名称: " + playerInfo.getPlayerName()); + sender.sendMessage("§a在线状态: " + playerInfo.isOnline()); + sender.sendMessage("§a所在子服: " + playerInfo.getBukkitServer()); + sender.sendMessage("§a代理接入: " + playerInfo.getProxyServer()); + return true; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length == 1) { + return ServiceInfoAPI.getAllPlayerInfo().stream() + .map(ServicePlayerInfo::getPlayerName) + .filter(o -> o.toLowerCase().startsWith(args[0].toLowerCase())) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/command/sub/ServerInfoCommand.java b/src/main/java/cn/hamster3/service/bukkit/command/sub/ServerInfoCommand.java new file mode 100644 index 0000000..212ffb8 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/command/sub/ServerInfoCommand.java @@ -0,0 +1,69 @@ +package cn.hamster3.service.bukkit.command.sub; + +import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand; +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.common.entity.ServiceSenderInfo; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class ServerInfoCommand extends ChildCommand { + public static final ServerInfoCommand INSTANCE = new ServerInfoCommand(); + + private ServerInfoCommand() { + } + + @Override + public @NotNull String getName() { + return "server-info"; + } + + @Override + public @NotNull String getUsage() { + return "server-info <服务器ID>"; + } + + @Override + public boolean hasPermission(@NotNull CommandSender sender) { + return sender.hasPermission("hamster.service.admin"); + } + + @Override + public @NotNull String getDescription() { + return "查看服务器的信息"; + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length < 1) { + sender.sendMessage("§a/service server-info <服务器ID>"); + return true; + } + ServiceSenderInfo senderInfo = ServiceInfoAPI.getSenderInfo(args[0]); + if (senderInfo == null) { + sender.sendMessage("§c未找到服务器 " + args[0] + " 的信息!"); + return true; + } + sender.sendMessage("§a服务器ID: " + senderInfo.getName()); + sender.sendMessage("§a服务器别名: " + senderInfo.getNickName()); + sender.sendMessage("§a服务器类型: " + senderInfo.getType().name()); + return true; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length == 1) { + return ServiceInfoAPI.getAllSenderInfo().stream() + .map(ServiceSenderInfo::getName) + .filter(o -> o.toLowerCase().startsWith(args[0].toLowerCase())) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/command/sub/SudoConsoleCommand.java b/src/main/java/cn/hamster3/service/bukkit/command/sub/SudoConsoleCommand.java new file mode 100644 index 0000000..0ea1b97 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/command/sub/SudoConsoleCommand.java @@ -0,0 +1,79 @@ +package cn.hamster3.service.bukkit.command.sub; + +import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand; +import cn.hamster3.service.bukkit.api.ServiceMessageAPI; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class SudoConsoleCommand extends ChildCommand { + public static final SudoConsoleCommand INSTANCE = new SudoConsoleCommand(); + + private SudoConsoleCommand() { + } + + @Override + public @NotNull String getName() { + return "command"; + } + + @Override + public @NotNull String getUsage() { + return "command [bukkit/proxy] [命令内容]"; + } + + @Override + public boolean hasPermission(@NotNull CommandSender sender) { + return sender.hasPermission("hamster.service.admin"); + } + + @Override + public @NotNull String getDescription() { + return "广播控制台执行命令"; + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length < 2) { + sender.sendMessage("§c/service command [bukkit/proxy] [命令内容]"); + return true; + } + + String action; + switch (args[0].toLowerCase()) { + case "bukkit": { + action = "bukkitConsoleCommand"; + break; + } + case "proxy": { + action = "proxyConsoleCommand"; + break; + } + default: { + sender.sendMessage("§c/service command [bukkit/proxy] [命令内容]"); + return true; + } + } + StringBuilder builder = new StringBuilder(); + for (int i = 1; i < args.length; i++) { + builder.append(args[i]).append(" "); + } + ServiceMessageAPI.sendServiceMessage("HamsterService", action, builder.toString()); + sender.sendMessage("§c已广播命令执行信息."); + return true; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length == 1) { + return Arrays.asList("bukkit", "proxy"); + } + return Collections.emptyList(); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/data/BukkitBlockPos.java b/src/main/java/cn/hamster3/service/bukkit/data/BukkitBlockPos.java new file mode 100644 index 0000000..cc93bf3 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/data/BukkitBlockPos.java @@ -0,0 +1,59 @@ +package cn.hamster3.service.bukkit.data; + +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.common.data.ServiceBlockPos; +import com.google.gson.JsonObject; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; + +@SuppressWarnings("unused") +public class BukkitBlockPos extends ServiceBlockPos { + public BukkitBlockPos(@NotNull String serverName, @NotNull String worldName, int x, int y, int z) { + super(serverName, worldName, x, y, z); + } + + public BukkitBlockPos(@NotNull JsonObject object) { + super(object); + } + + public BukkitBlockPos(@NotNull Entity player) { + this(player.getLocation()); + } + + public BukkitBlockPos(@NotNull Block block) { + this(block.getLocation()); + } + + public BukkitBlockPos(@NotNull Location location) { + super( + ServiceInfoAPI.getLocalServerName(), + location.getWorld().getName(), + location.getBlockX(), + location.getBlockY(), + location.getBlockZ() + ); + } + + public BukkitBlockPos(@NotNull ServiceBlockPos location) { + super( + ServiceInfoAPI.getLocalServerName(), + location.getWorldName(), + location.getX(), + location.getY(), + location.getZ() + ); + } + + @NotNull + public Location toBukkitLocation() { + return new Location(Bukkit.getWorld(getWorldName()), getX(), getY(), getZ(), 0, 0); + } + + @NotNull + public BukkitLocation toServiceLocation() { + return new BukkitLocation(getServerName(), getWorldName(), getX(), getY(), getZ()); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/data/BukkitLocation.java b/src/main/java/cn/hamster3/service/bukkit/data/BukkitLocation.java new file mode 100644 index 0000000..0fe7f1d --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/data/BukkitLocation.java @@ -0,0 +1,68 @@ +package cn.hamster3.service.bukkit.data; + +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.common.data.ServiceLocation; +import com.google.gson.JsonObject; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; + +@SuppressWarnings("unused") +public class BukkitLocation extends ServiceLocation { + + public BukkitLocation(@NotNull String serverName, @NotNull String worldName, double x, double y, double z) { + super(serverName, worldName, x, y, z); + } + + public BukkitLocation(@NotNull String serverName, @NotNull String worldName, double x, double y, double z, float yaw, float pitch) { + super(serverName, worldName, x, y, z, yaw, pitch); + } + + public BukkitLocation(@NotNull JsonObject object) { + super(object); + } + + public BukkitLocation(@NotNull Entity player) { + this(player.getLocation()); + } + + public BukkitLocation(@NotNull Block block) { + this(block.getLocation()); + } + + public BukkitLocation(@NotNull Location location) { + super( + ServiceInfoAPI.getLocalServerName(), + location.getWorld().getName(), + location.getX(), + location.getY(), + location.getZ(), + location.getYaw(), + location.getPitch() + ); + } + + public BukkitLocation(@NotNull ServiceLocation location) { + super( + location.getServerName(), + location.getWorldName(), + location.getX(), + location.getY(), + location.getZ(), + location.getYaw(), + location.getPitch() + ); + } + + @NotNull + public Location toBukkitLocation() { + return new Location(Bukkit.getWorld(getWorldName()), getX(), getY(), getZ(), getYaw(), getPitch()); + } + + @NotNull + public BukkitBlockPos toServiceBlockPos() { + return new BukkitBlockPos(getServerName(), getWorldName(), getBlockX(), getBlockY(), getBlockZ()); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/event/MessageEvent.java b/src/main/java/cn/hamster3/service/bukkit/event/MessageEvent.java new file mode 100644 index 0000000..5a00442 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/event/MessageEvent.java @@ -0,0 +1,40 @@ +package cn.hamster3.service.bukkit.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * 服务消息事件的基类 + */ +@SuppressWarnings("unused") +public class MessageEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final ServiceMessageInfo messageInfo; + + public MessageEvent(ServiceMessageInfo messageInfo) { + super(!Bukkit.getServer().isPrimaryThread()); + this.messageInfo = messageInfo; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * 获取这次事件相关的消息信息 + * + * @return 消息信息 + */ + public ServiceMessageInfo getMessageInfo() { + return messageInfo; + } + + @Override + @NotNull + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/event/MessageReceivedEvent.java b/src/main/java/cn/hamster3/service/bukkit/event/MessageReceivedEvent.java new file mode 100644 index 0000000..aa02053 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/event/MessageReceivedEvent.java @@ -0,0 +1,27 @@ +package cn.hamster3.service.bukkit.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * 从服务中心收到消息时产生的事件 + */ +@SuppressWarnings("unused") +public class MessageReceivedEvent extends MessageEvent { + private static final HandlerList handlers = new HandlerList(); + + public MessageReceivedEvent(ServiceMessageInfo info) { + super(info); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + @NotNull + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/event/MessageSentEvent.java b/src/main/java/cn/hamster3/service/bukkit/event/MessageSentEvent.java new file mode 100644 index 0000000..001b8ac --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/event/MessageSentEvent.java @@ -0,0 +1,57 @@ +package cn.hamster3.service.bukkit.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * 消息发送出去之后产生的事件 + */ +@SuppressWarnings("unused") +public class MessageSentEvent extends MessageEvent { + private static final HandlerList handlers = new HandlerList(); + + private final boolean success; + private final Throwable cause; + + public MessageSentEvent(ServiceMessageInfo info) { + super(info); + success = true; + cause = null; + } + + public MessageSentEvent(ServiceMessageInfo messageInfo, Throwable cause) { + super(messageInfo); + success = false; + this.cause = cause; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * 消息是否成功发送出去了 + * + * @return true代表成功发送 + */ + public boolean isSuccess() { + return success; + } + + /** + * 若消息发送失败,则失败原因为何 + * 若发送成功,则返回null + * + * @return 失败原因 + */ + public Throwable getCause() { + return cause; + } + + @Override + @NotNull + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/event/ServiceConnectEvent.java b/src/main/java/cn/hamster3/service/bukkit/event/ServiceConnectEvent.java new file mode 100644 index 0000000..c778afe --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/event/ServiceConnectEvent.java @@ -0,0 +1,58 @@ +package cn.hamster3.service.bukkit.event; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * 服务连接事件 + */ + +@SuppressWarnings("unused") +public class ServiceConnectEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final boolean success; + private final Throwable cause; + + public ServiceConnectEvent() { + super(true); + success = true; + cause = null; + } + + public ServiceConnectEvent(Throwable cause) { + super(true); + success = false; + this.cause = cause; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * 是否成功连接到服务中心 + * + * @return true代表成功 + */ + public boolean isSuccess() { + return success; + } + + /** + * 如果连接失败了,则返回失败原因 + *

+ * 如果连接成功了,则返回null + * + * @return 失败原因 + */ + public Throwable getCause() { + return cause; + } + + @Override + @NotNull + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/hook/ServicePlaceholderHook.java b/src/main/java/cn/hamster3/service/bukkit/hook/ServicePlaceholderHook.java new file mode 100644 index 0000000..695c412 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/hook/ServicePlaceholderHook.java @@ -0,0 +1,58 @@ +package cn.hamster3.service.bukkit.hook; + +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceSenderInfo; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ServicePlaceholderHook extends PlaceholderExpansion { + public static final ServicePlaceholderHook INSTANCE = new ServicePlaceholderHook(); + + private ServicePlaceholderHook() { + } + + @Override + public @NotNull String getIdentifier() { + return "HamsterService"; + } + + @Override + public @NotNull String getAuthor() { + return "Hamster3"; + } + + @Override + public @NotNull String getVersion() { + return "1.0.0"; + } + + @Override + public String onRequest(OfflinePlayer player, @NotNull String params) { + ServiceSenderInfo localSenderInfo = ServiceInfoAPI.getLocalSenderInfo(); + switch (params) { + case "server_name": + return localSenderInfo.getName(); + case "server_nick_name": + return localSenderInfo.getNickName(); + } + ServicePlayerInfo info = ServiceInfoAPI.getPlayerInfo(player.getUniqueId()); + if (info == null) { + return null; + } + switch (params) { + case "proxy_name": + return info.getProxyServer(); + case "proxy_nick_name": + return ServiceInfoAPI.getSenderInfo(info.getProxyServer()).getNickName(); // 不可能为 null + } + return null; + } + + @Override + public String onPlaceholderRequest(Player player, @NotNull String params) { + return onRequest(player, params); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/listener/BridgeListener.java b/src/main/java/cn/hamster3/service/bukkit/listener/BridgeListener.java new file mode 100644 index 0000000..81b2760 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/listener/BridgeListener.java @@ -0,0 +1,37 @@ +package cn.hamster3.service.bukkit.listener; + +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.bukkit.event.MessageReceivedEvent; +import cn.hamster3.service.bukkit.event.MessageSentEvent; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import com.google.common.eventbus.Subscribe; +import org.bukkit.Bukkit; + +public class BridgeListener { + public static final BridgeListener INSTANCE = new BridgeListener(); + + private BridgeListener() { + } + + @Subscribe + public void onMessageSent(cn.hamster3.mc.plugin.ball.common.event.message.MessageSentEvent event) { + Bukkit.getPluginManager().callEvent(new MessageSentEvent(new ServiceMessageInfo( + ServiceInfoAPI.getSenderInfo(event.getSenderID()), + event.getReceiverID(), + event.getChannel(), + event.getAction(), + event.getContent() + ))); + } + + @Subscribe + public void onMessageReceived(cn.hamster3.mc.plugin.ball.common.event.message.MessageReceivedEvent event) { + Bukkit.getPluginManager().callEvent(new MessageReceivedEvent(new ServiceMessageInfo( + ServiceInfoAPI.getSenderInfo(event.getSenderID()), + event.getReceiverID(), + event.getChannel(), + event.getAction(), + event.getContent() + ))); + } +} diff --git a/src/main/java/cn/hamster3/service/bukkit/listener/ServiceMainListener.java b/src/main/java/cn/hamster3/service/bukkit/listener/ServiceMainListener.java new file mode 100644 index 0000000..74dc0e2 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bukkit/listener/ServiceMainListener.java @@ -0,0 +1,105 @@ +package cn.hamster3.service.bukkit.listener; + +import cn.hamster3.service.bukkit.BallBridgePlugin; +import cn.hamster3.service.bukkit.api.ServiceInfoAPI; +import cn.hamster3.service.bukkit.api.ServiceMessageAPI; +import cn.hamster3.service.bukkit.data.BukkitLocation; +import cn.hamster3.service.bukkit.event.MessageReceivedEvent; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import com.google.gson.JsonObject; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.HashMap; +import java.util.UUID; + +public class ServiceMainListener implements Listener { + public static final ServiceMainListener INSTANCE = new ServiceMainListener(); + + private final HashMap playerToLocations; + + private ServiceMainListener() { + playerToLocations = new HashMap<>(); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + UUID uuid = player.getUniqueId(); + Location location = playerToLocations.remove(uuid); + if (location == null) { + return; + } + Bukkit.getScheduler().runTaskLater( + BallBridgePlugin.getInstance(), + () -> player.teleport(location, PlayerTeleportEvent.TeleportCause.PLUGIN), + 20 + ); + } + + @EventHandler(ignoreCancelled = true) + public void onMessageReceived(MessageReceivedEvent event) { + ServiceMessageInfo info = event.getMessageInfo(); + if (!"HamsterService".equals(info.getTag())) { + return; + } + switch (info.getAction()) { + case "bukkitConsoleCommand": { + Bukkit.getScheduler().runTask( + BallBridgePlugin.getInstance(), + () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), info.getContentAsString()) + ); + break; + } + case "dispatchBukkitCommand": { + JsonObject object = info.getContentAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + Player player = Bukkit.getPlayer(uuid); + if (player == null) { + return; + } + Bukkit.getScheduler().runTask( + BallBridgePlugin.getInstance(), + () -> Bukkit.dispatchCommand(player, object.get("command").getAsString()) + ); + break; + } + case "sendPlayerToPlayer": { + JsonObject object = info.getContentAsJsonObject(); + Player player = Bukkit.getPlayer(UUID.fromString(object.get("toPlayer").getAsString())); + if (player != null) { + UUID uuid = UUID.fromString(object.get("sendPlayer").getAsString()); + ServiceMessageAPI.sendPlayerToLocation(uuid, new BukkitLocation(player)); + } + break; + } + case "sendPlayerToLocation": { + JsonObject object = info.getContentAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + BukkitLocation location = new BukkitLocation(object.getAsJsonObject("location")); + if (!ServiceInfoAPI.getLocalServerName().equals(location.getServerName())) { + return; + } + Player player = Bukkit.getPlayer(uuid); + Location bukkitLocation = location.toBukkitLocation(); + if (player == null) { + playerToLocations.put(uuid, bukkitLocation); + return; + } + Bukkit.getScheduler().runTaskLater( + BallBridgePlugin.getInstance(), + () -> player.teleport(bukkitLocation, PlayerTeleportEvent.TeleportCause.UNKNOWN), + 1 + ); + break; + } + } + } + +} diff --git a/src/main/java/cn/hamster3/service/bungee/BallBridgePlugin.java b/src/main/java/cn/hamster3/service/bungee/BallBridgePlugin.java new file mode 100644 index 0000000..6a28424 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/BallBridgePlugin.java @@ -0,0 +1,27 @@ +package cn.hamster3.service.bungee; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.service.bungee.command.ServiceCommand; +import cn.hamster3.service.bungee.listener.BridgeListener; +import cn.hamster3.service.bungee.listener.ServiceMainListener; +import cn.hamster3.service.common.util.ServiceLogUtils; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.plugin.Plugin; + +public class BallBridgePlugin extends Plugin { + public static void main(String[] args) { + } + + @Override + public void onLoad() { + ServiceLogUtils.setLogger(getLogger()); + } + + @Override + public void onEnable() { + BallAPI.getInstance().getEventBus().register(BridgeListener.INSTANCE); + ProxyServer.getInstance().getPluginManager().registerListener(this, ServiceMainListener.INSTANCE); + ProxyServer.getInstance().getPluginManager().registerCommand(this, ServiceCommand.INSTANCE); + BallAPI.getInstance().subscribeIgnorePrefix("HamsterService"); + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/api/ServiceInfoAPI.java b/src/main/java/cn/hamster3/service/bungee/api/ServiceInfoAPI.java new file mode 100644 index 0000000..f331ec4 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/api/ServiceInfoAPI.java @@ -0,0 +1,141 @@ +package cn.hamster3.service.bungee.api; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo; +import cn.hamster3.mc.plugin.ball.common.entity.BallServerInfo; +import cn.hamster3.mc.plugin.ball.common.entity.BallServerType; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceSenderInfo; +import cn.hamster3.service.common.entity.ServiceSenderType; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.UUID; +import java.util.stream.Collectors; + +@SuppressWarnings("unused") +public class ServiceInfoAPI { + /** + * 获取玩家信息,当玩家不在线时返回 null + * + * @param uuid 玩家的UUID + * @return 玩家信息 + */ + public static ServicePlayerInfo getPlayerInfo(@NotNull UUID uuid) { + return transfer(BallAPI.getInstance().getPlayerInfo(uuid)); + } + + /** + * 获取玩家信息,当玩家不在线时返回 null + * + * @param playerName 玩家ID + * @return 玩家信息 + */ + public static ServicePlayerInfo getPlayerInfo(@NotNull String playerName) { + return transfer(BallAPI.getInstance().getPlayerInfo(playerName)); + } + + /** + * 获取全部在线玩家的信息 + * + * @return 玩家们的信息 + */ + public static HashSet getOnlinePlayers() { + return BallAPI.getInstance().getAllPlayerInfo().values() + .stream() + .filter(BallPlayerInfo::isOnline) + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * 获取全部在线玩家的信息 + * + * @return 玩家们的信息 + */ + public static HashSet getAllPlayerInfo() { + return BallAPI.getInstance().getAllPlayerInfo().values() + .stream() + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * 获取服务端信息 + * + * @param senderName 服务端id + * @return 服务端信息 + */ + public static ServiceSenderInfo getSenderInfo(String senderName) { + return transfer(BallAPI.getInstance().getServerInfo(senderName)); + } + + /** + * 获取所有连接至服务中心的信息 + * + * @return 服务器信息 + */ + public static HashSet getAllSenderInfo() { + return BallAPI.getInstance().getAllServerInfo().values() + .stream() + .map(ServiceInfoAPI::transfer) + .collect(Collectors.toCollection(HashSet::new)); + + } + + /** + * 获取当前服务器的名称 + * + * @return 服务器id + */ + public static String getLocalServerName() { + return BallAPI.getInstance().getLocalServerId(); + } + + /** + * 获取当前服务器的别名 + * + * @return 服务器别名 + */ + public static String getLocalServerNickName() { + return BallAPI.getInstance().getLocalServerInfo().getName(); + } + + /** + * 获取当前服务器的SenderInfo对象 + * + * @return 当前服务器的发送者信息 + */ + public static ServiceSenderInfo getLocalSenderInfo() { + return new ServiceSenderInfo( + ServiceSenderType.PROXY, + BallAPI.getInstance().getLocalServerInfo().getId(), + BallAPI.getInstance().getLocalServerInfo().getName() + ); + } + + public static ServiceSenderInfo transfer(BallServerInfo info) { + if (info == null) { + return null; + } + return new ServiceSenderInfo( + info.getType() == BallServerType.PROXY ? ServiceSenderType.PROXY : ServiceSenderType.BUKKIT, + info.getId(), + info.getName() + ); + } + + public static ServicePlayerInfo transfer(BallPlayerInfo info) { + if (info == null) { + return null; + } + return new ServicePlayerInfo( + info.getUuid(), + info.getName(), + info.getGameServer(), + info.getProxyServer(), + info.isOnline() + ); + } + +} diff --git a/src/main/java/cn/hamster3/service/bungee/api/ServiceMessageAPI.java b/src/main/java/cn/hamster3/service/bungee/api/ServiceMessageAPI.java new file mode 100644 index 0000000..714a58b --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/api/ServiceMessageAPI.java @@ -0,0 +1,329 @@ +package cn.hamster3.service.bungee.api; + +import cn.hamster3.mc.plugin.ball.common.api.BallAPI; +import cn.hamster3.mc.plugin.ball.common.data.BallMessage; +import cn.hamster3.service.common.data.ServiceLocation; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import cn.hamster3.service.common.util.ComponentUtils; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import java.util.UUID; + +@SuppressWarnings("unused") +public abstract class ServiceMessageAPI { + + /** + * 订阅某个标签的消息 + * + * @param tag 标签 + */ + public static void subscribeTag(String tag) { + sendServiceMessage("HamsterService", "subscribeTag", tag); + } + + /** + * 取消订阅某个标签的消息 + * + * @param tag 标签 + */ + public static void unsubscribeTag(String tag) { + sendServiceMessage("HamsterService", "unsubscribeTag", tag); + } + + /** + * 发送一条服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + */ + public static void sendServiceMessage(String tag, String action) { + BallAPI.getInstance().sendRawBallMessage(tag, action); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + */ + public static void sendServiceMessage(String tag, String action, String content) { + BallAPI.getInstance().sendRawBallMessage(tag, action, content); + } + + /** + * 发送一条有附加参数的服务消息,使用 String.format() 替换附加参数 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @param args 替换参数 + * @see String#format(String, Object...) + */ + public static void sendServiceMessage(String tag, String action, String content, Object... args) { + BallAPI.getInstance().sendRawBallMessage(tag, action, new JsonPrimitive(String.format(content, args))); + } + + /** + * 发送一条有附加参数的消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + */ + public static void sendServiceMessage(String tag, String action, JsonElement content) { + BallAPI.getInstance().sendBallMessage(tag, new BallMessage(action, content), false, false); + } + + /** + * 自定义服务消息信息并发送 + * + * @param info 消息内容 + * @param block 是否阻塞(即必须等待消息发送完成,该方法才会返回) + */ + public static void sendServiceMessage(ServiceMessageInfo info, boolean block) { + BallMessage message = new BallMessage( + info.getSenderInfo().getName(), + info.getToServer(), + null, + info.getAction(), + info.getContent() + ); + BallAPI.getInstance().sendBallMessage(info.getTag(), message, false, block); + } + + /** + * 强制玩家执行一个 bukkit 命令 + * + * @param uuid 玩家的uuid + * @param command 命令内容 + */ + public static void dispatchBukkitCommand(UUID uuid, String command) { + sendServiceMessage("HamsterService", "dispatchBukkitCommand", command); + } + + /** + * 强制玩家执行一个代理端(指BungeeCord等)命令 + * + * @param uuid 玩家的uuid + * @param command 命令内容 + */ + public static void dispatchProxyCommand(UUID uuid, String command) { + sendServiceMessage("HamsterService", "dispatchProxyCommand", command); + } + + /** + * 给玩家发送一条消息 + * + * @param uuid 玩家 + * @param message 消息 + */ + public static void sendPlayerMessage(UUID uuid, String message) { + sendPlayerMessage(uuid, new JsonPrimitive(message)); + } + + /** + * 给玩家发送一条消息 + * + * @param uuid 玩家 + * @param message 消息 + */ + public static void sendPlayerMessage(UUID uuid, JsonElement message) { + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player != null) { + player.sendMessage(ComponentUtils.parseComponentFromJson(message)); + return; + } + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("message", message); + sendServiceMessage("HamsterService", "sendPlayerMessage", object); + } + + /** + * 给服务器的在线玩家广播一条消息 + * + * @param message 消息 + * @since 2.1.0 + */ + public static void broadcastMessage(String message) { + JsonObject object = new JsonObject(); + object.addProperty("text", message); + broadcastMessage(object); + } + + /** + * 给服务器的在线玩家广播一条消息 + * + * @param message 消息 + * @since 2.1.0 + */ + public static void broadcastMessage(JsonElement message) { + sendServiceMessage("HamsterService", "broadcastMessage", message); + } + + /** + * 把玩家传送到另一个玩家身边 + *

+ * 支持跨服传送 + * + * @param sendPlayer 被传送的玩家 + * @param toPlayer 传送的目标玩家 + * @since 2.1.0 + */ + public static void sendPlayerToPlayer(UUID sendPlayer, UUID toPlayer) { + ServicePlayerInfo sendPlayerInfo = ServiceInfoAPI.getPlayerInfo(sendPlayer); + // 如果被传送玩家不在线 + if (sendPlayerInfo == null || !sendPlayerInfo.isOnline()) { + return; + } + + ServicePlayerInfo toPlayerInfo = ServiceInfoAPI.getPlayerInfo(toPlayer); + // 如果目标玩家不在线 + if (toPlayerInfo == null || !toPlayerInfo.isOnline()) { + return; + } + + JsonObject object = new JsonObject(); + object.addProperty("sendPlayer", sendPlayer.toString()); + object.addProperty("toPlayer", toPlayer.toString()); + sendServiceMessage("HamsterService", "sendPlayerToPlayer", object); + } + + /** + * 把玩家传送到一个位置 + *

+ * 支持跨服传送 + * + * @param uuid 玩家的uuid + * @param location 坐标 + * @since 2.1.0 + */ + public static void sendPlayerToLocation(UUID uuid, ServiceLocation location) { + ServicePlayerInfo playerInfo = ServiceInfoAPI.getPlayerInfo(uuid); + + // 如果玩家不在线 + if (playerInfo == null || !playerInfo.isOnline()) { + return; + } + // 如果目标服务器不在线 + if (ServiceInfoAPI.getSenderInfo(location.getServerName()) == null) { + return; + } + + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("location", location.saveToJson()); + sendServiceMessage("HamsterService", "sendPlayerToLocation", object); + } + + public static void kickPlayer(UUID uuid, String reason) { + kickPlayer(uuid, new JsonPrimitive(reason)); + } + + public static void kickPlayer(UUID uuid, JsonElement reason) { + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player != null) { + player.disconnect(ComponentUtils.parseComponentFromJson(reason)); + return; + } + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.add("reason", reason); + sendServiceMessage("HamsterService", "kickPlayer", object); + } + + /** + * 开启/关闭 安全模式 + *

+ * 在安全模式开启时玩家将无法连接至服务器 + *

+ * 且根据 config 的配置不同,有可能会踢出全部在线玩家 + * + * @param enable 是否启用 + */ + public static void setSafeMode(boolean enable) { + sendServiceMessage("HamsterService", "setSafeMode", new JsonPrimitive(enable)); + } + + /** + * 发送一条服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action) { + sendServiceMessage(tag, action); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, String content) { + sendServiceMessage(tag, action, content); + } + + /** + * 发送一条有附加参数的服务消息,使用 String.format() 替换附加参数 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @param args 替换参数 + * @see String#format(String, Object...) + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, String content, Object... args) { + sendServiceMessage(tag, action, content, args); + } + + /** + * 发送一条有附加参数的服务消息 + * + * @param tag 消息标签 + * @param action 执行动作 + * @param content 附加参数 + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(String tag, String action, JsonElement content) { + sendServiceMessage(tag, action, content); + } + + /** + * 自定义服务消息信息并发送 + * + * @param info 消息内容 + * @param block 是否阻塞(即必须等待消息发送完成,该方法才会返回) + * @deprecated 你应该使用 sendServiceMessage + *

+ * 因为这个方法名有歧义 + */ + @Deprecated + public static void sendMessage(ServiceMessageInfo info, boolean block) { + sendServiceMessage(info, block); + } + +} diff --git a/src/main/java/cn/hamster3/service/bungee/command/ServiceCommand.java b/src/main/java/cn/hamster3/service/bungee/command/ServiceCommand.java new file mode 100644 index 0000000..8c863eb --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/command/ServiceCommand.java @@ -0,0 +1,35 @@ +package cn.hamster3.service.bungee.command; + +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.plugin.Command; + +public class ServiceCommand extends Command { + public static final ServiceCommand INSTANCE = new ServiceCommand(); + + private ServiceCommand() { + super("serviceb", "service.admin"); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (!sender.hasPermission("service.admin")) { + sender.sendMessage(new TextComponent("§c你没有权限执行这个命令!")); + return; + } + if (args.length < 1) { + sender.sendMessage(new TextComponent("§c/service command [bukkit/proxy] [命令内容]")); + return; + } + switch (args[0]) { + case "command": { + SudoConsoleCommand.INSTANCE.onCommand(sender, args); + break; + } + case "": { + break; + } + } + + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/command/SudoConsoleCommand.java b/src/main/java/cn/hamster3/service/bungee/command/SudoConsoleCommand.java new file mode 100644 index 0000000..c02887e --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/command/SudoConsoleCommand.java @@ -0,0 +1,42 @@ +package cn.hamster3.service.bungee.command; + +import cn.hamster3.service.bungee.api.ServiceMessageAPI; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.chat.TextComponent; +import org.jetbrains.annotations.NotNull; + +public class SudoConsoleCommand { + public static final SudoConsoleCommand INSTANCE = new SudoConsoleCommand(); + + private SudoConsoleCommand() { + } + + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { + if (args.length < 3) { + sender.sendMessage(new TextComponent("§c/service command [bukkit/proxy] [命令内容]")); + return; + } + + String action; + switch (args[1].toLowerCase()) { + case "bukkit": { + action = "bukkitConsoleCommand"; + break; + } + case "proxy": { + action = "proxyConsoleCommand"; + break; + } + default: { + sender.sendMessage(new TextComponent("§c/service command [bukkit/proxy] [命令内容]")); + return; + } + } + StringBuilder builder = new StringBuilder(); + for (int i = 2; i < args.length; i++) { + builder.append(args[i]).append(" "); + } + ServiceMessageAPI.sendServiceMessage("HamsterService", action, builder.toString()); + sender.sendMessage(new TextComponent("§c已广播命令执行信息.")); + } +} \ No newline at end of file diff --git a/src/main/java/cn/hamster3/service/bungee/event/MessageEvent.java b/src/main/java/cn/hamster3/service/bungee/event/MessageEvent.java new file mode 100644 index 0000000..9a1e101 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/event/MessageEvent.java @@ -0,0 +1,21 @@ +package cn.hamster3.service.bungee.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import net.md_5.bungee.api.plugin.Event; + +/** + * 服务消息事件的基类 + */ +@SuppressWarnings("unused") +public class MessageEvent extends Event { + private final ServiceMessageInfo messageInfo; + + public MessageEvent(ServiceMessageInfo messageInfo) { + this.messageInfo = messageInfo; + } + + public ServiceMessageInfo getMessageInfo() { + return messageInfo; + } + +} diff --git a/src/main/java/cn/hamster3/service/bungee/event/MessageReceivedEvent.java b/src/main/java/cn/hamster3/service/bungee/event/MessageReceivedEvent.java new file mode 100644 index 0000000..ae33d13 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/event/MessageReceivedEvent.java @@ -0,0 +1,14 @@ +package cn.hamster3.service.bungee.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; + +/** + * 从服务中心收到消息时产生的事件 + */ +@SuppressWarnings("unused") +public class MessageReceivedEvent extends MessageEvent { + + public MessageReceivedEvent(ServiceMessageInfo info) { + super(info); + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/event/MessageSentEvent.java b/src/main/java/cn/hamster3/service/bungee/event/MessageSentEvent.java new file mode 100644 index 0000000..c8db2ed --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/event/MessageSentEvent.java @@ -0,0 +1,44 @@ +package cn.hamster3.service.bungee.event; + +import cn.hamster3.service.common.entity.ServiceMessageInfo; + +/** + * 消息发送出去之后产生的事件 + */ +@SuppressWarnings("unused") +public class MessageSentEvent extends MessageEvent { + private final boolean success; + private final Throwable cause; + + public MessageSentEvent(ServiceMessageInfo info) { + super(info); + success = true; + cause = null; + } + + public MessageSentEvent(ServiceMessageInfo messageInfo, Throwable cause) { + super(messageInfo); + success = false; + this.cause = cause; + } + + + /** + * 消息是否成功发送出去了 + * + * @return true代表成功发送 + */ + public boolean isSuccess() { + return success; + } + + /** + * 若消息发送失败,则失败原因为何 + * 若发送成功,则返回null + * + * @return 失败原因 + */ + public Throwable getCause() { + return cause; + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/event/ServiceConnectEvent.java b/src/main/java/cn/hamster3/service/bungee/event/ServiceConnectEvent.java new file mode 100644 index 0000000..b397520 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/event/ServiceConnectEvent.java @@ -0,0 +1,45 @@ +package cn.hamster3.service.bungee.event; + + +import net.md_5.bungee.api.plugin.Event; + +/** + * 服务连接事件 + */ + +@SuppressWarnings("unused") +public class ServiceConnectEvent extends Event { + private final boolean success; + private final Throwable cause; + + public ServiceConnectEvent() { + success = true; + cause = null; + } + + public ServiceConnectEvent(Throwable cause) { + success = false; + this.cause = cause; + } + + + /** + * 是否成功连接到服务中心 + * + * @return true代表成功 + */ + public boolean isSuccess() { + return success; + } + + /** + * 如果连接失败了,则返回失败原因 + *

+ * 如果连接成功了,则返回null + * + * @return 失败原因 + */ + public Throwable getCause() { + return cause; + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/listener/BridgeListener.java b/src/main/java/cn/hamster3/service/bungee/listener/BridgeListener.java new file mode 100644 index 0000000..5ac676c --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/listener/BridgeListener.java @@ -0,0 +1,37 @@ +package cn.hamster3.service.bungee.listener; + +import cn.hamster3.service.bungee.api.ServiceInfoAPI; +import cn.hamster3.service.bungee.event.MessageReceivedEvent; +import cn.hamster3.service.bungee.event.MessageSentEvent; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import com.google.common.eventbus.Subscribe; +import net.md_5.bungee.api.ProxyServer; + +public class BridgeListener { + public static final BridgeListener INSTANCE = new BridgeListener(); + + private BridgeListener() { + } + + @Subscribe + public void onMessageSent(cn.hamster3.mc.plugin.ball.common.event.message.MessageSentEvent event) { + ProxyServer.getInstance().getPluginManager().callEvent(new MessageSentEvent(new ServiceMessageInfo( + ServiceInfoAPI.getSenderInfo(event.getSenderID()), + event.getReceiverID(), + event.getChannel(), + event.getAction(), + event.getContent() + ))); + } + + @Subscribe + public void onMessageReceived(cn.hamster3.mc.plugin.ball.common.event.message.MessageReceivedEvent event) { + ProxyServer.getInstance().getPluginManager().callEvent(new MessageReceivedEvent(new ServiceMessageInfo( + ServiceInfoAPI.getSenderInfo(event.getSenderID()), + event.getReceiverID(), + event.getChannel(), + event.getAction(), + event.getContent() + ))); + } +} diff --git a/src/main/java/cn/hamster3/service/bungee/listener/ServiceMainListener.java b/src/main/java/cn/hamster3/service/bungee/listener/ServiceMainListener.java new file mode 100644 index 0000000..c21eb63 --- /dev/null +++ b/src/main/java/cn/hamster3/service/bungee/listener/ServiceMainListener.java @@ -0,0 +1,158 @@ +package cn.hamster3.service.bungee.listener; + +import cn.hamster3.service.bungee.api.ServiceInfoAPI; +import cn.hamster3.service.bungee.api.ServiceMessageAPI; +import cn.hamster3.service.bungee.event.MessageReceivedEvent; +import cn.hamster3.service.bungee.event.ServiceConnectEvent; +import cn.hamster3.service.common.data.ServiceLocation; +import cn.hamster3.service.common.data.ServicePlayerInfo; +import cn.hamster3.service.common.entity.ServiceMessageInfo; +import cn.hamster3.service.common.entity.ServiceSenderInfo; +import cn.hamster3.service.common.util.ComponentUtils; +import cn.hamster3.service.common.util.ServiceLogUtils; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.PlayerDisconnectEvent; +import net.md_5.bungee.api.event.PostLoginEvent; +import net.md_5.bungee.api.event.ServerConnectedEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; + +import java.util.UUID; + +public class ServiceMainListener implements Listener { + public static final ServiceMainListener INSTANCE = new ServiceMainListener(); + + private ServiceMainListener() { + } + + @EventHandler + public void onServiceConnect(ServiceConnectEvent event) { + if (!event.isSuccess()) { + return; + } + ServiceLogUtils.info("连接至服务中心成功..."); + JsonArray playerInfoArray = new JsonArray(); + for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { + ServicePlayerInfo playerInfo = new ServicePlayerInfo( + player.getUniqueId(), + player.getName(), + player.getServer().getInfo().getName(), + ServiceInfoAPI.getLocalServerName() + ); + playerInfoArray.add(playerInfo.saveToJson()); + } + ServiceMessageAPI.sendServiceMessage("HamsterService", "updatePlayerInfoArray", playerInfoArray); + } + + @EventHandler + public void onMessageReceived(MessageReceivedEvent event) { + ServiceMessageInfo info = event.getMessageInfo(); + if (!"HamsterService".equals(info.getTag())) { + return; + } + switch (info.getAction()) { + case "sendPlayerMessage": { + JsonObject object = info.getContentAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player == null) { + return; + } + player.sendMessage(ComponentUtils.parseComponentFromJson(object.get("message"))); + break; + } + case "broadcastMessage": { + ProxyServer.getInstance().broadcast(ComponentUtils.parseComponentFromJson(info.getContentAsJsonObject())); + break; + } + case "proxyConsoleCommand": { + ProxyServer.getInstance().getPluginManager().dispatchCommand( + ProxyServer.getInstance().getConsole(), + info.getContentAsString() + ); + break; + } + case "dispatchProxyCommand": { + JsonObject object = info.getContentAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player == null) { + return; + } + ProxyServer.getInstance().getPluginManager().dispatchCommand(player, object.get("command").getAsString()); + break; + } + case "sendPlayerToLocation": { + JsonObject object = info.getContent().getAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player == null) { + return; + } + ServiceLocation location = new ServiceLocation(object.getAsJsonObject("location")); + if (location.getServerName().equals(player.getServer().getInfo().getName())) { + return; + } + ServiceSenderInfo senderInfo = ServiceInfoAPI.getSenderInfo(location.getServerName()); + if (senderInfo == null) { + return; + } + player.connect(ProxyServer.getInstance().getServerInfo(location.getServerName())); + break; + } + case "kickPlayer": { + JsonObject object = info.getContentAsJsonObject(); + UUID uuid = UUID.fromString(object.get("uuid").getAsString()); + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); + if (player != null) { + player.disconnect(ComponentUtils.parseComponentFromJson(object.get("reason"))); + return; + } + break; + } + } + } + + @EventHandler + public void onServerConnected(ServerConnectedEvent event) { + ProxiedPlayer player = event.getPlayer(); + ServicePlayerInfo playerInfo = new ServicePlayerInfo( + player.getUniqueId(), + player.getName(), + event.getServer().getInfo().getName(), + ServiceInfoAPI.getLocalServerName() + ); + ServiceMessageAPI.sendServiceMessage("HamsterService", "updatePlayerInfo", playerInfo.saveToJson()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPostLogin(PostLoginEvent event) { + ProxiedPlayer player = event.getPlayer(); + ServicePlayerInfo playerInfo = new ServicePlayerInfo( + player.getUniqueId(), + player.getName(), + null, + ServiceInfoAPI.getLocalServerName(), + true + ); + ServiceMessageAPI.sendServiceMessage("HamsterService", "playerPostLogin", playerInfo.saveToJson()); + } + + @EventHandler + public void onPlayerDisconnect(PlayerDisconnectEvent event) { + ProxiedPlayer player = event.getPlayer(); + ServicePlayerInfo playerInfo = new ServicePlayerInfo( + player.getUniqueId(), + player.getName(), + null, + ServiceInfoAPI.getLocalServerName(), + false + ); + ServiceMessageAPI.sendServiceMessage("HamsterService", "playerDisconnect", playerInfo.saveToJson()); + } + +} diff --git a/src/main/java/cn/hamster3/service/common/data/ServiceBlockPos.java b/src/main/java/cn/hamster3/service/common/data/ServiceBlockPos.java new file mode 100644 index 0000000..bed91e6 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/data/ServiceBlockPos.java @@ -0,0 +1,101 @@ +package cn.hamster3.service.common.data; + +import com.google.gson.JsonObject; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +@SuppressWarnings("unused") +public class ServiceBlockPos { + @NotNull + private String serverName; + @NotNull + private String worldName; + private int x; + private int y; + private int z; + + public ServiceBlockPos(@NotNull String serverName, @NotNull String worldName, int x, int y, int z) { + this.serverName = serverName; + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + } + + public ServiceBlockPos(@NotNull JsonObject object) { + serverName = object.get("serverName").getAsString(); + worldName = object.get("worldName").getAsString(); + + x = object.get("x").getAsInt(); + y = object.get("y").getAsInt(); + z = object.get("z").getAsInt(); + } + + @NotNull + public JsonObject saveToJson() { + JsonObject object = new JsonObject(); + object.addProperty("serverName", serverName); + object.addProperty("worldName", worldName); + + object.addProperty("x", x); + object.addProperty("y", y); + object.addProperty("z", z); + return object; + } + + @NotNull + public String getServerName() { + return serverName; + } + + public void setServerName(@NotNull String serverName) { + this.serverName = serverName; + } + + @NotNull + public String getWorldName() { + return worldName; + } + + public void setWorldName(@NotNull String worldName) { + this.worldName = worldName; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public int getZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ServiceBlockPos that = (ServiceBlockPos) o; + return x == that.x && y == that.y && z == that.z && serverName.equals(that.serverName) && worldName.equals(that.worldName); + } + + @Override + public int hashCode() { + return Objects.hash(serverName, worldName, x, y, z); + } +} diff --git a/src/main/java/cn/hamster3/service/common/data/ServiceLocation.java b/src/main/java/cn/hamster3/service/common/data/ServiceLocation.java new file mode 100644 index 0000000..0b84da5 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/data/ServiceLocation.java @@ -0,0 +1,148 @@ +package cn.hamster3.service.common.data; + +import com.google.gson.JsonObject; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +@SuppressWarnings("unused") +public class ServiceLocation { + @NotNull + private String serverName; + @NotNull + private String worldName; + private double x; + private double y; + private double z; + + private float yaw; + private float pitch; + + public ServiceLocation(@NotNull String serverName, @NotNull String worldName, double x, double y, double z) { + this.serverName = serverName; + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + } + + public ServiceLocation(@NotNull String serverName, @NotNull String worldName, double x, double y, double z, float yaw, float pitch) { + this.serverName = serverName; + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + public ServiceLocation(@NotNull JsonObject object) { + serverName = object.get("serverName").getAsString(); + worldName = object.get("worldName").getAsString(); + + x = object.get("x").getAsDouble(); + y = object.get("y").getAsDouble(); + z = object.get("z").getAsDouble(); + + yaw = object.get("yaw").getAsFloat(); + pitch = object.get("pitch").getAsFloat(); + } + + @NotNull + public JsonObject saveToJson() { + JsonObject object = new JsonObject(); + object.addProperty("serverName", serverName); + object.addProperty("worldName", worldName); + + object.addProperty("x", x); + object.addProperty("y", y); + object.addProperty("z", z); + + object.addProperty("yaw", yaw); + object.addProperty("pitch", pitch); + return object; + } + + @NotNull + public String getServerName() { + return serverName; + } + + public void setServerName(@NotNull String serverName) { + this.serverName = serverName; + } + + @NotNull + public String getWorldName() { + return worldName; + } + + public void setWorldName(@NotNull String worldName) { + this.worldName = worldName; + } + + public double getX() { + return x; + } + + public void setX(double x) { + this.x = x; + } + + public int getBlockX() { + return (int) x; + } + + public int getBlockY() { + return (int) y; + } + + public int getBlockZ() { + return (int) z; + } + + public double getY() { + return y; + } + + public void setY(double y) { + this.y = y; + } + + public double getZ() { + return z; + } + + public void setZ(double z) { + this.z = z; + } + + public float getYaw() { + return yaw; + } + + public void setYaw(float yaw) { + this.yaw = yaw; + } + + public float getPitch() { + return pitch; + } + + public void setPitch(float pitch) { + this.pitch = pitch; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ServiceLocation that = (ServiceLocation) o; + return Double.compare(that.x, x) == 0 && Double.compare(that.y, y) == 0 && Double.compare(that.z, z) == 0 && Float.compare(that.yaw, yaw) == 0 && Float.compare(that.pitch, pitch) == 0 && serverName.equals(that.serverName) && worldName.equals(that.worldName); + } + + @Override + public int hashCode() { + return Objects.hash(serverName, worldName, x, y, z, yaw, pitch); + } +} diff --git a/src/main/java/cn/hamster3/service/common/data/ServicePlayerInfo.java b/src/main/java/cn/hamster3/service/common/data/ServicePlayerInfo.java new file mode 100644 index 0000000..ed55d50 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/data/ServicePlayerInfo.java @@ -0,0 +1,153 @@ +package cn.hamster3.service.common.data; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +/** + * 玩家信息 + */ +@SuppressWarnings("unused") +public class ServicePlayerInfo { + /** + * 玩家的uuid + */ + private final UUID uuid; + /** + * 玩家的名称 + */ + private final String playerName; + /** + * 玩家所在的 bukkit 服务器名称 + */ + private final String bukkitServer; + /** + * 玩家所在的 代理 服务器名称 + */ + private final String proxyServer; + /** + * 玩家是否在线 + */ + private boolean online; + + public ServicePlayerInfo(@NotNull UUID uuid, @NotNull String playerName, @Nullable String bukkitServer, @Nullable String proxyServer) { + this.uuid = uuid; + this.playerName = playerName; + this.bukkitServer = bukkitServer; + this.proxyServer = proxyServer; + online = true; + } + + public ServicePlayerInfo(@NotNull UUID uuid, @NotNull String playerName, @Nullable String bukkitServer, @Nullable String proxyServer, boolean online) { + this.uuid = uuid; + this.playerName = playerName; + this.bukkitServer = bukkitServer; + this.proxyServer = proxyServer; + this.online = online; + } + + public ServicePlayerInfo(JsonObject object) { + uuid = UUID.fromString(object.get("uuid").getAsString()); + playerName = object.get("playerName").getAsString(); + online = object.get("online").getAsBoolean(); + if (object.has("bukkitServer")) { + JsonElement bukkitServerJson = object.get("bukkitServer"); + if (!bukkitServerJson.isJsonNull()) { + bukkitServer = bukkitServerJson.getAsString(); + } else { + bukkitServer = null; + } + } else { + bukkitServer = null; + } + if (object.has("proxyServer")) { + JsonElement proxyServerJson = object.get("proxyServer"); + if (!proxyServerJson.isJsonNull()) { + proxyServer = proxyServerJson.getAsString(); + } else { + proxyServer = null; + } + } else { + proxyServer = null; + } + } + + public JsonObject saveToJson() { + JsonObject object = new JsonObject(); + object.addProperty("uuid", uuid.toString()); + object.addProperty("playerName", playerName); + object.addProperty("online", online); + object.addProperty("bukkitServer", bukkitServer); + object.addProperty("proxyServer", proxyServer); + return object; + } + + /** + * 获取玩家的UUID + * + * @return 玩家的UUID + */ + @NotNull + public UUID getUuid() { + return uuid; + } + + /** + * 获取玩家的名称 + * + * @return 玩家名称 + */ + @NotNull + public String getPlayerName() { + return playerName; + } + + public boolean isOnline() { + return online; + } + + public void setOnline(boolean online) { + this.online = online; + } + + /** + * 获取玩家所在的子服 + * + * @return 子服名称 + */ + public String getBukkitServer() { + return bukkitServer; + } + + /** + * 获取玩家所在的代理节点 + * + * @return 代理节点名称 + */ + public String getProxyServer() { + return proxyServer; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ServicePlayerInfo that = (ServicePlayerInfo) o; + + return uuid.equals(that.uuid); + } + + @Override + public int hashCode() { + return uuid.hashCode(); + } + + @Override + public String toString() { + return saveToJson().toString(); + } +} diff --git a/src/main/java/cn/hamster3/service/common/entity/ServiceMessageInfo.java b/src/main/java/cn/hamster3/service/common/entity/ServiceMessageInfo.java new file mode 100644 index 0000000..4f5cfec --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/entity/ServiceMessageInfo.java @@ -0,0 +1,202 @@ +package cn.hamster3.service.common.entity; + +import cn.hamster3.mc.plugin.core.common.api.CoreAPI; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * 消息内容 + */ +@SuppressWarnings("unused") +public class ServiceMessageInfo { + /** + * 消息发送者 + */ + private final ServiceSenderInfo senderInfo; + /** + * 接受该消息的目标服务器 + *

+ * 一旦设定该值,则此条消息将会由 HamsterService-Server 过滤 + *

+ * 仅服务器名称匹配的子端才能接收到这条消息 + *

+ * 若不设定(值为null),则该消息会广播给所有子端 + */ + private final String toServer; + /** + * 消息标签 + *

+ * 一般用这个来判断消息由哪个插件发出 + */ + private String tag; + /** + * 消息动作 + *

+ * 一般用这个来判断插件应该如何处理这条消息 + */ + private String action; + /** + * 消息内容 + *

+ * 这里是消息的附加参数 + */ + private JsonElement content; + + public ServiceMessageInfo(@NotNull ServiceSenderInfo senderInfo, @NotNull String tag, @NotNull String action) { + this(senderInfo, tag, action, null); + } + + public ServiceMessageInfo(@NotNull ServiceSenderInfo senderInfo, @NotNull String tag, @NotNull String action, @Nullable JsonElement content) { + this(senderInfo, null, tag, action, content); + } + + public ServiceMessageInfo(@NotNull ServiceSenderInfo senderInfo, @Nullable String toServer, @NotNull String tag, @NotNull String action, @Nullable JsonElement content) { + this.senderInfo = senderInfo; + this.toServer = toServer; + this.tag = tag; + this.action = action; + this.content = content; + } + + public ServiceMessageInfo(@NotNull JsonObject object) { + senderInfo = new ServiceSenderInfo(object.getAsJsonObject("senderInfo")); + if (object.has("toServer")) { + toServer = object.get("toServer").getAsString(); + } else { + toServer = null; + } + tag = object.get("tag").getAsString(); + action = object.get("action").getAsString(); + content = object.get("content"); + } + + /** + * 序列化至Json + * + * @return json对象 + */ + @NotNull + public JsonObject saveToJson() { + JsonObject object = new JsonObject(); + object.add("senderInfo", senderInfo.saveToJson()); + if (toServer != null) { + object.addProperty("toServer", toServer); + } + object.addProperty("tag", tag); + object.addProperty("action", action); + object.add("content", content); + return object; + } + + /** + * 获取消息发送者 + * + * @return 发送者 + */ + @NotNull + public ServiceSenderInfo getSenderInfo() { + return senderInfo; + } + + /** + * 获取定向发送的接受者 + *

+ * 如果返回为 null 则代表广播消息 + * + * @return 定向发送的接受者 + */ + public String getToServer() { + return toServer; + } + + /** + * 获取消息标签 + * + * @return 消息标签 + */ + @NotNull + public String getTag() { + return tag; + } + + /** + * 设置消息标签 + * + * @param tag 消息标签 + */ + public void setTag(@NotNull String tag) { + this.tag = tag; + } + + /** + * 获取消息动作 + * + * @return 消息动作 + */ + @NotNull + public String getAction() { + return action; + } + + /** + * 设置消息动作 + * + * @param action 消息动作 + */ + public void setAction(@NotNull String action) { + this.action = action; + } + + /** + * 获取消息内容 + * + * @return 消息内容 + */ + public JsonElement getContent() { + return content; + } + + /** + * 设置消息内容 + * + * @param content 消息内容 + */ + public void setContent(@Nullable JsonElement content) { + this.content = content; + } + + /** + * 以字符串形式获取消息内容 + * + * @return 消息内容 + */ + public String getContentAsString() { + return content.getAsString(); + } + + /** + * 以 JsonObject 对象获取消息内容 + * + * @return 消息内容 + */ + public JsonObject getContentAsJsonObject() { + return content.getAsJsonObject(); + } + + /** + * 以 JsonArray 对象获取消息内容 + * + * @return 消息内容 + */ + public JsonArray getContentAsJsonArray() { + return content.getAsJsonArray(); + } + + @Override + public String toString() { + return CoreAPI.getInstance().getGson().toJson(this); + } +} diff --git a/src/main/java/cn/hamster3/service/common/entity/ServiceSenderInfo.java b/src/main/java/cn/hamster3/service/common/entity/ServiceSenderInfo.java new file mode 100644 index 0000000..045f89f --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/entity/ServiceSenderInfo.java @@ -0,0 +1,82 @@ +package cn.hamster3.service.common.entity; + +import com.google.gson.JsonObject; +import org.jetbrains.annotations.NotNull; + +/** + * 消息发送者信息 + */ +@SuppressWarnings("unused") +public class ServiceSenderInfo { + private final ServiceSenderType type; + private final String name; + private final String nickName; + + /** + * 缓存用的 jsonInfo + */ + private JsonObject jsonInfo; + + public ServiceSenderInfo(@NotNull ServiceSenderType type, @NotNull String name, @NotNull String nickName) { + this.type = type; + this.name = name; + this.nickName = nickName; + } + + public ServiceSenderInfo(@NotNull JsonObject object) { + type = ServiceSenderType.valueOf(object.get("type").getAsString()); + name = object.get("name").getAsString(); + nickName = object.get("nickName").getAsString(); + } + + /** + * 序列化至Json + * + * @return json对象 + */ + @NotNull + public JsonObject saveToJson() { + if (jsonInfo == null) { + jsonInfo = new JsonObject(); + jsonInfo.addProperty("type", type.name()); + jsonInfo.addProperty("name", name); + jsonInfo.addProperty("nickName", nickName); + } + return jsonInfo; + } + + @NotNull + public ServiceSenderType getType() { + return type; + } + + @NotNull + public String getName() { + return name; + } + + @NotNull + public String getNickName() { + return nickName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ServiceSenderInfo that = (ServiceSenderInfo) o; + + return name.equals(that.name); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public String toString() { + return saveToJson().toString(); + } +} diff --git a/src/main/java/cn/hamster3/service/common/entity/ServiceSenderType.java b/src/main/java/cn/hamster3/service/common/entity/ServiceSenderType.java new file mode 100644 index 0000000..ba9f9e9 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/entity/ServiceSenderType.java @@ -0,0 +1,20 @@ +package cn.hamster3.service.common.entity; + +/** + * 消息发送者类型 + */ +@SuppressWarnings("unused") +public enum ServiceSenderType { + /** + * Bukkit服务器 + */ + BUKKIT, + /** + * BungeeCord 等代理服务器 + */ + PROXY, + /** + * 消息中心服务器(名称为:ServiceCentre) + */ + SERVICE_CENTRE +} diff --git a/src/main/java/cn/hamster3/service/common/util/ComponentUtils.java b/src/main/java/cn/hamster3/service/common/util/ComponentUtils.java new file mode 100644 index 0000000..5c2fa84 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/util/ComponentUtils.java @@ -0,0 +1,106 @@ +package cn.hamster3.service.common.util; + +import com.google.gson.*; +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; + +import java.util.ArrayList; +import java.util.Collections; + +public class ComponentUtils { + private static final Gson gson = new GsonBuilder() + .setLenient()// json宽松 + .enableComplexMapKeySerialization()//支持Map的key为复杂对象的形式 + .serializeNulls() //智能null + .setPrettyPrinting()// 调教格式 + .create(); + + private ComponentUtils() { + } + + public static BaseComponent[] parseComponentFromJson(JsonElement json) { + if (json.isJsonPrimitive()) { + return new ComponentBuilder(json.getAsString()).create(); + } + if (json.isJsonArray()) { + JsonArray array = json.getAsJsonArray(); + ArrayList list = new ArrayList<>(); + for (JsonElement element : array) { + Collections.addAll(list, parseComponentFromJson(element)); + } + BaseComponent[] components = new BaseComponent[list.size()]; + for (int i = 0; i < list.size(); i++) { + components[i] = list.get(i); + } + return components; + } + if (json.isJsonObject()) { + JsonObject object = json.getAsJsonObject(); + ComponentBuilder builder = new ComponentBuilder(object.get("text").getAsString()); + if (object.has("color")) { + builder.color(ChatColor.of(object.get("color").getAsString())); + } + if (object.has("bold")) { + builder.bold(object.get("bold").getAsBoolean()); + } + if (object.has("italic")) { + builder.italic(object.get("italic").getAsBoolean()); + } + if (object.has("underlined")) { + builder.underlined(object.get("underlined").getAsBoolean()); + } + if (object.has("strikethrough")) { + builder.strikethrough(object.get("strikethrough").getAsBoolean()); + } + if (object.has("obfuscated")) { + builder.obfuscated(object.get("obfuscated").getAsBoolean()); + } + if (object.has("insertion")) { + builder.insertion(object.get("insertion").getAsString()); + } + if (object.has("clickEvent")) { + builder.event(parseClickEvent(object.getAsJsonObject("clickEvent"))); + } + if (object.has("hoverEvent")) { + builder.event(parseHoverEvent(object.getAsJsonObject("hoverEvent"))); + } + if (object.has("extra")) { + builder.append(parseComponentFromJson(object.get("extra"))); + } + return builder.create(); + } + throw new IllegalArgumentException("非法json字符串: " + json); + } + + private static ClickEvent parseClickEvent(JsonObject object) { + return new ClickEvent( + ClickEvent.Action.valueOf( + object + .get("action") + .getAsString() + .toUpperCase() + ), + object.get("value").getAsString() + ); + } + + @SuppressWarnings("deprecation") + private static HoverEvent parseHoverEvent(JsonObject object) { + return new HoverEvent( + HoverEvent.Action.valueOf( + object + .get("action") + .getAsString() + .toUpperCase() + ), + parseComponentFromJson(object.get("value")) + ); + } + + public static Gson getGson() { + return gson; + } +} diff --git a/src/main/java/cn/hamster3/service/common/util/ServiceLogUtils.java b/src/main/java/cn/hamster3/service/common/util/ServiceLogUtils.java new file mode 100644 index 0000000..bc33898 --- /dev/null +++ b/src/main/java/cn/hamster3/service/common/util/ServiceLogUtils.java @@ -0,0 +1,38 @@ +package cn.hamster3.service.common.util; + +import java.util.logging.Logger; + +@SuppressWarnings({"unused", "CallToPrintStackTrace"}) +public abstract class ServiceLogUtils { + private static Logger logger; + + public static void setLogger(Logger logger) { + ServiceLogUtils.logger = logger; + } + + public static void info(String info) { + logger.info(info); + } + + public static void info(String info, Object... params) { + logger.info(String.format(info, params)); + } + + public static void warning(String warning) { + logger.warning(warning); + } + + public static void warning(String warning, Object... params) { + logger.warning(String.format(warning, params)); + } + + public static void error(Throwable e, String message) { + warning(message); + e.printStackTrace(); + } + + public static void error(Throwable e, String message, Object... args) { + warning(message, args); + e.printStackTrace(); + } +} diff --git a/src/main/resources/bungee.yml b/src/main/resources/bungee.yml new file mode 100644 index 0000000..2600004 --- /dev/null +++ b/src/main/resources/bungee.yml @@ -0,0 +1,8 @@ +name: HamsterService-Proxy +main: cn.hamster3.service.bungee.BallBridgePlugin +version: ${version} + +author: MiniDay + +depends: + - HamsterBall diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..5defb9a --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,23 @@ +name: HamsterService-Bukkit +main: cn.hamster3.service.bukkit.BallBridgePlugin +version: ${version} +api-version: 1.13 + +author: MiniDay +website: https://github.com/MiniDay/hamster-little-plugins +description: 将 HamsterBall 转换成 HamsterService 兼容的 API + +depend: + - HamsterCore + - HamsterBall + +softdepend: + - PlaceholderAPI + +commands: + hamster-service: + aliases: [ hservice, service ] + +permissions: + hamster.service.admin: + default: op