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; package com.alttd.afkdectector;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
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;
@ -14,73 +11,98 @@ import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; 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) { public AFKCheckTimer(AFKDetector plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
public void init() { public void init() {
runTaskTimer(plugin, 0, 20); runTaskTimer(plugin, 0, 20);
} }
@Override @Override
public void run() { public void run() {
for (UUID uuid : plugin.players.keySet()) { for (UUID uuid : plugin.players.keySet()) {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
AFKPlayer afkplayer = plugin.players.get(uuid); AFKPlayer afkPlayer = plugin.players.get(uuid);
if(player == null || player.hasPermission("afkdetector.bypass")) { if (player == null || player.hasPermission("afkdetector.bypass")) {
continue; continue;
} }
Location pastLocation = afkplayer.getplayerToSphereCenter();
if(pastLocation == null || !player.getLocation().getWorld().getName().equals(pastLocation.getWorld().getName())) { Location pastLocation = afkPlayer.getPlayerToSphereCenter();
pastLocation = player.getLocation(); if (pastLocation == null || !player.getLocation().getWorld().getName().equals(pastLocation.getWorld().getName())) {
afkplayer.setplayerToSphereCenter(pastLocation); 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); if (playerMovedOutOfSphere(player, pastLocation) && playerHeadMoved(player.getLocation(), pastLocation)) {
afkplayer.setstandingTime(System.currentTimeMillis()); resetAFKPlayer(pastLocation, player, afkPlayer);
player.setSleepingIgnored(false); continue;
//player.setCanPickupItems(true); }
plugin.AFKPlayers.removeEntry(player.getName());
afkplayer.ResetAFK(); long standingTime = afkPlayer.getStandingTime();
MessageTimer currentTimer = plugin.messageTimers.get(player.getUniqueId()); if (!afkPlayer.isAFK() && System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(Config.TOGGLE_TIME)) {
if (currentTimer != null) { setPlayerAFK(afkPlayer, player);
plugin.messageTimers.remove(player.getUniqueId()); }
} runMessageTimerCheck(afkPlayer, uuid, standingTime);
continue; }
} }
}
long standingTime = afkplayer.getstandingTime(); private boolean playerMovedOutOfSphere(Player player, Location pastLocation) {
if(!afkplayer.isafk() && System.currentTimeMillis() - standingTime > TimeUnit.MINUTES.toMillis(Config.TOGGLETIME)) { return player.getLocation().distanceSquared(pastLocation) > Config.RADIUS * Config.RADIUS;
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());
}
}
}
} }
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.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 com.alttd.afkdectector.util.Logger;
import io.papermc.paper.event.player.AsyncChatEvent;
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;
@ -18,7 +20,6 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; 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;
@ -41,11 +42,11 @@ public class AFKDetector extends JavaPlugin implements Listener{
public HashMap<UUID, MessageTimer> messageTimers = new HashMap<>(); public HashMap<UUID, MessageTimer> messageTimers = new HashMap<>();
public HashMap<UUID, Integer> PlayerAfkTime = new HashMap<>(); public HashMap<UUID, Integer> PlayerAfkTime = new HashMap<>();
public boolean fulloverride; public boolean fullOverride;
public static MiniMessage miniMessage; public static MiniMessage miniMessage;
/** /**
* afkplayers need to be added to a team. * AFK players need to be added to a team.
*/ */
Team AFKPlayers; Team AFKPlayers;
@ -55,7 +56,7 @@ public class AFKDetector extends JavaPlugin implements Listener{
instance = this; instance = this;
miniMessage = MiniMessage.miniMessage(); miniMessage = MiniMessage.miniMessage();
loadConfig(null); loadConfig(null);
settupAfkState(); setupAFKStats();
getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(this, this);
//getCommand("afk").setExecutor(new AFKCommand(this)); //getCommand("afk").setExecutor(new AFKCommand(this));
getCommand("afklist").setExecutor(new AFKListCommand(this)); getCommand("afklist").setExecutor(new AFKListCommand(this));
@ -86,12 +87,16 @@ public class AFKDetector extends JavaPlugin implements Listener{
return players.get(player.getUniqueId()); return players.get(player.getUniqueId());
} }
private void settupAfkState() { private void setupAFKStats() {
if (Bukkit.getScoreboardManager().getMainScoreboard().getTeam("AFKPlayers") == null) { if (Bukkit.getScoreboardManager().getMainScoreboard().getTeam("AFKPlayers") == null) {
AFKPlayers = Bukkit.getScoreboardManager().getMainScoreboard().registerNewTeam("AFKPlayers"); AFKPlayers = Bukkit.getScoreboardManager().getMainScoreboard().registerNewTeam("AFKPlayers");
} else { } else {
AFKPlayers = Bukkit.getScoreboardManager().getMainScoreboard().getTeam("AFKPlayers"); 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.COLLISION_RULE, Team.OptionStatus.NEVER);
//AFKPlayers.setOption(Team.Option.NAME_TAG_VISIBILITY, 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 * Get the afk time for a player
*/ */
public int getaAllowedAfktime(Player player) { public int getAllowedAFKTime(Player player) {
if(Config.SERVERFULL) { if(Config.SERVER_FULL) {
return Config.DEFAULTAFKTIME; return Config.DEFAULT_AFK_TIME;
} }
return PlayerAfkTime.get(player.getUniqueId()); return PlayerAfkTime.get(player.getUniqueId());
} }
public int getPlayerAfktime(Player player) { public int getPlayerAFKTime(Player player) {
String permissionPrefix = "afkdetector.afktime."; String permissionPrefix = "afkdetector.afktime.";
for (PermissionAttachmentInfo attachmentInfo : player.getEffectivePermissions()) { for (PermissionAttachmentInfo attachmentInfo : player.getEffectivePermissions()) {
if (attachmentInfo.getPermission().startsWith(permissionPrefix)) { if (attachmentInfo.getPermission().startsWith(permissionPrefix)) {
String perm = attachmentInfo.getPermission(); String perm = attachmentInfo.getPermission();
int Time = Integer.parseInt(perm.substring(perm.lastIndexOf(".") + 1)); int Time = Integer.parseInt(perm.substring(perm.lastIndexOf(".") + 1));
if(Time >= Config.MAXAFKTIME) { return Math.min(Time, Config.MAX_AFK_TIME);
return Config.MAXAFKTIME;
} else {
return Time;
}
} }
} }
return Config.DEFAULTAFKTIME; return Config.DEFAULT_AFK_TIME;
} }
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
PlayerAfkTime.put(uuid, getPlayerAfktime(player)); PlayerAfkTime.put(uuid, getPlayerAFKTime(player));
players.put(uuid, new AFKPlayer(player, this)); players.put(uuid, new AFKPlayer(player, this));
if(Bukkit.getOnlinePlayers().size() >= Config.PLAYERLIMIT && !Config.SERVERFULL) { if(Bukkit.getOnlinePlayers().size() >= Config.PLAYER_LIMIT && !Config.SERVER_FULL) {
fulloverride = true; fullOverride = true;
} }
long lastKick = AutoJoinTracker.getInstance().getLastKick(uuid); 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); AutoJoinTracker.getInstance().setLastKick(uuid, 0);
SuspiciousKickTracker skt = SuspiciousKickTracker.getInstance(); SuspiciousKickTracker skt = SuspiciousKickTracker.getInstance();
skt.addSuspiciousKick(uuid); skt.addSuspiciousKick(uuid);
@ -142,7 +143,7 @@ public class AFKDetector extends JavaPlugin implements Listener{
Placeholder.component("player", player.name()), Placeholder.component("player", player.name()),
Placeholder.parsed("count", "" + suspiciousKickCount) 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"); Bukkit.broadcast(component, "afkdetector.notify");
} }
} }
@ -152,14 +153,14 @@ public class AFKDetector extends JavaPlugin implements Listener{
Player player = event.getPlayer(); Player player = event.getPlayer();
// Remove the players from the timer if they logout // Remove the players from the timer if they logout
players.remove(player.getUniqueId()); players.remove(player.getUniqueId());
if(Bukkit.getOnlinePlayers().size() < Config.PLAYERLIMIT && fulloverride){ if(Bukkit.getOnlinePlayers().size() < Config.PLAYER_LIMIT && fullOverride){
fulloverride = false; fullOverride = false;
} }
} }
@EventHandler @EventHandler
public void onTalkCancel(AsyncPlayerChatEvent event) { public void onTalkCancel(AsyncChatEvent event) {
if (!Config.CHATWILLCANCEL) { if (!Config.CHAT_WILL_CANCEL) {
return; return;
} }
Player player = event.getPlayer(); Player player = event.getPlayer();
@ -167,8 +168,8 @@ public class AFKDetector extends JavaPlugin implements Listener{
} }
@EventHandler @EventHandler
public void oncommandCancel(PlayerCommandPreprocessEvent event) { public void onCommandCancel(PlayerCommandPreprocessEvent event) {
if (!Config.COMMANDWILLCANCEL) { if (!Config.COMMAND_WILL_CANCEL) {
return; return;
} }
Player player = event.getPlayer(); Player player = event.getPlayer();

View File

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

View File

@ -1,7 +1,6 @@
package com.alttd.afkdectector.afkplayer; 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.Config;
import com.alttd.afkdectector.config.Messages; import com.alttd.afkdectector.config.Messages;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@ -11,81 +10,82 @@ import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.alttd.afkdectector.AFKDetector; import java.util.UUID;
public class AFKPlayer { public class AFKPlayer {
private final String playerName; private final String playerName;
private final UUID uuid; private final UUID uuid;
private Location playerToSphereCenter; private Location playerToSphereCenter;
private long standingTime; private long standingTime;
private final int afkTime; private final int afkTime;
private boolean isafk; private boolean isAFK;
public AFKPlayer(Player player, AFKDetector plugin) { public AFKPlayer(Player player, AFKDetector plugin) {
this.playerName = player.getName(); this.playerName = player.getName();
this.uuid = player.getUniqueId(); this.uuid = player.getUniqueId();
this.playerToSphereCenter = player.getLocation(); this.playerToSphereCenter = player.getLocation();
this.standingTime = System.currentTimeMillis(); this.standingTime = System.currentTimeMillis();
this.afkTime = plugin.getaAllowedAfktime(player); this.afkTime = plugin.getAllowedAFKTime(player);
this.isafk = false; this.isAFK = false;
} }
public String getPlayerName() { public String getPlayerName() {
return this.playerName; return this.playerName;
} }
public UUID getPlayerUuid() { public UUID getPlayerUuid() {
return this.uuid; return this.uuid;
} }
public Location getplayerToSphereCenter() { public Location getPlayerToSphereCenter() {
return playerToSphereCenter; return playerToSphereCenter;
} }
public void setplayerToSphereCenter(Location playerlocation) { public void setPlayerToSphereCenter(Location playerlocation) {
playerToSphereCenter = playerlocation; playerToSphereCenter = playerlocation;
} }
public long getstandingTime() { public long getStandingTime() {
return standingTime; return standingTime;
} }
public void setstandingTime(long Time) { public void setStandingTime(long Time) {
standingTime = Time; standingTime = Time;
} }
public int getafkTime() { public int getAfkTime() {
if (isInSpawn()) if (isInSpawn())
return this.afkTime + Config.EXTRA_MIN_IN_SPAWN; return this.afkTime + Config.EXTRA_MIN_IN_SPAWN;
return this.afkTime; return this.afkTime;
} }
public boolean isInSpawn() { public boolean isInSpawn() {
double x = getplayerToSphereCenter().getX(); double x = getPlayerToSphereCenter().getX();
double z = getplayerToSphereCenter().getZ(); 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; 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) { public void setAFK(boolean bool) {
isafk = bool; isAFK = bool;
} }
public boolean isafk() { public boolean isAFK() {
return isafk; return isAFK;
} }
public void ResetAFK() { public void ResetAFK() {
if(isafk && Config.AFKTOGGLEMESSAGES) { if (isAFK && Config.AFK_TOGGLE_MESSAGES) {
TagResolver placeholders = TagResolver.resolver( TagResolver placeholders = TagResolver.resolver(
Placeholder.parsed("player", playerName) Placeholder.parsed("player", playerName)
); );
Component component = AFKDetector.miniMessage.deserialize(Messages.AFKTOGGLEOFF.getMessage(), placeholders); Component component = AFKDetector.miniMessage.deserialize(Messages.AFK_TOGGLE_OFF.getMessage(), placeholders);
Bukkit.broadcast(component, "afkdetector.notify"); Bukkit.broadcast(component, "afkdetector.notify");
} }
standingTime = System.currentTimeMillis(); standingTime = System.currentTimeMillis();
playerToSphereCenter = Bukkit.getPlayer(getPlayerUuid()).getLocation(); Player player = Bukkit.getPlayer(getPlayerUuid());
isafk = false; 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.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -22,44 +23,43 @@ import java.util.stream.Collectors;
public class AFKCheckCommand implements CommandExecutor, TabCompleter { public class AFKCheckCommand implements CommandExecutor, TabCompleter {
private AFKDetector plugin; private final AFKDetector plugin;
public AFKCheckCommand(AFKDetector plugin) { public AFKCheckCommand(AFKDetector plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (!(args.length > 0)) { if (!(args.length > 0)) {
sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED)); sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED));
return true; return true;
} }
Player target = Bukkit.getPlayer(args[0]); Player target = Bukkit.getPlayer(args[0]);
if (target == null) { if (target == null) {
sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED)); sender.sendMessage(Component.text(command.getUsage(), NamedTextColor.RED));
return true; return true;
} }
MiniMessage miniMessage = AFKDetector.miniMessage; MiniMessage miniMessage = AFKDetector.miniMessage;
target.showTitle(Title.title(miniMessage.deserialize(Messages.AFKCHECKTITLE.getMessage()), target.showTitle(Title.title(miniMessage.deserialize(Messages.AFK_CHECK_TITLE.getMessage()),
miniMessage.deserialize(Messages.AFKCHECKSUBTITLE.getMessage()))); miniMessage.deserialize(Messages.AFK_CHECK_SUBTITLE.getMessage())));
if(sender instanceof Player) { if (sender instanceof Player player) {
Player player = (Player) sender; String cmd = "msg " + args[0] + " " + Messages.AFK_CHECK_MESSAGE.getMessage();
String cmd = "msg " + args[0] + " " + Messages.AFKCHECKMESSAGE.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(sender, "msg " + args[0] + " " + Messages.AFKCHECKMESSAGE.getMessage()); }
}
return true; return true;
} }
@Override @Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) { public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) {
List<String> completions = new ArrayList<>(); List<String> completions = new ArrayList<>();
if (strings.length == 1) { if (strings.length == 1) {
StringUtil.copyPartialMatches(strings[0], plugin.players.values().stream().filter(AFKPlayer::isafk).map(AFKPlayer::getPlayerName).collect(Collectors.toList()), completions); StringUtil.copyPartialMatches(strings[0], plugin.players.values().stream().filter(AFKPlayer::isAFK).map(AFKPlayer::getPlayerName).collect(Collectors.toList()), completions);
} }
return null; return null;
} }
} }

