feat: 完成插件

This commit is contained in:
2024-02-26 00:47:53 +08:00
commit 015a662036
18 changed files with 1002 additions and 0 deletions

43
.gitignore vendored Normal file
View File

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

54
build.gradle.kts Normal file
View File

@@ -0,0 +1,54 @@
@file:Suppress("VulnerableLibrariesLocal")
plugins {
id("java")
}
group = "cn.hamster3.mc.plugin"
version = "1.1.1"
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")
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly("org.projectlombok:lombok:1.18.30")
annotationProcessor("org.projectlombok:lombok:1.18.30")
compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
compileOnly("cn.hamster3.mc.plugin:core-bukkit:1.2.2")
compileOnly("cn.hamster3.mc.plugin:ball-bukkit:1.5.3")
}
tasks {
withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
}
withType<Jar>().configureEach {
from(rootProject.file("LICENSE"))
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withSourcesJar()
}
jar {
archiveBaseName = "HamsterTPA"
destinationDirectory = rootProject.layout.buildDirectory
}
processResources {
filesMatching("plugin.yml") {
expand(project.properties)
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Mon Feb 26 00:30:39 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

234
gradlew vendored Normal file
View File

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

89
gradlew.bat vendored Normal file
View File

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

2
settings.gradle.kts Normal file
View File

@@ -0,0 +1,2 @@
rootProject.name = "hamster-tpa"

View File

@@ -0,0 +1,33 @@
package cn.hamster3.mc.plugin.tpa;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.tpa.command.TPACommand;
import cn.hamster3.mc.plugin.tpa.command.TPAcceptCommand;
import cn.hamster3.mc.plugin.tpa.command.TPDenyCommand;
import cn.hamster3.mc.plugin.tpa.config.ConfigManager;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import cn.hamster3.mc.plugin.tpa.listener.MainListener;
import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
public class HamsterTPAPlugin extends JavaPlugin {
public static final String BALL_CHANNEL = "HamsterTPA";
@Getter
private static HamsterTPAPlugin instance;
@Override
public void onLoad() {
instance = this;
ConfigManager.init();
DataManager.init();
}
@Override
public void onEnable() {
TPACommand.INSTANCE.register();
TPAcceptCommand.INSTANCE.register();
TPDenyCommand.INSTANCE.register();
BallAPI.getInstance().getEventBus().register(MainListener.INSTANCE);
BallAPI.getInstance().subscribe(BALL_CHANNEL);
}
}

View File

@@ -0,0 +1,106 @@
package cn.hamster3.mc.plugin.tpa.command;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ParentCommand;
import cn.hamster3.mc.plugin.core.bukkit.constant.CoreMessage;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.TextReplacementConfig;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import cn.hamster3.mc.plugin.tpa.config.ConfigManager;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import cn.hamster3.mc.plugin.tpa.core.Message;
import cn.hamster3.mc.plugin.tpa.thread.TimeoutThread;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public final class TPACommand extends ParentCommand {
public static final TPACommand INSTANCE = new TPACommand();
private TPACommand() {
}
@Override
public @NotNull String getName() {
return "hamster-tpa";
}
@Override
public @NotNull JavaPlugin getPlugin() {
return HamsterTPAPlugin.getInstance();
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!(sender instanceof Player)) {
CoreMessage.COMMAND_MUST_USED_BY_PLAYER.show(sender);
return true;
}
Player player = (Player) sender;
UUID uuid = player.getUniqueId();
if (args.length < 1) {
Message.TPA_NOT_INPUT_PLAYER_NAME.show(sender);
return true;
}
long now = System.currentTimeMillis();
long cdTime = DataManager.getPlayerUseTime(uuid) + ConfigManager.getTpaCD();
if (cdTime >= now) {
Message.TPA_IN_CD.show(player, TextReplacementConfig.builder()
.matchLiteral("%cd_time%")
.replacement(String.valueOf((cdTime - now) / 1000))
.build());
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
Message.TPA_TARGET_PLAYER_NOT_ONLINE.show(player);
return true;
}
if (!playerInfo.isOnline()) {
Message.TPA_TARGET_PLAYER_NOT_ONLINE.show(player);
return true;
}
DataManager.setPlayerUseTime(uuid, now, true);
DataManager.sendTPA(uuid, playerInfo.getUuid(), now, true);
Message.TPA_SEND_SUCCESS.show(sender, TextReplacementConfig.builder()
.matchLiteral("%player_name%")
.replacement(playerInfo.getName())
.build());
BallAPI.getInstance().sendMessageToPlayer(
playerInfo.getUuid(),
Message.TPA_RECEIVED.getMessage().replace(TextReplacementConfig.builder()
.matchLiteral("%player_name%")
.replacement(player.getName())
.build()),
false);
CoreAPI.getInstance().getScheduledService().schedule(
new TimeoutThread(uuid, playerInfo.getUuid()),
ConfigManager.getTimeout(),
TimeUnit.MILLISECONDS
);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
if (args.length == 1) {
String lowerCase = args[0].toLowerCase();
return BallAPI.getInstance().getAllPlayerInfo().values()
.stream()
.filter(BallPlayerInfo::isOnline)
.map(BallPlayerInfo::getName)
.filter(name -> name.toLowerCase().startsWith(lowerCase))
.collect(Collectors.toList());
}
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,67 @@
package cn.hamster3.mc.plugin.tpa.command;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.core.bukkit.command.ParentCommand;
import cn.hamster3.mc.plugin.core.bukkit.constant.CoreMessage;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import cn.hamster3.mc.plugin.tpa.config.ConfigManager;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import cn.hamster3.mc.plugin.tpa.core.Message;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public final class TPAcceptCommand extends ParentCommand {
public static final TPAcceptCommand INSTANCE = new TPAcceptCommand();
private TPAcceptCommand() {
}
@Override
public @NotNull String getName() {
return "hamster-tpaccept";
}
@Override
public @NotNull JavaPlugin getPlugin() {
return HamsterTPAPlugin.getInstance();
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!(sender instanceof Player)) {
CoreMessage.COMMAND_MUST_USED_BY_PLAYER.show(sender);
return true;
}
Player player = (Player) sender;
UUID uuid = player.getUniqueId();
long now = System.currentTimeMillis();
List<UUID> list = DataManager.getPlayerReceivedTpa(uuid).entrySet()
.stream()
.filter(o -> o.getValue() + ConfigManager.getTimeout() >= now)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (list.isEmpty()) {
Message.RECEIVED_TPA_LIST_IS_EMPTY.show(sender);
return true;
}
BallAPI.getInstance().sendPlayerToPlayer(list, uuid,
Message.TPA_SUCCESS.getMessage(),
Message.TPA_ACCEPT_SUCCESS.getMessage());
DataManager.clearTPAList(uuid, true);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,75 @@
package cn.hamster3.mc.plugin.tpa.command;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.core.bukkit.command.ParentCommand;
import cn.hamster3.mc.plugin.core.bukkit.constant.CoreMessage;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.TextReplacementConfig;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import cn.hamster3.mc.plugin.tpa.config.ConfigManager;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import cn.hamster3.mc.plugin.tpa.core.Message;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public final class TPDenyCommand extends ParentCommand {
public static final TPDenyCommand INSTANCE = new TPDenyCommand();
private TPDenyCommand() {
}
@Override
public @NotNull String getName() {
return "hamster-tpdeny";
}
@Override
public @NotNull JavaPlugin getPlugin() {
return HamsterTPAPlugin.getInstance();
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!(sender instanceof Player)) {
CoreMessage.COMMAND_MUST_USED_BY_PLAYER.show(sender);
return true;
}
Player player = (Player) sender;
UUID uuid = player.getUniqueId();
long now = System.currentTimeMillis();
List<UUID> list = DataManager.getPlayerReceivedTpa(uuid).entrySet()
.stream()
.filter(o -> o.getValue() + ConfigManager.getTimeout() >= now)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (list.isEmpty()) {
Message.RECEIVED_TPA_LIST_IS_EMPTY.show(sender);
return true;
}
for (UUID requireUUID : list) {
DataManager.setPlayerUseTime(requireUUID, 0, true);
BallAPI.getInstance().sendMessageToPlayer(requireUUID,
Message.TPA_DENIED.getMessage().replace(TextReplacementConfig.builder()
.matchLiteral("%player_name%")
.replacement(player.getName())
.build()),
false);
}
DataManager.clearTPAList(uuid, true);
Message.TPA_DENY_SUCCESS.show(player);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,29 @@
package cn.hamster3.mc.plugin.tpa.config;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import cn.hamster3.mc.plugin.tpa.core.Message;
import lombok.Getter;
import org.bukkit.configuration.file.FileConfiguration;
public final class ConfigManager {
@Getter
private static long tpaCD;
@Getter
private static long timeout;
private ConfigManager() {
}
public static void init() {
HamsterTPAPlugin plugin = HamsterTPAPlugin.getInstance();
plugin.saveDefaultConfig();
plugin.reloadConfig();
FileConfiguration pluginConfig = plugin.getConfig();
tpaCD = pluginConfig.getLong("tpa-cd") * 1000L;
timeout = pluginConfig.getLong("timeout") * 1000L;
Message.init(plugin);
}
}

View File

@@ -0,0 +1,57 @@
package cn.hamster3.mc.plugin.tpa.core;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import com.google.gson.JsonObject;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class DataManager {
private static Map<UUID, Long> PLAYER_USE_TIME;
private static Map<UUID, Map<UUID, Long>> PLAYER_RECEIVED_TPA;
public static void init() {
PLAYER_USE_TIME = new HashMap<>();
PLAYER_RECEIVED_TPA = new HashMap<>();
}
public static void setPlayerUseTime(@NotNull UUID uuid, long time, boolean broadcast) {
PLAYER_USE_TIME.put(uuid, time);
if (broadcast) {
JsonObject object = new JsonObject();
object.addProperty("uuid", uuid.toString());
object.addProperty("time", time);
BallAPI.getInstance().sendBallMessage(HamsterTPAPlugin.BALL_CHANNEL, "setPlayerUseTime", object);
}
}
public static void sendTPA(@NotNull UUID sender, @NotNull UUID target, long time, boolean broadcast) {
Map<UUID, Long> map = PLAYER_RECEIVED_TPA.computeIfAbsent(target, o -> new HashMap<>());
map.put(sender, time);
if (broadcast) {
JsonObject object = new JsonObject();
object.addProperty("sender", sender.toString());
object.addProperty("target", target.toString());
object.addProperty("time", time);
BallAPI.getInstance().sendBallMessage(HamsterTPAPlugin.BALL_CHANNEL, "sendTPA", object);
}
}
public static void clearTPAList(@NotNull UUID uuid, boolean broadcast) {
PLAYER_RECEIVED_TPA.remove(uuid);
if (broadcast) {
BallAPI.getInstance().sendBallMessage(HamsterTPAPlugin.BALL_CHANNEL, "clearTPAList", uuid.toString());
}
}
public static long getPlayerUseTime(@NotNull UUID uuid) {
return PLAYER_USE_TIME.getOrDefault(uuid, 0L);
}
public static Map<UUID, Long> getPlayerReceivedTpa(@NotNull UUID uuid) {
return PLAYER_RECEIVED_TPA.computeIfAbsent(uuid, o -> new HashMap<>());
}
}

View File

@@ -0,0 +1,82 @@
package cn.hamster3.mc.plugin.tpa.core;
import cn.hamster3.mc.plugin.core.bukkit.api.CoreBukkitAPI;
import cn.hamster3.mc.plugin.core.bukkit.util.CoreBukkitUtils;
import cn.hamster3.mc.plugin.core.common.data.DisplayMessage;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.audience.Audience;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.TextReplacementConfig;
import lombok.Getter;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
@Getter
public enum Message {
TPA_IN_CD("§a传送正在冷却中时间%cd_time% 秒"),
TPA_NOT_INPUT_PLAYER_NAME("§c请输入要传送的玩家名称"),
TPA_TARGET_PLAYER_NOT_ONLINE("§c该玩家不在线"),
TPA_SEND_SUCCESS("§a已向玩家 %player_name% 发出传送申请"),
RECEIVED_TPA_LIST_IS_EMPTY("§a你没有收到任何传送请求"),
TPA_RECEIVED("§a收到了来自 %player_name% 的传送申请\n §a请输入 §e§l/tpaccept §a同意请求\n §a或使用 §c§l/tpdeny §a拒绝请求"),
TPA_SUCCESS("§a已成功传送至玩家 %player_name%"),
TPA_ACCEPT_SUCCESS("§a已成功接受玩家 %player_name% 的传送请求"),
TPA_DENIED("§a玩家 %player_name% 拒绝了你的传送请求,冷却时间已返还"),
TPA_DENY_SUCCESS("§a已拒绝玩家 %player_name% 的传送请求"),
SEND_TPA_TIMEOUT("§a玩家 %player_name% 未能及时处理你的传送请求,冷却时间已返还"),
RECEIVED_TPA_TIMEOUT("§a你未能及时处理 %player_name% 的传送请求");
@NotNull
private DisplayMessage message;
Message(@NotNull String message) {
this.message = new DisplayMessage().setMessage(message);
}
@SuppressWarnings("CallToPrintStackTrace")
public static void init(@NotNull Plugin plugin) {
File dataFolder = plugin.getDataFolder();
if (dataFolder.mkdirs()) {
plugin.getLogger().info("已生成插件存档文件夹 " + dataFolder.getName());
}
File file = new File(dataFolder, "messages.yml");
YamlConfiguration config = new YamlConfiguration();
if (file.exists()) {
try {
config.load(file);
} catch (Exception e) {
plugin.getLogger().warning("加载消息配置文件时出现了一个异常:");
e.printStackTrace();
}
}
for (Message value : values()) {
ConfigurationSection section = config.getConfigurationSection(value.name());
if (section == null) {
plugin.getLogger().info("生成消息设置: " + value.name());
config.set(value.name(), CoreBukkitUtils.saveDisplayMessage(value.message));
continue;
}
try {
value.message = CoreBukkitUtils.loadDisplayMessage(section);
} catch (Exception e) {
plugin.getLogger().warning("加载消息设置 " + value.name() + " 时遇到了一个异常: ");
e.printStackTrace();
}
}
try {
config.save(file);
} catch (IOException e) {
plugin.getLogger().warning("保存消息配置文件时出现了一个异常:");
e.printStackTrace();
}
}
public void show(CommandSender sender, TextReplacementConfig... replacement) {
Audience audience = CoreBukkitAPI.getInstance().getAudienceProvider().sender(sender);
message.show(audience, replacement);
}
}

View File

@@ -0,0 +1,52 @@
package cn.hamster3.mc.plugin.tpa.listener;
import cn.hamster3.mc.plugin.ball.common.event.message.MessageReceivedEvent;
import cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import com.google.common.eventbus.Subscribe;
import com.google.gson.JsonObject;
import org.bukkit.event.Listener;
import java.util.UUID;
public final class MainListener implements Listener {
public static final MainListener INSTANCE = new MainListener();
private MainListener() {
}
@Subscribe
public void onMessageReceived(MessageReceivedEvent event) {
if (!HamsterTPAPlugin.BALL_CHANNEL.equals(event.getChannel())) {
return;
}
switch (event.getAction()) {
case "setPlayerUseTime": {
JsonObject object = event.getContentAsJsonObject();
DataManager.setPlayerUseTime(
UUID.fromString(object.get("uuid").getAsString()),
object.get("time").getAsLong(),
false
);
break;
}
case "sendTPA": {
JsonObject object = event.getContentAsJsonObject();
DataManager.sendTPA(
UUID.fromString(object.get("sender").getAsString()),
UUID.fromString(object.get("target").getAsString()),
object.get("time").getAsLong(),
false
);
break;
}
case "clearTPAList": {
DataManager.clearTPAList(event.getContentAsUUID(), false);
break;
}
case "": {
break;
}
}
}
}

View File

@@ -0,0 +1,41 @@
package cn.hamster3.mc.plugin.tpa.thread;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.TextReplacementConfig;
import cn.hamster3.mc.plugin.tpa.core.DataManager;
import cn.hamster3.mc.plugin.tpa.core.Message;
import java.util.Map;
import java.util.UUID;
public class TimeoutThread implements Runnable {
private final UUID sender;
private final UUID target;
public TimeoutThread(UUID sender, UUID target) {
this.sender = sender;
this.target = target;
}
@Override
public void run() {
Map<UUID, Long> map = DataManager.getPlayerReceivedTpa(target);
if (map.containsKey(sender)) {
BallAPI.getInstance().sendMessageToPlayer(sender,
Message.SEND_TPA_TIMEOUT.getMessage().replace(
TextReplacementConfig.builder()
.matchLiteral("%player_name%")
.replacement(BallAPI.getInstance().getPlayerName(target, ""))
.build()),
false);
BallAPI.getInstance().sendMessageToPlayer(target,
Message.RECEIVED_TPA_TIMEOUT.getMessage().replace(
TextReplacementConfig.builder()
.matchLiteral("%player_name%")
.replacement(BallAPI.getInstance().getPlayerName(sender, ""))
.build()),
false);
DataManager.setPlayerUseTime(sender, 0, true);
}
}
}

View File

@@ -0,0 +1,7 @@
# 使用 TPA 传送的冷却时间
# 以秒为单位
tpa-cd: 300
# 传送请求超时的时间
# 以秒为单位
timeout: 30

View File

@@ -0,0 +1,25 @@
name: HamsterTPA
main: cn.hamster3.mc.plugin.tpa.HamsterTPAPlugin
version: ${version}
api-version: 1.13
author: MiniDay
website: https://github.com/MiniDay/hamster-little-plugins
description: TPA 功能
depend:
- HamsterCore
- HamsterBall
commands:
hamster-tpa:
aliases: [ tpa ]
hamster-tpaccept:
aliases: [ tpaccept ]
hamster-tpdeny:
aliases: [ tpdeny ]
permissions:
hamster.tpa.use:
default: true
description: 允许使用 HamsterTPA 的权限