Compare commits

..
18 Commits
21 changed files with 327 additions and 387 deletions
+2
View File
@@ -39,3 +39,5 @@ hs_err_pid*
.gradle .gradle
build/ build/
!gradle/wrapper/gradle-wrapper.jar !gradle/wrapper/gradle-wrapper.jar
*.bat
Vendored
+7 -1
View File
@@ -3,7 +3,13 @@ pipeline {
stages { stages {
stage('Gradle') { stage('Gradle') {
steps { steps {
sh './gradlew build' withCredentials([usernamePassword(credentialsId: 'alttd-snapshot-user', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
sh '''
set +x
chmod +x gradlew
./gradlew build -PalttdSnapshotUsername=$USERNAME -PalttdSnapshotPassword=$PASSWORD
'''
}
} }
} }
stage('Archive') { stage('Archive') {
+67 -25
View File
@@ -1,21 +1,16 @@
import java.io.ByteArrayOutputStream import net.minecrell.pluginyml.bukkit.BukkitPluginDescription
import net.minecrell.pluginyml.paper.PaperPluginDescription
plugins { plugins {
id("java") id("java")
id("com.github.johnrengelman.shadow") version "7.1.0" id("de.eldoria.plugin-yml.paper") version "0.9.0"
} }
group = "com.alttd" group = "com.alttd.afkdectector"
version = System.getenv("BUILD_NUMBER") ?: gitCommit() version = System.getenv("BUILD_NUMBER") ?: gitCommit()
description = "Altitude AFK Detector plugin." description = "Altitude AFK Detector plugin."
apply<JavaLibraryPlugin>() apply<JavaLibraryPlugin>()
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
tasks { tasks {
withType<JavaCompile> { withType<JavaCompile> {
options.encoding = Charsets.UTF_8.name() options.encoding = Charsets.UTF_8.name()
@@ -28,32 +23,79 @@ tasks {
jar { jar {
archiveFileName.set("${rootProject.name}.jar") archiveFileName.set("${rootProject.name}.jar")
} }
processResources {
filteringCharset = Charsets.UTF_8.name()
duplicatesStrategy = DuplicatesStrategy.INCLUDE
filesMatching("plugin.yml") {
expand(Pair("projectVersion", project.version))
}
}
} }
dependencies { dependencies {
compileOnly("com.alttd.cosmos:cosmos-api:1.21.6-R0.1-SNAPSHOT") { compileOnly("com.alttd.cosmos:cosmos-api:26.2.build.17-stable") {
isChanging = true isChanging = true
} }
compileOnly("de.keyle:mypet:3.11-SNAPSHOT") compileOnly("de.keyle:mypet-api:4.0.0-SNAPSHOT")
compileOnly("com.alttd:VillagerShopUI:1.1-SNAPSHOT") { compileOnly("com.alttd:VillagerShopUI:1.1-SNAPSHOT") {
isChanging = true isChanging = true
} }
} }
fun gitCommit(): String { fun gitCommit(): String {
val os = ByteArrayOutputStream() return "FIXME"
project.exec { }
isIgnoreExitValue = true
commandLine = "git rev-parse --short HEAD".split(" ") paper {
standardOutput = os name = rootProject.name
main = "$group.${rootProject.name}"
description = rootProject.description
bootstrapper = "$group.${rootProject.name}Bootstrap"
version = "${rootProject.version}"
apiVersion = "26.2"
authors = listOf("destro174")
serverDependencies {
register("MyPet") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
}
permissions {
register("afkdetector.admin") {
description = "Admin permission for the ${rootProject.name} plugin."
default = BukkitPluginDescription.Permission.Default.FALSE
children = listOf(
"afkdetector.bypass",
"afkdetector.afklist",
"afkdetector.afkcheck",
"afkdetector.notify",
"afkdetector.reload"
)
}
register("afkdetector.bypass") {
description = "Bypass permission for the ${rootProject.name} plugin."
default = BukkitPluginDescription.Permission.Default.FALSE
children = listOf(
"afkdetector.kickexempt"
)
}
register("afkdetector.reload") {
description = "Allows reloading the ${rootProject.name} plugin."
default = BukkitPluginDescription.Permission.Default.FALSE
}
register("afkdetector.kickexempt") {
description = "Bypass permission for being afk kicked."
default = BukkitPluginDescription.Permission.Default.FALSE
}
register("afkdetector.afktime") {
description = "Master permission for custom afk time in the ${rootProject.name} plugin."
default = BukkitPluginDescription.Permission.Default.FALSE
}
register("afkdetector.afkcheck") {
description = "Allows usage of the /afkcheck command."
default = BukkitPluginDescription.Permission.Default.FALSE
}
register("afkdetector.afklist") {
description = "Allows usage of the /afklist command."
default = BukkitPluginDescription.Permission.Default.FALSE
}
register("afkdetector.notify") {
description = "Get notified when a player is afk."
default = BukkitPluginDescription.Permission.Default.FALSE
}
} }
return String(os.toByteArray()).trim()
} }
Binary file not shown.
+3 -1
View File
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+26 -18
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015-2021 the original authors. # Copyright © 2015 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (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 # https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +82,11 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -133,22 +132,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java 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. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -165,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -193,16 +198,19 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
# shell script including quotes and variable substitutions, so put them in DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded. # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.
Vendored
+14 -12
View File
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@@ -26,6 +28,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -42,11 +45,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -56,22 +59,21 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
+18 -7
View File
@@ -1,20 +1,31 @@
import org.gradle.kotlin.dsl.maven
rootProject.name = "AFKDetector" rootProject.name = "AFKDetector"
val nexusUser = providers.gradleProperty("alttdSnapshotUsername").orNull ?: System.getenv("NEXUS_USERNAME")
val nexusPass = providers.gradleProperty("alttdSnapshotPassword").orNull ?: System.getenv("NEXUS_PASSWORD")
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
mavenLocal()
mavenCentral() mavenCentral()
maven("https://repo.destro.xyz/snapshots") // Altitude - Galaxy
maven("https://repo.alttd.com/repository/alttd-snapshot/")
maven { maven {
name = "nexus"
url = uri("https://repo.alttd.com/repository/alttd-snapshot/") url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials { credentials {
username = providers.gradleProperty("alttdSnapshotUsername").get() username = nexusUser
password = providers.gradleProperty("alttdSnapshotPassword").get() password = nexusPass
} }
} }
maven {
url = uri("https://repo.alttd.com/repository/alttd/")
credentials {
username = nexusUser
password = nexusPass
}
}
maven("https://repo.papermc.io/repository/maven-public/")
maven {
name = "userderezzedRepoSnapshots"
url = uri("https://repo.userderezzed.dev/snapshots")
}
} }
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
} }
@@ -4,12 +4,16 @@ import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.command.AFKCheckCommand; import com.alttd.afkdectector.command.AFKCheckCommand;
import com.alttd.afkdectector.command.AFKListCommand; import com.alttd.afkdectector.command.AFKListCommand;
import com.alttd.afkdectector.command.ReloadCommand; import com.alttd.afkdectector.command.ReloadCommand;
import com.alttd.afkdectector.command.RelogCheckCommand;
import com.alttd.afkdectector.config.Config; import com.alttd.afkdectector.config.Config;
import com.alttd.afkdectector.config.Messages; import com.alttd.afkdectector.config.Messages;
import com.alttd.afkdectector.config.MessagesConfig; import com.alttd.afkdectector.config.MessagesConfig;
import com.alttd.afkdectector.trackers.AutoJoinTracker; import com.alttd.afkdectector.trackers.AutoJoinTracker;
import com.alttd.afkdectector.trackers.SuspiciousKickTracker; import com.alttd.afkdectector.trackers.SuspiciousKickTracker;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.event.player.AsyncChatEvent; import io.papermc.paper.event.player.AsyncChatEvent;
import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
@@ -24,10 +28,12 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -52,12 +58,11 @@ public class AFKDetector extends JavaPlugin implements Listener {
miniMessage = MiniMessage.miniMessage(); miniMessage = MiniMessage.miniMessage();
loadConfig(null); loadConfig(null);
getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(this, this);
//getCommand("afk").setExecutor(new AFKCommand(this));
getCommand("afklist").setExecutor(new AFKListCommand(this)); registerCommands();
getCommand("afkcheck").setExecutor(new AFKCheckCommand(this));
getCommand("reloadafkdetector").setExecutor(new ReloadCommand(this));
new AFKCheckTimer(this).init(); new AFKCheckTimer(this).init();
myPetEnabled = getServer().getPluginManager().getPlugin("MyPet") != null; myPetEnabled = getServer().getPluginManager().isPluginEnabled("MyPet");
} catch (Throwable t) { } catch (Throwable t) {
getLogger().severe("An error has occured while loading AFKDetector"); getLogger().severe("An error has occured while loading AFKDetector");
if (!(t instanceof ExceptionInInitializerError)) { if (!(t instanceof ExceptionInInitializerError)) {
@@ -67,6 +72,17 @@ public class AFKDetector extends JavaPlugin implements Listener {
} }
} }
private void registerCommands() {
LifecycleEventManager<Plugin> manager = this.getLifecycleManager();
manager.registerEventHandler(LifecycleEvents.COMMANDS, event -> {
final Commands commands = event.registrar();
new AFKListCommand().register(commands);
new AFKCheckCommand().register(commands);
new RelogCheckCommand().register(commands);
new ReloadCommand().register(commands);
});
}
@Override @Override
public void onDisable() { public void onDisable() {
this.getServer().getScheduler().cancelTasks(this); this.getServer().getScheduler().cancelTasks(this);
@@ -0,0 +1,13 @@
package com.alttd.afkdectector;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
@SuppressWarnings("UnstableApiUsage")
public class AFKDetectorBootstrap implements PluginBootstrap {
@Override
public void bootstrap(BootstrapContext context) {}
}
@@ -4,8 +4,9 @@ import com.alttd.afkdectector.AFKDetector;
import com.alttd.afkdectector.config.Config; import com.alttd.afkdectector.config.Config;
import com.alttd.afkdectector.config.Messages; import com.alttd.afkdectector.config.Messages;
import de.Keyle.MyPet.MyPetApi; import de.Keyle.MyPet.MyPetApi;
import de.Keyle.MyPet.api.entity.MyPet; import de.Keyle.MyPet.api.entity.Pet;
import de.Keyle.MyPet.api.player.MyPetPlayer; import de.Keyle.MyPet.api.player.MyPetPlayer;
import de.Keyle.MyPet.api.plugin.MyPetPlugin;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
@@ -138,10 +139,10 @@ public class AFKPlayer {
if (!AFKDetector.myPetEnabled) return; if (!AFKDetector.myPetEnabled) return;
MyPetPlayer myPetPlayer = MyPetApi.getPlayerManager().getMyPetPlayer(player); MyPetPlayer myPetPlayer = MyPetApi.getPlayerManager().getMyPetPlayer(player);
if (myPetPlayer == null || !myPetPlayer.hasMyPet() || !myPetPlayer.getMyPet().getStatus().equals(MyPet.PetState.Here)) if (myPetPlayer == null || !myPetPlayer.hasPet() || !myPetPlayer.getPet().getStatus().equals(Pet.PetState.Here))
return; return;
MyPet myPet = myPetPlayer.getMyPet(); Pet myPet = myPetPlayer.getPet();
myPet.removePet(); myPet.removePet();
} }
} }
@@ -3,6 +3,10 @@ package com.alttd.afkdectector.command;
import com.alttd.afkdectector.AFKDetector; import com.alttd.afkdectector.AFKDetector;
import com.alttd.afkdectector.afkplayer.AFKPlayer; import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.config.Messages; import com.alttd.afkdectector.config.Messages;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.resolvers.selector.PlayerSelectorArgumentResolver;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
@@ -21,45 +25,35 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class AFKCheckCommand implements CommandExecutor, TabCompleter { public class AFKCheckCommand {
private final AFKDetector plugin; public void register(Commands commands) {
commands.register(
Commands.literal("afkcheck")
.requires(commandSourceStack ->
commandSourceStack.getSender().hasPermission("afkdetector.afkcheck"))
.then(Commands.argument("player", ArgumentTypes.player())
.executes(commandContext -> {
CommandSourceStack sourceStack = commandContext.getSource();
Player target = commandContext.getArgument("player", PlayerSelectorArgumentResolver.class).resolve(sourceStack).getFirst();
public AFKCheckCommand(AFKDetector plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!(args.length > 0)) {
sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED));
return true;
}
Player target = Bukkit.getPlayer(args[0]);
if (target == null) {
sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED));
return true;
}
MiniMessage miniMessage = AFKDetector.miniMessage; MiniMessage miniMessage = AFKDetector.miniMessage;
target.showTitle(Title.title(miniMessage.deserialize(Messages.AFK_CHECK_TITLE.getMessage()), target.showTitle(Title.title(miniMessage.deserialize(Messages.AFK_CHECK_TITLE.getMessage()),
miniMessage.deserialize(Messages.AFK_CHECK_SUBTITLE.getMessage()))); miniMessage.deserialize(Messages.AFK_CHECK_SUBTITLE.getMessage())));
if (sender instanceof Player player) {
String cmd = "msg " + args[0] + " " + Messages.AFK_CHECK_MESSAGE.getMessage(); if (commandContext.getSource().getSender() instanceof Player player) {
String cmd = "msg " + target.getName() + " " + Messages.AFK_CHECK_MESSAGE.getMessage();
PlayerCommandPreprocessEvent commandEvent = new PlayerCommandPreprocessEvent(player, "/" + cmd); PlayerCommandPreprocessEvent commandEvent = new PlayerCommandPreprocessEvent(player, "/" + cmd);
Bukkit.getPluginManager().callEvent(commandEvent); Bukkit.getPluginManager().callEvent(commandEvent);
player.performCommand(cmd); player.performCommand(cmd);
} else { } else {
Bukkit.dispatchCommand(sender, "msg " + args[0] + " " + Messages.AFK_CHECK_MESSAGE.getMessage()); Bukkit.dispatchCommand(commandContext.getSource().getSender(), "msg " + target.getName() + " " + Messages.AFK_CHECK_MESSAGE.getMessage());
} }
return true; return com.mojang.brigadier.Command.SINGLE_SUCCESS;
} })
)
@Override .build()
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) { , "Perform an afk check on the target."
List<String> completions = new ArrayList<>(); );
if (strings.length == 1) {
StringUtil.copyPartialMatches(strings[0], plugin.players.values().stream().filter(AFKPlayer::isAFK).map(AFKPlayer::getPlayerName).collect(Collectors.toList()), completions);
}
return null;
} }
} }
@@ -4,33 +4,39 @@ import com.alttd.afkdectector.AFKDetector;
import com.alttd.afkdectector.afkplayer.AFKPlayer; import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.config.Config; import com.alttd.afkdectector.config.Config;
import com.alttd.afkdectector.config.Messages; import com.alttd.afkdectector.config.Messages;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.resolvers.selector.PlayerSelectorArgumentResolver;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class AFKListCommand implements CommandExecutor, TabCompleter { public class AFKListCommand {
private final AFKDetector plugin; public void register(Commands commands) {
commands.register(
public AFKListCommand(AFKDetector plugin) { Commands.literal("afklist")
this.plugin = plugin; .requires(commandSourceStack ->
} commandSourceStack.getSender().hasPermission("afkdetector.afkcheck"))
.executes(commandContext -> {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
int afkPlayers = 0; int afkPlayers = 0;
Component message = Component.empty(); Component message = Component.empty();
MiniMessage miniMessage = AFKDetector.miniMessage; MiniMessage miniMessage = AFKDetector.miniMessage;
for (AFKPlayer afkplayer : plugin.players.values()) { for (AFKPlayer afkplayer : AFKDetector.getInstance().players.values()) {
long standingTime = afkplayer.getStandingTime(); long standingTime = afkplayer.getStandingTime();
if (System.currentTimeMillis() - standingTime <= TimeUnit.MINUTES.toMillis(Config.TOGGLE_TIME)) { if (System.currentTimeMillis() - standingTime <= TimeUnit.MINUTES.toMillis(Config.TOGGLE_TIME)) {
continue; continue;
@@ -50,12 +56,12 @@ public class AFKListCommand implements CommandExecutor, TabCompleter {
Placeholder.parsed("afkplayers", Integer.toString(afkPlayers)) Placeholder.parsed("afkplayers", Integer.toString(afkPlayers))
); );
Component component = miniMessage.deserialize(Messages.AFK_LIST.getMessage(), templates); Component component = miniMessage.deserialize(Messages.AFK_LIST.getMessage(), templates);
sender.sendMessage(component.append(message)); commandContext.getSource().getSender().sendMessage(component.append(message));
return true;
}
@Override return com.mojang.brigadier.Command.SINGLE_SUCCESS;
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) { })
return null; .build()
, "List all players that are afk"
);
} }
} }
@@ -1,6 +1,7 @@
package com.alttd.afkdectector.command; package com.alttd.afkdectector.command;
import com.alttd.afkdectector.AFKDetector; import com.alttd.afkdectector.AFKDetector;
import io.papermc.paper.command.brigadier.Commands;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -9,22 +10,19 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class ReloadCommand implements CommandExecutor, TabCompleter { public class ReloadCommand {
private final AFKDetector plugin; public void register(Commands commands) {
commands.register(
public ReloadCommand(AFKDetector plugin) { Commands.literal("reloadafkdetector")
this.plugin = plugin; .requires(commandSourceStack ->
} commandSourceStack.getSender().hasPermission("afkdetector.reload"))
.executes(commandContext -> {
@Override AFKDetector.getInstance().loadConfig(commandContext.getSource().getSender());
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { return com.mojang.brigadier.Command.SINGLE_SUCCESS;
AFKDetector.getInstance().loadConfig(sender); })
return true; .build()
} , "Reload the plugin configuration."
);
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) {
return null;
} }
} }
@@ -0,0 +1,59 @@
package com.alttd.afkdectector.command;
import com.alttd.afkdectector.AFKDetector;
import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.config.Messages;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.resolvers.selector.PlayerSelectorArgumentResolver;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class RelogCheckCommand {
public void register(Commands commands) {
commands.register(
Commands.literal("relogcheck")
.requires(commandSourceStack ->
commandSourceStack.getSender().hasPermission("afkdetector.relogcheck"))
.then(Commands.argument("player", ArgumentTypes.player())
.executes(commandContext -> {
CommandSourceStack sourceStack = commandContext.getSource();
Player target = commandContext.getArgument("player", PlayerSelectorArgumentResolver.class).resolve(sourceStack).getFirst();
MiniMessage miniMessage = AFKDetector.miniMessage;
target.showTitle(Title.title(miniMessage.deserialize(Messages.RELOG_CHECK_TITLE.getMessage()),
miniMessage.deserialize(Messages.RELOG_CHECK_SUBTITLE.getMessage())));
if (commandContext.getSource().getSender() instanceof Player player) {
String cmd = "msg " + target.getName() + " " + Messages.RELOG_CHECK_MESSAGE.getMessage();
PlayerCommandPreprocessEvent commandEvent = new PlayerCommandPreprocessEvent(player, "/" + cmd);
Bukkit.getPluginManager().callEvent(commandEvent);
player.performCommand(cmd);
} else {
Bukkit.dispatchCommand(commandContext.getSource().getSender(), "msg " + target.getName() + " " + Messages.RELOG_CHECK_MESSAGE.getMessage());
}
return com.mojang.brigadier.Command.SINGLE_SUCCESS;
})
)
.build()
, "Perform a relog check on the target."
);
}
}
@@ -1,135 +0,0 @@
package com.alttd.afkdectector.config;
import com.alttd.VillagerUI;
import com.alttd.util.Logger;
import com.google.common.collect.ImmutableMap;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"unused", "SameParameterValue"})
abstract class AbstractConfig {
File file;
YamlConfiguration yaml;
AbstractConfig(String filename) {
init(new File(VillagerUI.getInstance().getDataFolder(), filename), filename);
}
AbstractConfig(File file, String filename) {
init(new File(file.getPath() + File.separator + filename), filename);
}
private void init(File file, String filename) {
this.file = file;
this.yaml = new YamlConfiguration();
try {
yaml.load(file);
} catch (IOException ignore) {
} catch (InvalidConfigurationException ex) {
Logger.severe(String.format("Could not load %s, please correct your syntax errors", filename));
throw new RuntimeException(ex);
}
yaml.options().copyDefaults(true);
}
void readConfig(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
try {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (Exception ex) {
Logger.severe("Error invoking %.", method.toString());
ex.printStackTrace();
}
}
}
}
save();
}
private void save() {
try {
yaml.save(file);
} catch (IOException ex) {
Logger.severe("Could not save %.", file.toString());
ex.printStackTrace();
}
}
void set(String path, Object val) {
yaml.addDefault(path, val);
yaml.set(path, val);
save();
}
String getString(String path, String def) {
yaml.addDefault(path, def);
return yaml.getString(path, yaml.getString(path));
}
boolean getBoolean(String path, boolean def) {
yaml.addDefault(path, def);
return yaml.getBoolean(path, yaml.getBoolean(path));
}
int getInt(String path, int def) {
yaml.addDefault(path, def);
return yaml.getInt(path, yaml.getInt(path));
}
double getDouble(String path, double def) {
yaml.addDefault(path, def);
return yaml.getDouble(path, yaml.getDouble(path));
}
<T> List<?> getList(String path, T def) {
yaml.addDefault(path, def);
return yaml.getList(path, yaml.getList(path));
}
List<String> getStringList(String path, List<String> def) {
yaml.addDefault(path, def);
return yaml.getStringList(path);
}
@NonNull
<T> Map<String, T> getMap(final @NonNull String path, final @Nullable Map<String, T> def) {
final ImmutableMap.Builder<String, T> builder = ImmutableMap.builder();
if (def != null && yaml.getConfigurationSection(path) == null) {
yaml.addDefault(path, def.isEmpty() ? new HashMap<>() : def);
return def;
}
final ConfigurationSection section = yaml.getConfigurationSection(path);
if (section != null) {
for (String key : section.getKeys(false)) {
@SuppressWarnings("unchecked")
final T val = (T) section.get(key);
if (val != null) {
builder.put(key, val);
}
}
}
return builder.build();
}
ConfigurationSection getConfigurationSection(String path) {
return yaml.getConfigurationSection(path);
}
}
@@ -15,6 +15,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Pattern;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class Config { public class Config {
@@ -19,6 +19,9 @@ public enum Messages {
AFK_CHECK_TITLE("afkcheck-title", "AFK CHECK"), AFK_CHECK_TITLE("afkcheck-title", "AFK CHECK"),
AFK_CHECK_SUBTITLE("afkcheck-subtitle", "Please respond to the dm from staff!"), AFK_CHECK_SUBTITLE("afkcheck-subtitle", "Please respond to the dm from staff!"),
AFK_CHECK_MESSAGE("afkcheck-message", "Hey, since you're near a farm and not moving. I'm making sure you aren't afk. Please respond to me if you're not AFK."), AFK_CHECK_MESSAGE("afkcheck-message", "Hey, since you're near a farm and not moving. I'm making sure you aren't afk. Please respond to me if you're not AFK."),
RELOG_CHECK_TITLE("relogcheck-title", "AFK CHECK"),
RELOG_CHECK_SUBTITLE("relogcheck-subtitle", "Please respond to the dm from staff!"),
RELOG_CHECK_MESSAGE("relogcheck-message", "Hey, since you're near a farm and not moving. I'm making sure you aren't afk. Please respond to me if you're not AFK."),
AFK_KICK_STAFF_MESSAGE("afkkick-staff-messsge", "<gold><player> got afk kicked after being afk for <afk_time> minutes."), AFK_KICK_STAFF_MESSAGE("afkkick-staff-messsge", "<gold><player> got afk kicked after being afk for <afk_time> minutes."),
SUSPICIOUS_KICK_COUNT("afkkick-suspicious-message", "<gold><player> has had <count> suspicious AFK kicks since last reboot."), SUSPICIOUS_KICK_COUNT("afkkick-suspicious-message", "<gold><player> has had <count> suspicious AFK kicks since last reboot."),
AFK_SOON_BOSS_BAR("afk-soon-boss-bar", "<dark_aqua>Time until AFK.</dark_aqua>"), AFK_SOON_BOSS_BAR("afk-soon-boss-bar", "<dark_aqua>Time until AFK.</dark_aqua>"),
@@ -1,28 +0,0 @@
package com.alttd.afkdectector.util;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import java.util.logging.Level;
public class Logger {
public static void info(String str) {
log(Level.INFO, "&e" + str);
}
public static void warn(String str) {
log(Level.SEVERE, "&6" + str);
}
public static void severe(String str) {
log(Level.SEVERE, "&c" + str);
}
public static void log(Level level, String str) {
Bukkit.getLogger().log(level,
ChatColor.translateAlternateColorCodes('&',
"&r " + str));
}
}
View File
-61
View File
@@ -1,61 +0,0 @@
main: com.alttd.afkdectector.AFKDetector
name: AFKDetector
version: ${projectVersion}
api-version: 1.21
author: Destro174
softdepend:
- MyPet
description: Checks if a player is afk.
commands:
afklist:
description: Gives a list of all afk players
permission: afkdetector.afklist
permission-message: You do not have permission!
usage: /afklist
afkcheck:
description: Sends and afkcheck message to the target
permission: afkdetector.afkcheck
permission-message: You do not have permission!
usage: /afkcheck <target>
reloadafkdetector:
description: Reloads the plugin config
permission: afkdetector.reload
permission-message: You do not have permission!
usage: /afkdetectorreload
permissions:
afkdetector.admin:
default: op
description: Implies all permissions.
children:
afkdetector.bypass: true
afkdetector.afklist: true
afkdetector.afkcheck: true
afkdetector.notify: true
afkdetector.reload: true
afkdetector.bypass:
description: Bypass the AFKplugin.
default: op
children:
afkdetector.kickexempt: true
afkdetector.reload:
description: Allows reloading the afkdetector plugin config.
default: op
afkdetector.kickexempt:
description: Doesn't kick you automatically for AFK.
default: op
afkdetector.afktime:
description: Master permission for custom times.
default: false
afkdetector.afkcheck:
description: Allows the usage of /afkcheck command.
default: false
afkdetector.afklist:
description: Allows the usage of /afklist command.
default: false
afkdetector.notify:
description: Get output when a player goes afk.
default: false