Improved code readability (for me)

This commit is contained in:
Teriuihi 2023-03-30 02:24:56 +02:00
parent af47035b8b
commit ce798fcefa
10 changed files with 323 additions and 280 deletions

View File

@ -1,8 +1,5 @@
package com.alttd.afkdectector;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.config.Config;
import com.alttd.afkdectector.config.Messages;
@ -14,73 +11,98 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class AFKCheckTimer extends BukkitRunnable{
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class AFKCheckTimer extends BukkitRunnable {
private final AFKDetector plugin;
private AFKDetector plugin;
public AFKCheckTimer(AFKDetector plugin) {
this.plugin = plugin;
}
public void init() {
runTaskTimer(plugin, 0, 20);
runTaskTimer(plugin, 0, 20);
}
@Override
@Override
public void run() {
for (UUID uuid : plugin.players.keySet()) {
Player player = Bukkit.getPlayer(uuid);
AFKPlayer afkplayer = plugin.players.get(uuid);
if(player == null || player.hasPermission("afkdetector.bypass")) {
continue;
}
Location pastLocation = afkplayer.getplayerToSphereCenter();
if(pastLocation == null || !player.getLocation().getWorld().getName().equals(pastLocation.getWorld().getName())) {
pastLocation = player.getLocation();
afkplayer.setplayerToSphereCenter(pastLocation);
}
if (player.getLocation().distanceSquared(pastLocation) > Config.RADIUS * Config.RADIUS) {
if(player.getLocation().getYaw() != pastLocation.getYaw() && player.getLocation().getPitch() != pastLocation.getPitch()) {
afkplayer.setplayerToSphereCenter(pastLocation);
afkplayer.setstandingTime(System.currentTimeMillis());
player.setSleepingIgnored(false);
//player.setCanPickupItems(true);
plugin.AFKPlayers.removeEntry(player.getName());
afkplayer.ResetAFK();
MessageTimer currentTimer = plugin.messageTimers.get(player.getUniqueId());
if (currentTimer != null) {
plugin.messageTimers.remove(player.getUniqueId());
}
continue;
}
}
long standingTime = afkplayer.getstandingTime();
if(!afkplayer.isafk() && System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(Config.TOGGLETIME)) {
afkplayer.setafk(true);
player.setSleepingIgnored(true);
//player.setCanPickupItems(false);
plugin.AFKPlayers.addEntry(player.getName());
if (Config.AFKTOGGLEMESSAGES) {
TagResolver placeholders = TagResolver.resolver(
Placeholder.parsed("player", player.getName())
);
Component component = AFKDetector.miniMessage.deserialize(Messages.AFKTOGGLEON.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify");
}
}
if(System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(afkplayer.getafkTime())) {
MessageTimer currentTimer = plugin.messageTimers.get(uuid);
if(currentTimer == null) {
currentTimer = new MessageTimer(plugin, afkplayer, Config.MESSAGEREPEATS);
plugin.messageTimers.put(uuid, currentTimer);
currentTimer.init();
}
} else {
MessageTimer currentTimer = plugin.messageTimers.get(uuid);
if(currentTimer != null) {
plugin.messageTimers.remove(player.getUniqueId());
}
}
}
for (UUID uuid : plugin.players.keySet()) {
Player player = Bukkit.getPlayer(uuid);
AFKPlayer afkPlayer = plugin.players.get(uuid);
if (player == null || player.hasPermission("afkdetector.bypass")) {
continue;
}
Location pastLocation = afkPlayer.getPlayerToSphereCenter();
if (pastLocation == null || !player.getLocation().getWorld().getName().equals(pastLocation.getWorld().getName())) {
pastLocation = player.getLocation();
afkPlayer.setPlayerToSphereCenter(pastLocation);
}
if (playerMovedOutOfSphere(player, pastLocation) && playerHeadMoved(player.getLocation(), pastLocation)) {
resetAFKPlayer(pastLocation, player, afkPlayer);
continue;
}
long standingTime = afkPlayer.getStandingTime();
if (!afkPlayer.isAFK() && System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(Config.TOGGLE_TIME)) {
setPlayerAFK(afkPlayer, player);
}
runMessageTimerCheck(afkPlayer, uuid, standingTime);
}
}
private boolean playerMovedOutOfSphere(Player player, Location pastLocation) {
return player.getLocation().distanceSquared(pastLocation) > Config.RADIUS * Config.RADIUS;
}
private boolean playerHeadMoved(Location playerLocation, Location pastLocation) {
return playerLocation.getYaw() != pastLocation.getYaw() && playerLocation.getPitch() != pastLocation.getPitch();
}
private void resetAFKPlayer(Location pastLocation, Player player, AFKPlayer afkPlayer) {
afkPlayer.setPlayerToSphereCenter(pastLocation);
afkPlayer.setStandingTime(System.currentTimeMillis());
player.setSleepingIgnored(false);
plugin.AFKPlayers.removeEntry(player.getName());
afkPlayer.ResetAFK();
MessageTimer currentTimer = plugin.messageTimers.get(player.getUniqueId());
if (currentTimer != null) {
plugin.messageTimers.remove(player.getUniqueId());
}
}
private void setPlayerAFK(AFKPlayer afkPlayer, Player player) {
afkPlayer.setAFK(true);
player.setSleepingIgnored(true);
//player.setCanPickupItems(false);
plugin.AFKPlayers.addEntry(player.getName());
if (Config.AFK_TOGGLE_MESSAGES) {
TagResolver placeholders = TagResolver.resolver(
Placeholder.parsed("player", player.getName())
);
Component component = AFKDetector.miniMessage.deserialize(Messages.AFK_TOGGLE_ON.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify");
}
}
private void runMessageTimerCheck(AFKPlayer afkPlayer, UUID uuid, long standingTime) {
if (System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(afkPlayer.getAfkTime())) {
MessageTimer currentTimer = plugin.messageTimers.get(uuid);
if (currentTimer == null) {
currentTimer = new MessageTimer(plugin, afkPlayer, Config.MESSAGE_REPEATS);
plugin.messageTimers.put(uuid, currentTimer);
currentTimer.init();
}
} else {
MessageTimer currentTimer = plugin.messageTimers.get(uuid);
if (currentTimer != null) {
plugin.messageTimers.remove(uuid);
}
}
}
}

View File

@ -9,6 +9,8 @@ import com.alttd.afkdectector.config.Messages;
import com.alttd.afkdectector.config.MessagesConfig;
import com.alttd.afkdectector.trackers.AutoJoinTracker;
import com.alttd.afkdectector.trackers.SuspiciousKickTracker;
import com.alttd.afkdectector.util.Logger;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
@ -18,7 +20,6 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
@ -41,11 +42,11 @@ public class AFKDetector extends JavaPlugin implements Listener{
public HashMap<UUID, MessageTimer> messageTimers = new HashMap<>();
public HashMap<UUID, Integer> PlayerAfkTime = new HashMap<>();
public boolean fulloverride;
public boolean fullOverride;
public static MiniMessage miniMessage;
/**
* afkplayers need to be added to a team.
* AFK players need to be added to a team.
*/
Team AFKPlayers;
@ -55,7 +56,7 @@ public class AFKDetector extends JavaPlugin implements Listener{
instance = this;
miniMessage = MiniMessage.miniMessage();
loadConfig(null);
settupAfkState();
setupAFKStats();
getServer().getPluginManager().registerEvents(this, this);
//getCommand("afk").setExecutor(new AFKCommand(this));
getCommand("afklist").setExecutor(new AFKListCommand(this));
@ -86,12 +87,16 @@ public class AFKDetector extends JavaPlugin implements Listener{
return players.get(player.getUniqueId());
}
private void settupAfkState() {
private void setupAFKStats() {
if (Bukkit.getScoreboardManager().getMainScoreboard().getTeam("AFKPlayers") == null) {
AFKPlayers = Bukkit.getScoreboardManager().getMainScoreboard().registerNewTeam("AFKPlayers");
} else {
AFKPlayers = Bukkit.getScoreboardManager().getMainScoreboard().getTeam("AFKPlayers");
}
if (AFKPlayers == null) {
Logger.warn("Could not find scoreboard AFKPlayers");
return;
}
AFKPlayers.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER);
//AFKPlayers.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER);
}
@ -99,41 +104,37 @@ public class AFKDetector extends JavaPlugin implements Listener{
/**
* Get the afk time for a player
*/
public int getaAllowedAfktime(Player player) {
if(Config.SERVERFULL) {
return Config.DEFAULTAFKTIME;
public int getAllowedAFKTime(Player player) {
if(Config.SERVER_FULL) {
return Config.DEFAULT_AFK_TIME;
}
return PlayerAfkTime.get(player.getUniqueId());
}
public int getPlayerAfktime(Player player) {
public int getPlayerAFKTime(Player player) {
String permissionPrefix = "afkdetector.afktime.";
for (PermissionAttachmentInfo attachmentInfo : player.getEffectivePermissions()) {
if (attachmentInfo.getPermission().startsWith(permissionPrefix)) {
String perm = attachmentInfo.getPermission();
int Time = Integer.parseInt(perm.substring(perm.lastIndexOf(".") + 1));
if(Time >= Config.MAXAFKTIME) {
return Config.MAXAFKTIME;
} else {
return Time;
}
return Math.min(Time, Config.MAX_AFK_TIME);
}
}
return Config.DEFAULTAFKTIME;
return Config.DEFAULT_AFK_TIME;
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
PlayerAfkTime.put(uuid, getPlayerAfktime(player));
PlayerAfkTime.put(uuid, getPlayerAFKTime(player));
players.put(uuid, new AFKPlayer(player, this));
if(Bukkit.getOnlinePlayers().size() >= Config.PLAYERLIMIT && !Config.SERVERFULL) {
fulloverride = true;
if(Bukkit.getOnlinePlayers().size() >= Config.PLAYER_LIMIT && !Config.SERVER_FULL) {
fullOverride = true;
}
long lastKick = AutoJoinTracker.getInstance().getLastKick(uuid);
if (lastKick + TimeUnit.SECONDS.toMillis(Config.MAXREJOINFORTRACKING) > new Date().getTime()) {
if (lastKick + TimeUnit.SECONDS.toMillis(Config.MAX_REJOIN_FOR_TRACKING) > new Date().getTime()) {
AutoJoinTracker.getInstance().setLastKick(uuid, 0);
SuspiciousKickTracker skt = SuspiciousKickTracker.getInstance();
skt.addSuspiciousKick(uuid);
@ -142,7 +143,7 @@ public class AFKDetector extends JavaPlugin implements Listener{
Placeholder.component("player", player.name()),
Placeholder.parsed("count", "" + suspiciousKickCount)
);
Component component = MiniMessage.miniMessage().deserialize(Messages.SUSPICIOUSKICKCOUNT.getMessage(), placeholders);
Component component = MiniMessage.miniMessage().deserialize(Messages.SUSPICIOUS_KICK_COUNT.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify");
}
}
@ -152,14 +153,14 @@ public class AFKDetector extends JavaPlugin implements Listener{
Player player = event.getPlayer();
// Remove the players from the timer if they logout
players.remove(player.getUniqueId());
if(Bukkit.getOnlinePlayers().size() < Config.PLAYERLIMIT && fulloverride){
fulloverride = false;
if(Bukkit.getOnlinePlayers().size() < Config.PLAYER_LIMIT && fullOverride){
fullOverride = false;
}
}
@EventHandler
public void onTalkCancel(AsyncPlayerChatEvent event) {
if (!Config.CHATWILLCANCEL) {
public void onTalkCancel(AsyncChatEvent event) {
if (!Config.CHAT_WILL_CANCEL) {
return;
}
Player player = event.getPlayer();
@ -167,8 +168,8 @@ public class AFKDetector extends JavaPlugin implements Listener{
}
@EventHandler
public void oncommandCancel(PlayerCommandPreprocessEvent event) {
if (!Config.COMMANDWILLCANCEL) {
public void onCommandCancel(PlayerCommandPreprocessEvent event) {
if (!Config.COMMAND_WILL_CANCEL) {
return;
}
Player player = event.getPlayer();

View File

@ -2,6 +2,7 @@ package com.alttd.afkdectector;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.alttd.afkdectector.afkplayer.AFKPlayer;
import com.alttd.afkdectector.config.Config;
@ -18,9 +19,9 @@ import org.bukkit.scheduler.BukkitRunnable;
public class MessageTimer extends BukkitRunnable {
private AFKDetector plugin;
private UUID uuid;
private AFKPlayer afkPlayer;
private final AFKDetector plugin;
private final UUID uuid;
private final AFKPlayer afkPlayer;
private int repeats;
public MessageTimer(AFKDetector plugin, AFKPlayer afkPlayer, int repeats) {
@ -31,7 +32,7 @@ public class MessageTimer extends BukkitRunnable {
}
public void init() {
runTaskTimer(plugin, 0, Config.MESSAGEDELAY * 20L);
runTaskTimer(plugin, 0, Config.MESSAGE_DELAY * 20L);
}
// TODO get a better string builder
@ -39,7 +40,8 @@ public class MessageTimer extends BukkitRunnable {
private String return_placeholders(Param String ... string)
*/
private String return_placeholders(String s, Player p) {
s = s.replaceAll("%player%", p.getName()).replaceAll("%afktime%", (int) Math.floor((System.currentTimeMillis() - plugin.getPlayer(p).getstandingTime()) / 60 / 1000) +"");
int afkTime = (int) TimeUnit.MILLISECONDS.toMinutes((long) Math.floor(System.currentTimeMillis() - plugin.getPlayer(p).getStandingTime()));
s = s.replaceAll("%player%", p.getName()).replaceAll("%afktime%", afkTime + "");
return s;
}
@ -51,13 +53,13 @@ public class MessageTimer extends BukkitRunnable {
cancel();
return;
}
if(Config.COUNTDOWNENABLED) {
if(Config.COUNT_DOWN_ENABLED) {
MiniMessage miniMessage = AFKDetector.miniMessage;
Title title = Title.title(miniMessage.deserialize(Messages.COUNTDOWNTITLE1.getMessage()),
miniMessage.deserialize(Messages.COUNTDOWNTITLE2.getMessage()));
Title title = Title.title(miniMessage.deserialize(Messages.COUNT_DOWN_TITLE_1.getMessage()),
miniMessage.deserialize(Messages.COUNT_DOWN_TITLE_2.getMessage()));
//Title.Times.of(Config.FADEIN, Config.STAY, Config.STAY);
player.showTitle(title);
player.sendMessage(miniMessage.deserialize(Messages.COUNTDOWNMESSAGE.getMessage()));
player.sendMessage(miniMessage.deserialize(Messages.COUNT_DOWN_MESSAGE.getMessage()));
}
repeats = repeats - 1;
@ -67,13 +69,13 @@ public class MessageTimer extends BukkitRunnable {
}
//Bukkit.dispatchCommand(Bukkit.getConsoleSender(), plugin.kickCommand.replace("%player%", player.getName()));
plugin.messageTimers.remove(player.getUniqueId());
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), return_placeholders(Config.KICKCOMMAND, player));
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), return_placeholders(Config.KICK_COMMAND, player));
AutoJoinTracker.getInstance().setLastKick(player.getUniqueId(), new Date().getTime());
TagResolver templates = TagResolver.resolver(
Placeholder.unparsed("player", player.getName()),
Placeholder.unparsed("afk_time", "" + (int) Math.floor((System.currentTimeMillis() - plugin.getPlayer(player).getstandingTime()) / 60f / 1000))
Placeholder.unparsed("afk_time", "" + (int) Math.floor((System.currentTimeMillis() - plugin.getPlayer(player).getStandingTime()) / 60f / 1000))
);
Component message = MiniMessage.miniMessage().deserialize(Messages.AFKICKSTAFFMESSAGE.getMessage(), templates);
Component message = MiniMessage.miniMessage().deserialize(Messages.AFK_KICK_STAFF_MESSAGE.getMessage(), templates);
Bukkit.broadcast(message, "afkdetector.notify");
cancel();
}

View File

@ -1,7 +1,6 @@
package com.alttd.afkdectector.afkplayer;
import java.util.UUID;
import com.alttd.afkdectector.AFKDetector;
import com.alttd.afkdectector.config.Config;
import com.alttd.afkdectector.config.Messages;
import net.kyori.adventure.text.Component;
@ -11,81 +10,82 @@ import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.alttd.afkdectector.AFKDetector;
import java.util.UUID;
public class AFKPlayer {
private final String playerName;
private final UUID uuid;
private Location playerToSphereCenter;
private long standingTime;
private final int afkTime;
private boolean isafk;
private final String playerName;
private final UUID uuid;
private Location playerToSphereCenter;
private long standingTime;
private final int afkTime;
private boolean isAFK;
public AFKPlayer(Player player, AFKDetector plugin) {
this.playerName = player.getName();
this.uuid = player.getUniqueId();
this.playerToSphereCenter = player.getLocation();
this.standingTime = System.currentTimeMillis();
this.afkTime = plugin.getaAllowedAfktime(player);
this.isafk = false;
}
public AFKPlayer(Player player, AFKDetector plugin) {
this.playerName = player.getName();
this.uuid = player.getUniqueId();
this.playerToSphereCenter = player.getLocation();
this.standingTime = System.currentTimeMillis();
this.afkTime = plugin.getAllowedAFKTime(player);
this.isAFK = false;
}
public String getPlayerName() {
return this.playerName;
}
public UUID getPlayerUuid() {
return this.uuid;
}
public Location getplayerToSphereCenter() {
return playerToSphereCenter;
public Location getPlayerToSphereCenter() {
return playerToSphereCenter;
}
public void setplayerToSphereCenter(Location playerlocation) {
playerToSphereCenter = playerlocation;
public void setPlayerToSphereCenter(Location playerlocation) {
playerToSphereCenter = playerlocation;
}
public long getstandingTime() {
return standingTime;
public long getStandingTime() {
return standingTime;
}
public void setstandingTime(long Time) {
standingTime = Time;
public void setStandingTime(long Time) {
standingTime = Time;
}
public int getafkTime() {
if (isInSpawn())
return this.afkTime + Config.EXTRA_MIN_IN_SPAWN;
return this.afkTime;
public int getAfkTime() {
if (isInSpawn())
return this.afkTime + Config.EXTRA_MIN_IN_SPAWN;
return this.afkTime;
}
public boolean isInSpawn() {
double x = getplayerToSphereCenter().getX();
double z = getplayerToSphereCenter().getZ();
return x < Config.SPAWN_MAX_X && x > Config.SPAWN_MIN_X && z < Config.SPAWN_MAX_Z && z > Config.SPAWN_MIN_Z;
}
double x = getPlayerToSphereCenter().getX();
double z = getPlayerToSphereCenter().getZ();
return x < Config.SPAWN_MAX_X && x > Config.SPAWN_MIN_X && z < Config.SPAWN_MAX_Z && z > Config.SPAWN_MIN_Z;
}
public void setafk(boolean bool) {
isafk = bool;
}
public void setAFK(boolean bool) {
isAFK = bool;
}
public boolean isafk() {
return isafk;
}
public boolean isAFK() {
return isAFK;
}
public void ResetAFK() {
if(isafk && Config.AFKTOGGLEMESSAGES) {
TagResolver placeholders = TagResolver.resolver(
Placeholder.parsed("player", playerName)
);
Component component = AFKDetector.miniMessage.deserialize(Messages.AFKTOGGLEOFF.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify");
}
standingTime = System.currentTimeMillis();
playerToSphereCenter = Bukkit.getPlayer(getPlayerUuid()).getLocation();
isafk = false;
if (isAFK && Config.AFK_TOGGLE_MESSAGES) {
TagResolver placeholders = TagResolver.resolver(
Placeholder.parsed("player", playerName)
);
Component component = AFKDetector.miniMessage.deserialize(Messages.AFK_TOGGLE_OFF.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify");
}
standingTime = System.currentTimeMillis();
Player player = Bukkit.getPlayer(getPlayerUuid());
playerToSphereCenter = (player == null) ? null : player.getLocation();
isAFK = false;
}
}

View File

@ -15,6 +15,7 @@ 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;
@ -22,44 +23,43 @@ import java.util.stream.Collectors;
public class AFKCheckCommand implements CommandExecutor, TabCompleter {
private AFKDetector plugin;
private final AFKDetector plugin;
public AFKCheckCommand(AFKDetector plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, 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;
target.showTitle(Title.title(miniMessage.deserialize(Messages.AFKCHECKTITLE.getMessage()),
miniMessage.deserialize(Messages.AFKCHECKSUBTITLE.getMessage())));
if(sender instanceof Player) {
Player player = (Player) sender;
String cmd = "msg " + args[0] + " " + Messages.AFKCHECKMESSAGE.getMessage();
PlayerCommandPreprocessEvent commandEvent = new PlayerCommandPreprocessEvent(player, "/" + cmd);
Bukkit.getPluginManager().callEvent(commandEvent);
player.performCommand(cmd);
} else {
Bukkit.dispatchCommand(sender, "msg " + args[0] + " " + Messages.AFKCHECKMESSAGE.getMessage());
}
@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;
target.showTitle(Title.title(miniMessage.deserialize(Messages.AFK_CHECK_TITLE.getMessage()),
miniMessage.deserialize(Messages.AFK_CHECK_SUBTITLE.getMessage())));
if (sender instanceof Player player) {
String cmd = "msg " + args[0] + " " + Messages.AFK_CHECK_MESSAGE.getMessage();
PlayerCommandPreprocessEvent commandEvent = new PlayerCommandPreprocessEvent(player, "/" + cmd);
Bukkit.getPluginManager().callEvent(commandEvent);
player.performCommand(cmd);
} else {
Bukkit.dispatchCommand(sender, "msg " + args[0] + " " + Messages.AFK_CHECK_MESSAGE.getMessage());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
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;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) {
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;
}
}

View File

@ -12,46 +12,50 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class AFKListCommand implements CommandExecutor, TabCompleter {
private AFKDetector plugin;
private final AFKDetector plugin;
public AFKListCommand(AFKDetector plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
int afkplayers = 0;
Component message = Component.empty();
MiniMessage miniMessage = AFKDetector.miniMessage;
for (AFKPlayer afkplayer : plugin.players.values()) {
long standingTime = afkplayer.getstandingTime();
if(System.currentTimeMillis() - standingTime > Config.TOGGLETIME * 60 * 1000) {
afkplayers += 1;
message = message.append(Component.newline());
TagResolver templates = TagResolver.resolver(
Placeholder.parsed("player", afkplayer.getPlayerName()),
Placeholder.parsed("afktime", (System.currentTimeMillis() - standingTime) / 1000 + "")
);
Component userinfo = miniMessage.deserialize(Messages.AFK_LIST_ENTRY.getMessage(), templates);
message = message.append(userinfo);
}
}
TagResolver templates = TagResolver.resolver(
Placeholder.parsed("afkplayers", Integer.toString(afkplayers))
);
Component component = miniMessage.deserialize(Messages.AFK_LIST.getMessage(), templates);
sender.sendMessage(component.append(message));
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
int afkPlayers = 0;
Component message = Component.empty();
MiniMessage miniMessage = AFKDetector.miniMessage;
for (AFKPlayer afkplayer : plugin.players.values()) {
long standingTime = afkplayer.getStandingTime();
if (System.currentTimeMillis() - standingTime <= TimeUnit.MINUTES.toMillis(Config.TOGGLE_TIME)) {
continue;
}
afkPlayers += 1;
message = message.append(Component.newline());
TagResolver templates = TagResolver.resolver(
Placeholder.parsed("player", afkplayer.getPlayerName()),
Placeholder.parsed("afktime", (System.currentTimeMillis() - standingTime) / 1000 + "")
);
Component userinfo = miniMessage.deserialize(Messages.AFK_LIST_ENTRY.getMessage(), templates);
message = message.append(userinfo);
}
TagResolver templates = TagResolver.resolver(
Placeholder.parsed("afkplayers", Integer.toString(afkPlayers))
);
Component component = miniMessage.deserialize(Messages.AFK_LIST.getMessage(), templates);
sender.sendMessage(component.append(message));
return true;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
return null;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) {
return null;
}
}

View File

@ -5,25 +5,26 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class ReloadCommand implements CommandExecutor, TabCompleter {
private AFKDetector plugin;
private final AFKDetector plugin;
public ReloadCommand(AFKDetector plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
AFKDetector.getInstance().loadConfig(sender);
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
AFKDetector.getInstance().loadConfig(sender);
return true;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
return null;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) {
return null;
}
}

View File

@ -26,56 +26,60 @@ public class Config extends AbstractConfiguration {
}
public static boolean DEBUG_MODE = false;
private static void settings() {
DEBUG_MODE = config.getBoolean("debug-mode", DEBUG_MODE);
}
public static boolean SLEEPIGNORE = false;
public static boolean SLEEP_IGNORE = false;
public static int RADIUS = 4;
public static int TOGGLETIME = 4;
public static int DEFAULTAFKTIME = 5;
public static int MAXAFKTIME = 5;
public static boolean SERVERFULL = false;
public static int PLAYERLIMIT = Math.round(Bukkit.getMaxPlayers() * 90 / 100);
public static int COMMANDCOOLDOWWN = 60;
public static boolean AFKTOGGLEMESSAGES = true;
public static boolean NOTIFYSTAFFONAFKKIC = true;
public static int MAXREJOINFORTRACKING = 30;
public static int TOGGLE_TIME = 4;
public static int DEFAULT_AFK_TIME = 5;
public static int MAX_AFK_TIME = 5;
public static boolean SERVER_FULL = false;
public static int PLAYER_LIMIT = Math.round(Bukkit.getMaxPlayers() * 90 / 100);
public static int COMMAND_COOL_DOWN = 60;
public static boolean AFK_TOGGLE_MESSAGES = true;
public static boolean NOTIFY_STAFF_ON_AFK_KICK = true;
public static int MAX_REJOIN_FOR_TRACKING = 30;
private static void playerSettings() {
SLEEPIGNORE = config.getBoolean("player.sleep", SLEEPIGNORE);
SLEEP_IGNORE = config.getBoolean("player.sleep", SLEEP_IGNORE);
RADIUS = config.getInt("player.radius", RADIUS);
TOGGLETIME = config.getInt("player.toggle-time", TOGGLETIME);
DEFAULTAFKTIME = config.getInt("player.afk-time", 5);
MAXAFKTIME = config.getInt("player.maxafk-time", 5);
SERVERFULL = config.getBoolean("player.serverfull" ,false);
COMMANDCOOLDOWWN = config.getInt("player.commandcooldown", COMMANDCOOLDOWWN);
AFKTOGGLEMESSAGES = config.getBoolean("player.afk-toggle-messages", AFKTOGGLEMESSAGES);
NOTIFYSTAFFONAFKKIC = config.getBoolean("player.notify-staff-on-afk-kick", NOTIFYSTAFFONAFKKIC);
MAXREJOINFORTRACKING = config.getInt("tracking.max-seconds-for-tracking", MAXREJOINFORTRACKING);
TOGGLE_TIME = config.getInt("player.toggle-time", TOGGLE_TIME);
DEFAULT_AFK_TIME = config.getInt("player.afk-time", 5);
MAX_AFK_TIME = config.getInt("player.maxafk-time", 5);
SERVER_FULL = config.getBoolean("player.serverfull", false);
COMMAND_COOL_DOWN = config.getInt("player.commandcooldown", COMMAND_COOL_DOWN);
AFK_TOGGLE_MESSAGES = config.getBoolean("player.afk-toggle-messages", AFK_TOGGLE_MESSAGES);
NOTIFY_STAFF_ON_AFK_KICK = config.getBoolean("player.notify-staff-on-afk-kick", NOTIFY_STAFF_ON_AFK_KICK);
MAX_REJOIN_FOR_TRACKING = config.getInt("tracking.max-seconds-for-tracking", MAX_REJOIN_FOR_TRACKING);
}
public static boolean COUNTDOWNENABLED = false;
public static boolean COUNT_DOWN_ENABLED = false;
public static int FADEIN = 10;
public static int STAY = 50;
public static int FADEOUt = 10;
public static int MESSAGEDELAY = 15;
public static int MESSAGEREPEATS = 15;
public static String KICKCOMMAND = "kickfrombungee %player% &cYou have been afk for %afktime% minutes.";
private static void countdownSettigns() {
COUNTDOWNENABLED = config.getBoolean("countdown.enabled" ,COUNTDOWNENABLED);
public static int FADEOUT = 10;
public static int MESSAGE_DELAY = 15;
public static int MESSAGE_REPEATS = 15;
public static String KICK_COMMAND = "kickfrombungee %player% &cYou have been afk for %afktime% minutes.";
private static void countdownSettings() {
COUNT_DOWN_ENABLED = config.getBoolean("countdown.enabled", COUNT_DOWN_ENABLED);
FADEIN = config.getInt("countdown.fadein", FADEIN);
STAY = config.getInt("countdown.stay", STAY);
FADEOUt = config.getInt("countdown.fadeout", FADEOUt);
MESSAGEDELAY = config.getInt("countdown.message-delay", MESSAGEDELAY);
MESSAGEREPEATS = config.getInt("countdown.message-repeats", MESSAGEREPEATS);
KICKCOMMAND = config.getString("countdown.kick-command", KICKCOMMAND);
FADEOUT = config.getInt("countdown.fadeout", FADEOUT);
MESSAGE_DELAY = config.getInt("countdown.message-delay", MESSAGE_DELAY);
MESSAGE_REPEATS = config.getInt("countdown.message-repeats", MESSAGE_REPEATS);
KICK_COMMAND = config.getString("countdown.kick-command", KICK_COMMAND);
}
public static boolean CHATWILLCANCEL = true;
public static boolean COMMANDWILLCANCEL = true;
private static void eventSettigns() {
CHATWILLCANCEL = config.getBoolean("events.chat", CHATWILLCANCEL);
COMMANDWILLCANCEL = config.getBoolean("events.commands", COMMANDWILLCANCEL);
public static boolean CHAT_WILL_CANCEL = true;
public static boolean COMMAND_WILL_CANCEL = true;
private static void eventSettings() {
CHAT_WILL_CANCEL = config.getBoolean("events.chat", CHAT_WILL_CANCEL);
COMMAND_WILL_CANCEL = config.getBoolean("events.commands", COMMAND_WILL_CANCEL);
}
public static int SPAWN_MAX_X = 250;
@ -83,6 +87,7 @@ public class Config extends AbstractConfiguration {
public static int SPAWN_MAX_Z = 250;
public static int SPAWN_MIN_Z = -250;
public static int EXTRA_MIN_IN_SPAWN = 10;
private static void spawnSettings() {
SPAWN_MAX_X = config.getInt("spawn.max-x", SPAWN_MAX_X);
SPAWN_MIN_X = config.getInt("spawn.min-x", SPAWN_MIN_X);

View File

@ -2,7 +2,7 @@ package com.alttd.afkdectector.config;
public enum Messages {
TITLE("title-name", "<red>[<white>AFKDetector</white>]</red> "),
COOLDOWN("cooldown-message", "You need to wait <timeleft> seconds before using this command."),
COOL_DOWN("cooldown-message", "You need to wait <timeleft> seconds before using this command."),
INVALID_PLAYER("invalid-args", "<red>Invalid args!usage: -p:playername"),
INVALID_REASON("invalid-reason" , "<red>Invalid args! usage: -r:reason"),
NOT_ONLINE("player-notonline", "<red>Invalid args! player not online"),
@ -11,19 +11,27 @@ public enum Messages {
AFK_LIST("afk-list", "<gold>There are <afkplayers> afk."),
AFK_LIST_ENTRY("afk-list-entry", "<player> has been afk for <afktime> seconds. <hover:show_text:Click to teleport><click:suggest_command:/tp <player>>[Teleport]</click></hover> <hover:show_text:Click to send an afkcheck.><click:suggest_command:/afkcheck <player>>[Afkcheck]</click></hover>"),
AFK_PREFIX("afk-prefix", "[AFK]"),
COUNTDOWNMESSAGE("countdown-message", "<gray>You need to move around to avoid being kicked"),
COUNTDOWNTITLE1("countdown-title1", "<gray>You need to move around to avoid being kicked"),
COUNTDOWNTITLE2("countdown-title2", "<gray>You need to move around to avoid being kicked"),
AFKTOGGLEON("afk-toggle-on", "<teal><player> is now afk."),
AFKTOGGLEOFF("afk-toggle-off", "<teal><player> is no longer afk."),
AFKCHECKTITLE("afkcheck-title", "AFK CHECK"),
AFKCHECKSUBTITLE("afkcheck-subtitle", "Please respond to the dm from staff!"),
AFKCHECKMESSAGE("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."),
AFKICKSTAFFMESSAGE("afkkick-staff-messsge", "<gold><player> got afk kicked after being afk for <afk_time> minutes."),
SUSPICIOUSKICKCOUNT("afkkick-suspicious-message", "<gold><player> has had <count> suspicious AFK kicks since last reboot.");
COUNT_DOWN_MESSAGE("countdown-message", "<gray>You need to move around to avoid being kicked"),
COUNT_DOWN_TITLE_1("countdown-title1", "<gray>You need to move around to avoid being kicked"),
COUNT_DOWN_TITLE_2("countdown-title2", "<gray>You need to move around to avoid being kicked"),
AFK_TOGGLE_ON("afk-toggle-on", "<teal><player> is now afk."),
AFK_TOGGLE_OFF("afk-toggle-off", "<teal><player> is no longer afk."),
AFK_CHECK_TITLE("afkcheck-title", "AFK CHECK"),
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_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.");
public final String key;
public String message;
private final String key;
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getKey() {
return key;
}
Messages(String key, String... message) {
this.key = key;

View File

@ -30,7 +30,7 @@ public class MessagesConfig extends AbstractConfiguration {
private static void loadMessages() {
for (Messages message : Messages.values()) {
message.message = config.getString(message.key, message.message);
message.setMessage(config.getString(message.getKey(), message.getMessage()));
}
}
}