View File

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

View File

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

View File

@ -26,56 +26,60 @@ public class Config extends AbstractConfiguration {
} }
public static boolean DEBUG_MODE = false; public static boolean DEBUG_MODE = false;
private static void settings() { private static void settings() {
DEBUG_MODE = config.getBoolean("debug-mode", DEBUG_MODE); 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 RADIUS = 4;
public static int TOGGLETIME = 4; public static int TOGGLE_TIME = 4;
public static int DEFAULTAFKTIME = 5; public static int DEFAULT_AFK_TIME = 5;
public static int MAXAFKTIME = 5; public static int MAX_AFK_TIME = 5;
public static boolean SERVERFULL = false; public static boolean SERVER_FULL = false;
public static int PLAYERLIMIT = Math.round(Bukkit.getMaxPlayers() * 90 / 100); public static int PLAYER_LIMIT = Math.round(Bukkit.getMaxPlayers() * 90 / 100);
public static int COMMANDCOOLDOWWN = 60; public static int COMMAND_COOL_DOWN = 60;
public static boolean AFKTOGGLEMESSAGES = true; public static boolean AFK_TOGGLE_MESSAGES = true;
public static boolean NOTIFYSTAFFONAFKKIC = true; public static boolean NOTIFY_STAFF_ON_AFK_KICK = true;
public static int MAXREJOINFORTRACKING = 30; public static int MAX_REJOIN_FOR_TRACKING = 30;
private static void playerSettings() { private static void playerSettings() {
SLEEPIGNORE = config.getBoolean("player.sleep", SLEEPIGNORE); SLEEP_IGNORE = config.getBoolean("player.sleep", SLEEP_IGNORE);
RADIUS = config.getInt("player.radius", RADIUS); RADIUS = config.getInt("player.radius", RADIUS);
TOGGLETIME = config.getInt("player.toggle-time", TOGGLETIME); TOGGLE_TIME = config.getInt("player.toggle-time", TOGGLE_TIME);
DEFAULTAFKTIME = config.getInt("player.afk-time", 5); DEFAULT_AFK_TIME = config.getInt("player.afk-time", 5);
MAXAFKTIME = config.getInt("player.maxafk-time", 5); MAX_AFK_TIME = config.getInt("player.maxafk-time", 5);
SERVERFULL = config.getBoolean("player.serverfull" ,false); SERVER_FULL = config.getBoolean("player.serverfull", false);
COMMANDCOOLDOWWN = config.getInt("player.commandcooldown", COMMANDCOOLDOWWN); COMMAND_COOL_DOWN = config.getInt("player.commandcooldown", COMMAND_COOL_DOWN);
AFKTOGGLEMESSAGES = config.getBoolean("player.afk-toggle-messages", AFKTOGGLEMESSAGES); AFK_TOGGLE_MESSAGES = config.getBoolean("player.afk-toggle-messages", AFK_TOGGLE_MESSAGES);
NOTIFYSTAFFONAFKKIC = config.getBoolean("player.notify-staff-on-afk-kick", NOTIFYSTAFFONAFKKIC); NOTIFY_STAFF_ON_AFK_KICK = config.getBoolean("player.notify-staff-on-afk-kick", NOTIFY_STAFF_ON_AFK_KICK);
MAXREJOINFORTRACKING = config.getInt("tracking.max-seconds-for-tracking", MAXREJOINFORTRACKING); 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 FADEIN = 10;
public static int STAY = 50; public static int STAY = 50;
public static int FADEOUt = 10; public static int FADEOUT = 10;
public static int MESSAGEDELAY = 15; public static int MESSAGE_DELAY = 15;
public static int MESSAGEREPEATS = 15; public static int MESSAGE_REPEATS = 15;
public static String KICKCOMMAND = "kickfrombungee %player% &cYou have been afk for %afktime% minutes."; public static String KICK_COMMAND = "kickfrombungee %player% &cYou have been afk for %afktime% minutes.";
private static void countdownSettigns() {
COUNTDOWNENABLED = config.getBoolean("countdown.enabled" ,COUNTDOWNENABLED); private static void countdownSettings() {
COUNT_DOWN_ENABLED = config.getBoolean("countdown.enabled", COUNT_DOWN_ENABLED);
FADEIN = config.getInt("countdown.fadein", FADEIN); FADEIN = config.getInt("countdown.fadein", FADEIN);
STAY = config.getInt("countdown.stay", STAY); STAY = config.getInt("countdown.stay", STAY);
FADEOUt = config.getInt("countdown.fadeout", FADEOUt); FADEOUT = config.getInt("countdown.fadeout", FADEOUT);
MESSAGEDELAY = config.getInt("countdown.message-delay", MESSAGEDELAY); MESSAGE_DELAY = config.getInt("countdown.message-delay", MESSAGE_DELAY);
MESSAGEREPEATS = config.getInt("countdown.message-repeats", MESSAGEREPEATS); MESSAGE_REPEATS = config.getInt("countdown.message-repeats", MESSAGE_REPEATS);
KICKCOMMAND = config.getString("countdown.kick-command", KICKCOMMAND); KICK_COMMAND = config.getString("countdown.kick-command", KICK_COMMAND);
} }
public static boolean CHATWILLCANCEL = true; public static boolean CHAT_WILL_CANCEL = true;
public static boolean COMMANDWILLCANCEL = true; public static boolean COMMAND_WILL_CANCEL = true;
private static void eventSettigns() {
CHATWILLCANCEL = config.getBoolean("events.chat", CHATWILLCANCEL); private static void eventSettings() {
COMMANDWILLCANCEL = config.getBoolean("events.commands", COMMANDWILLCANCEL); 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; 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_MAX_Z = 250;
public static int SPAWN_MIN_Z = -250; public static int SPAWN_MIN_Z = -250;
public static int EXTRA_MIN_IN_SPAWN = 10; public static int EXTRA_MIN_IN_SPAWN = 10;
private static void spawnSettings() { private static void spawnSettings() {
SPAWN_MAX_X = config.getInt("spawn.max-x", SPAWN_MAX_X); SPAWN_MAX_X = config.getInt("spawn.max-x", SPAWN_MAX_X);
SPAWN_MIN_X = config.getInt("spawn.min-x", SPAWN_MIN_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 { public enum Messages {
TITLE("title-name", "<red>[<white>AFKDetector</white>]</red> "), 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_PLAYER("invalid-args", "<red>Invalid args!usage: -p:playername"),
INVALID_REASON("invalid-reason" , "<red>Invalid args! usage: -r:reason"), INVALID_REASON("invalid-reason" , "<red>Invalid args! usage: -r:reason"),
NOT_ONLINE("player-notonline", "<red>Invalid args! player not online"), 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("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_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]"), AFK_PREFIX("afk-prefix", "[AFK]"),
COUNTDOWNMESSAGE("countdown-message", "<gray>You need to move around to avoid being kicked"), COUNT_DOWN_MESSAGE("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"), COUNT_DOWN_TITLE_1("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"), COUNT_DOWN_TITLE_2("countdown-title2", "<gray>You need to move around to avoid being kicked"),
AFKTOGGLEON("afk-toggle-on", "<teal><player> is now afk."), AFK_TOGGLE_ON("afk-toggle-on", "<teal><player> is now afk."),
AFKTOGGLEOFF("afk-toggle-off", "<teal><player> is no longer afk."), AFK_TOGGLE_OFF("afk-toggle-off", "<teal><player> is no longer afk."),
AFKCHECKTITLE("afkcheck-title", "AFK CHECK"), AFK_CHECK_TITLE("afkcheck-title", "AFK CHECK"),
AFKCHECKSUBTITLE("afkcheck-subtitle", "Please respond to the dm from staff!"), AFK_CHECK_SUBTITLE("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."), 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."),
AFKICKSTAFFMESSAGE("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."),
SUSPICIOUSKICKCOUNT("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.");
public final String key; private final String key;
public String message; private String message;
public void setMessage(String message) {
this.message = message;
}
public String getKey() {
return key;
}
Messages(String key, String... message) { Messages(String key, String... message) {
this.key = key; this.key = key;

View File

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