diff --git a/pom.xml b/pom.xml index 18babb6e..039afeb0 100644 --- a/pom.xml +++ b/pom.xml @@ -410,14 +410,10 @@ - commons-io:commons-io - org.apache.commons:commons-lang3 org.reflections:reflections - org.javassist:javassist io.papermc:paperlib org.bstats:bstats-bukkit org.bstats:bstats-base - org.jetbrains:annotations diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java b/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java index ecefb7dd..676517b1 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java @@ -2,8 +2,8 @@ package me.totalfreedom.totalfreedommod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; -import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.ChatColor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -35,10 +35,10 @@ public class AntiNuke extends FreedomService if (fPlayer.incrementAndGetBlockDestroyCount() > ConfigEntry.NUKE_MONITOR_COUNT_BREAK.getInteger()) { - FUtil.bcastMsg(player.getName() + " is breaking blocks too fast!", ChatColor.RED); - //plugin.ae.autoEject(player, "You are breaking blocks too fast. Nukers are not permitted on this server."); - player.kickPlayer(ChatColor.RED + "You are breaking blocks too fast. Nukers are not permitted on this server."); - + server.broadcast(Component.text(player.getName()).append(Component.text(" is breaking blocks too fast!")) + .color(NamedTextColor.RED)); + player.kick(Component.text("You are breaking blocks too fast. Nukers are not permitted on this server.", + NamedTextColor.RED)); fPlayer.resetBlockDestroyCount(); event.setCancelled(true); @@ -58,10 +58,9 @@ public class AntiNuke extends FreedomService if (fPlayer.incrementAndGetBlockPlaceCount() > ConfigEntry.NUKE_MONITOR_COUNT_PLACE.getInteger()) { - FUtil.bcastMsg(player.getName() + " is placing blocks too fast!", ChatColor.RED); - //plugin.ae.autoEject(player, "You are placing blocks too fast."); - player.kickPlayer(ChatColor.RED + "You are placing blocks too fast."); - + server.broadcast(Component.text(player.getName()).append(Component.text(" is placing blocks too fast!")) + .color(NamedTextColor.RED)); + player.kick(Component.text("You are placing blocks too fast.", NamedTextColor.RED)); fPlayer.resetBlockPlaceCount(); event.setCancelled(true); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java b/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java index 2e0a2bc0..7cf69fdf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java @@ -2,60 +2,48 @@ package me.totalfreedom.totalfreedommod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; -import me.totalfreedom.totalfreedommod.util.FSync; -import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.ChatColor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; public class AntiSpam extends FreedomService { - + private ScheduledThreadPoolExecutor cycle; public static final int MSG_PER_CYCLE = 8; - public static final int TICKS_PER_CYCLE = 2 * 10; // - public BukkitTask cycleTask = null; private Map muteCounts = new HashMap<>(); @Override public void onStart() { - new BukkitRunnable() - { - - @Override - public void run() - { - cycle(); - } - }.runTaskTimer(plugin, TICKS_PER_CYCLE, TICKS_PER_CYCLE); + cycle = new ScheduledThreadPoolExecutor(1); + cycle.scheduleAtFixedRate(this::cycle, 0, 1, TimeUnit.SECONDS); } @Override public void onStop() { - FUtil.cancel(cycleTask); + cycle.shutdownNow(); } private void cycle() { - for (Player player : server.getOnlinePlayers()) + server.getOnlinePlayers().stream().map(player -> plugin.pl.getPlayer(player)).forEach(fPlayer -> { - final FPlayer playerdata = plugin.pl.getPlayer(player); - // TODO: Move each to their own section - playerdata.resetMsgCount(); - playerdata.resetBlockDestroyCount(); - playerdata.resetBlockPlaceCount(); - } + fPlayer.resetMsgCount(); + fPlayer.resetBlockDestroyCount(); + fPlayer.resetBlockPlaceCount(); + }); } @EventHandler(priority = EventPriority.LOW) @@ -81,17 +69,16 @@ public class AntiSpam extends FreedomService int time = count * minutes; playerdata.setMuted(true, time); - FSync.bcastMsg(String.format("%s has automatically been muted for %d minutes for spamming chat.", - player.getName(), - time), - ChatColor.RED); + server.broadcast(Component.text(player.getName()).append(Component.text(" has been automatically muted for ")) + .append(Component.text(time)).append(Component.text(" minutes for spamming chat.")) + .color(NamedTextColor.RED)); playerdata.resetMsgCount(); event.setCancelled(true); } else if (playerdata.incrementAndGetMsgCount() > MSG_PER_CYCLE / 2) { - FUtil.playerMsg(player, "Please refrain from spamming chat.", ChatColor.GRAY); + player.sendMessage(Component.text("Please refrain from spamming chat.", NamedTextColor.GRAY)); event.setCancelled(true); } @@ -107,7 +94,7 @@ public class AntiSpam extends FreedomService if (fPlayer.allCommandsBlocked()) { - FUtil.playerMsg(player, "Your commands have been blocked by an admin.", ChatColor.RED); + player.sendMessage(Component.text("Your commands have been blocked by an admin.", NamedTextColor.RED)); event.setCancelled(true); return; } @@ -119,7 +106,9 @@ public class AntiSpam extends FreedomService if (fPlayer.incrementAndGetMsgCount() > MSG_PER_CYCLE) { - FUtil.bcastMsg(player.getName() + " was automatically kicked for spamming commands.", ChatColor.RED); + server.broadcast(Component.text(player.getName()) + .append(Component.text(" was automatically kicked for spamming commands.")) + .color(NamedTextColor.RED)); plugin.ae.autoEject(player, "Kicked for spamming commands."); fPlayer.resetMsgCount(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java b/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java index 2e84035a..46ff03bb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java @@ -91,7 +91,7 @@ public class AutoEject extends FreedomService } case STRIKE_THREE: { - plugin.bm.addBan(Ban.forPlayerFuzzy(player, Bukkit.getConsoleSender(), null, kickMessage)); + plugin.bm.addBan(Ban.forPlayer(player, Bukkit.getConsoleSender(), null, kickMessage)); FUtil.bcastMsg(ChatColor.RED + player.getName() + " has been banned."); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java b/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java index fd8c3d8d..116a4beb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java @@ -4,13 +4,11 @@ import com.google.common.base.Strings; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; -import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Displayable; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FSync; import me.totalfreedom.totalfreedommod.util.FUtil; import net.md_5.bungee.api.ChatColor; -import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.command.CommandSender; @@ -54,17 +52,6 @@ public class ChatManager extends FreedomService message = FUtil.colorize(message); message = message.replaceAll(ChatColor.MAGIC.toString(), "&k"); - if (ConfigEntry.SHOP_ENABLED.getBoolean() && ConfigEntry.SHOP_REACTIONS_ENABLED.getBoolean() && !plugin.sh.reactionString.isEmpty() && message.equals(plugin.sh.reactionString)) - { - event.setCancelled(true); - PlayerData data = plugin.pl.getData(player); - data.setCoins(data.getCoins() + plugin.sh.coinsPerReactionWin); - plugin.pl.save(data); - plugin.sh.endReaction(player.getName()); - player.sendMessage(ChatColor.GREEN + "You have been given " + ChatColor.GOLD + plugin.sh.coinsPerReactionWin + ChatColor.GREEN + " coins!"); - return; - } - if (!ConfigEntry.TOGGLE_CHAT.getBoolean() && !plugin.al.isAdmin(player)) { event.setCancelled(true); @@ -96,10 +83,11 @@ public class ChatManager extends FreedomService } // Check for 4chan trigger - boolean green = ChatColor.stripColor(message).toLowerCase().startsWith(">"); - boolean orange = ChatColor.stripColor(message).toLowerCase().endsWith("<"); if (ConfigEntry.FOURCHAN_ENABLED.getBoolean()) { + boolean green = ChatColor.stripColor(message).toLowerCase().startsWith(">"); + boolean orange = ChatColor.stripColor(message).toLowerCase().endsWith("<"); + if (green) { message = ChatColor.GREEN + message; @@ -123,23 +111,27 @@ public class ChatManager extends FreedomService } // Check for mentions - boolean mentionEveryone = ChatColor.stripColor(message).toLowerCase().contains("@everyone") && plugin.al.isAdmin(player); - for (Player p : server.getOnlinePlayers()) + String stripped = ChatColor.stripColor(message).toLowerCase(); + + /* There is an issue would have allowed muted players to ping players. The issue is caused by the order in which + * these event handlers are registered when the plugin starts up. Muter is registered after the ChatManager, + * which results in latter being called first (before the former can cancel it). EventPriority does not seem to + * make a difference. As a short-term solution I've added this mute check alongside the usual isCancelled check + * so that the issue is mitigated, but a long-term solution should be to change the order in which things like + * ChatManager and Muter are registered. */ + if (!event.isCancelled() && !plugin.pl.getPlayer(player).isMuted()) { - if (ChatColor.stripColor(message).toLowerCase().contains("@" + p.getName().toLowerCase()) || mentionEveryone) + server.getOnlinePlayers().forEach(pl -> { - p.playSound(p.getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, SoundCategory.MASTER, 1337F, 0.9F); - } + if (stripped.contains("@" + pl.getName()) || (plugin.al.isAdmin(player) && stripped.contains("@everyone"))) + { + pl.playSound(pl.getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, SoundCategory.MASTER, 1337F, 0.9F); + } + }); } // Set format event.setFormat(format); - - // Send to discord - if (!ConfigEntry.ADMIN_ONLY_MODE.getBoolean() && !Bukkit.hasWhitelist() && !plugin.pl.getPlayer(player).isMuted()) - { - plugin.dc.messageChatChannel(player.getName() + " \u00BB " + ChatColor.stripColor(message)); - } } public ChatColor getColor(Displayable display) @@ -162,7 +154,8 @@ public class ChatManager extends FreedomService server.getOnlinePlayers().stream().filter(player -> plugin.al.isAdmin(player)).forEach(player -> { Admin admin = plugin.al.getAdmin(player); - if (!Strings.isNullOrEmpty(admin.getAcFormat())) { + if (!Strings.isNullOrEmpty(admin.getAcFormat())) + { String format = admin.getAcFormat(); ChatColor color = getColor(display); String msg = format.replace("%name%", sender.getName()).replace("%rank%", display.getAbbr()).replace("%rankcolor%", color.toString()).replace("%msg%", message); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/CommandSpy.java b/src/main/java/me/totalfreedom/totalfreedommod/CommandSpy.java index 30d39f0f..5d2730d6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/CommandSpy.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/CommandSpy.java @@ -1,7 +1,7 @@ package me.totalfreedom.totalfreedommod; -import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.entity.Player; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerCommandPreprocessEvent; @@ -21,15 +21,9 @@ public class CommandSpy extends FreedomService @EventHandler(priority = EventPriority.MONITOR) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - for (Player player : server.getOnlinePlayers()) - { - if (plugin.al.isAdmin(player) && plugin.al.getAdmin(player).getCommandSpy()) - { - if (player != event.getPlayer()) - { - FUtil.playerMsg(player, event.getPlayer().getName() + ": " + event.getMessage()); - } - } - } + server.getOnlinePlayers().stream().filter(player -> plugin.al.isAdmin(player) + && plugin.al.getAdmin(player).getCommandSpy() && player != event.getPlayer()).forEach(player -> + player.sendMessage(Component.text(event.getPlayer().getName()).append(Component.text(": ")) + .append(Component.text(event.getMessage())))); } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java b/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java deleted file mode 100644 index 1c302f99..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java +++ /dev/null @@ -1,201 +0,0 @@ -package me.totalfreedom.totalfreedommod; - -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.util.FLog; -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -public class LogViewer extends FreedomService -{ - @Override - public void onStart() - { - } - - @Override - public void onStop() - { - } - - public void updateLogsRegistration(final CommandSender sender, final Player target, final LogsRegistrationMode mode) - { - updateLogsRegistration(sender, target.getName(), mode); - } - - public void updateLogsRegistration(final CommandSender sender, final String targetName, final LogsRegistrationMode mode) - { - final String logsRegisterUrl = ConfigEntry.LOGS_URL.getString(); - final String logsRegisterPassword = ConfigEntry.LOGS_SECRET.getString(); - - if (logsRegisterUrl == null || logsRegisterPassword == null || logsRegisterUrl.isEmpty() || logsRegisterPassword.isEmpty()) - { - return; - } - - new BukkitRunnable() - { - @Override - public void run() - { - try - { - if (sender != null) - { - sender.sendMessage(ChatColor.YELLOW + "Connecting..."); - } - - final String key = SecureCodeGenerator.generateCode(20); - - final URL urlAdd = new URLBuilder(logsRegisterUrl) - .addQueryParameter("mode", mode.name()) - .addQueryParameter("password", logsRegisterPassword) - .addQueryParameter("name", targetName) - .addQueryParameter("key", key) - .getURL(); - - final HttpURLConnection connection = (HttpURLConnection)urlAdd.openConnection(); - connection.setConnectTimeout(1000 * 5); - connection.setReadTimeout(1000 * 5); - connection.setUseCaches(false); - connection.setRequestMethod("HEAD"); - - final int responseCode = connection.getResponseCode(); - - if (sender != null) - { - if (!plugin.isEnabled()) - { - return; - } - - new BukkitRunnable() - { - @Override - public void run() - { - if (responseCode == 200) - { - if (mode == LogsRegistrationMode.ADD) - { - String link = null; - try - { - final URL urlVerify = new URLBuilder(logsRegisterUrl) - .addQueryParameter("mode", LogsRegistrationMode.VERIFY.name()) - .addQueryParameter("name", targetName) - .addQueryParameter("key", key) - .getURL(); - link = urlVerify.toString(); - } - catch (Exception ex) - { - FLog.severe(ex); - } - - sender.sendMessage(ChatColor.GREEN + "Open this link to verify your logviewer registration:\n" + ChatColor.DARK_GREEN + link); - } - else - { - sender.sendMessage(ChatColor.GREEN + "Logviewer access revoked successfully."); - } - } - else - { - sender.sendMessage(ChatColor.RED + "Error contacting logs registration server."); - } - } - }.runTask(plugin); - } - } - catch (Exception ex) - { - FLog.severe(ex); - } - } - }.runTaskAsynchronously(plugin); - } - - public enum LogsRegistrationMode - { - - ADD, DELETE, VERIFY - } - - private static class URLBuilder - { - - private final String requestPath; - private final Map queryStringMap = new HashMap<>(); - - private URLBuilder(String requestPath) - { - this.requestPath = requestPath; - } - - public URLBuilder addQueryParameter(String key, String value) - { - queryStringMap.put(key, value); - return this; - } - - public URL getURL() throws MalformedURLException - { - List pairs = new ArrayList<>(); - for (Map.Entry pair : queryStringMap.entrySet()) - { - try - { - pairs.add(URLEncoder.encode(pair.getKey(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8")); - } - catch (UnsupportedEncodingException ex) - { - FLog.severe(ex); - } - } - - return new URL(requestPath + "?" + StringUtils.join(pairs, "&")); - } - } - - private static class SecureCodeGenerator - { - - private static final String CHARACTER_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - - public static String generateCode(final int length) - { - SecureRandom random; - try - { - random = SecureRandom.getInstance("SHA1PRNG", "SUN"); - } - catch (NoSuchAlgorithmException | NoSuchProviderException ex) - { - random = new SecureRandom(); - FLog.severe(ex); - } - - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) - { - sb.append(CHARACTER_SET.charAt(random.nextInt(CHARACTER_SET.length()))); - } - return sb.toString(); - } - } -} diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Muter.java b/src/main/java/me/totalfreedom/totalfreedommod/Muter.java index c6b336ae..270b848c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/Muter.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/Muter.java @@ -1,11 +1,11 @@ package me.totalfreedom.totalfreedommod; -import java.util.ArrayList; -import java.util.List; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FSync; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.entity.Player; @@ -13,13 +13,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerJoinEvent; public class Muter extends FreedomService { - - public final List MUTED_PLAYERS = new ArrayList<>(); - @Override public void onStart() { @@ -45,11 +41,10 @@ public class Muter extends FreedomService if (plugin.al.isAdminSync(player)) { fPlayer.setMuted(false); - MUTED_PLAYERS.remove(player.getName()); return; } - FSync.playerMsg(event.getPlayer(), ChatColor.RED + "You are muted."); + player.sendMessage(Component.text("You are muted.", NamedTextColor.RED)); event.setCancelled(true); } @@ -87,7 +82,7 @@ public class Muter extends FreedomService if (ConfigEntry.MUTED_BLOCKED_COMMANDS.getStringList().contains(cmdName)) { - player.sendMessage(ChatColor.RED + "That command is blocked while you are muted."); + player.sendMessage(Component.text("That command is blocked while you are muted.", NamedTextColor.RED)); event.setCancelled(true); return; } @@ -98,16 +93,4 @@ public class Muter extends FreedomService FLog.info(String.format("[PREPROCESS_COMMAND] %s(%s): %s", player.getName(), ChatColor.stripColor(player.getDisplayName()), message), true); } } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerJoin(PlayerJoinEvent event) - { - Player player = event.getPlayer(); - FPlayer playerdata = plugin.pl.getPlayer(player); - - if (MUTED_PLAYERS.contains(player.getName())) - { - playerdata.setMuted(true); - } - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java b/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java deleted file mode 100644 index 75b2e548..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java +++ /dev/null @@ -1,214 +0,0 @@ -package me.totalfreedom.totalfreedommod; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import com.google.common.base.Strings; -import me.totalfreedom.totalfreedommod.admin.Admin; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.util.FLog; -import me.totalfreedom.totalfreedommod.util.FUtil; -import me.totalfreedom.totalfreedommod.util.Response; -import org.json.simple.JSONObject; -import org.json.simple.parser.ParseException; - -public class Pterodactyl extends FreedomService -{ - - public final String URL = ConfigEntry.PTERO_URL.getString(); - private final String SERVER_KEY = ConfigEntry.PTERO_SERVER_KEY.getString(); - private final String ADMIN_KEY = ConfigEntry.PTERO_ADMIN_KEY.getString(); - private final List SERVER_HEADERS = Arrays.asList("Accept:Application/vnd.pterodactyl.v1+json", "Content-Type:application/json", "Authorization:Bearer " + SERVER_KEY); - private final List ADMIN_HEADERS = Arrays.asList("Accept:Application/vnd.pterodactyl.v1+json", "Content-Type:application/json", "Authorization:Bearer " + ADMIN_KEY); - - private boolean enabled = !Strings.isNullOrEmpty(URL); - - public void onStart() - { - } - - public void onStop() - { - } - - public void updateAccountStatus(Admin admin) - { - String id = admin.getPteroID(); - - if (Strings.isNullOrEmpty(id) || !enabled) - { - return; - } - - if (!admin.isActive() || admin.getRank() != Rank.SENIOR_ADMIN) - { - FLog.debug("Disabling ptero acc"); - removeAccountFromServer(id); - return; - } - - FLog.debug("Enabling ptero acc"); - addAccountToServer(id); - } - - @SuppressWarnings("unchecked") - public String createAccount(String username, String password) - { - JSONObject json = new JSONObject(); - json.put("username", username); - json.put("password", password); - json.put("email", username.toLowerCase() + "@" + ConfigEntry.PTERO_DEFAULT_EMAIL_DOMAIN.getString()); - json.put("first_name", username); - json.put("last_name", "\u200E"); // required, so I made it appear empty - - Response response; - JSONObject jsonResponse; - try - { - response = FUtil.sendRequest(URL + "/api/application/users", "POST", ADMIN_HEADERS, json.toJSONString()); - jsonResponse = response.getJSONMessage(); - } - catch (IOException | ParseException e) - { - FLog.severe(e); - return null; - } - - return ((JSONObject)jsonResponse.get("attributes")).get("id").toString(); - - } - - public boolean deleteAccount(String id) - { - JSONObject json = new JSONObject(); - try - { - return FUtil.sendRequest(URL + "/api/application/users/" + id, "DELETE", ADMIN_HEADERS, json.toJSONString()).getCode() == 204; - } - catch (IOException e) - { - FLog.severe(e); - return false; - } - } - - @SuppressWarnings("unchecked") - public void addAccountToServer(String id) - { - String url = URL + "/api/client/servers/" + ConfigEntry.PTERO_SERVER_UUID.getString() + "/users"; - - JSONObject userData = getUserData(id); - if (userData == null) - { - FLog.severe("The Pterodactyl user with the ID of " + id + " was not found"); - return; - } - - JSONObject json = new JSONObject(); - json.put("email", userData.get("email").toString()); - json.put("permissions", Arrays.asList("control.console", "control.start", "control.restart", "control.stop", "control.kill")); - - try - { - FUtil.sendRequest(url, "POST", SERVER_HEADERS, json.toJSONString()); - } - catch (IOException e) - { - FLog.severe(e); - } - } - - public void removeAccountFromServer(String id) - { - JSONObject userData = getUserData(id); - if (userData == null) - { - FLog.severe("The Pterodactyl user with the ID of " + id + " was not found"); - return; - } - - String url = URL + "/api/client/servers/" + ConfigEntry.PTERO_SERVER_UUID.getString() + "/users/" + userData.get("uuid"); - - try - { - FUtil.sendRequest(url, "DELETE", SERVER_HEADERS, null); - } - catch (IOException e) - { - FLog.severe(e); - } - } - - public JSONObject getUserData(String id) - { - Response response; - JSONObject jsonResponse; - try - { - response = FUtil.sendRequest(URL + "/api/application/users/" + id, "GET", ADMIN_HEADERS, null); - jsonResponse = response.getJSONMessage(); - - } - catch (IOException | ParseException e) - { - FLog.severe(e); - return null; - } - - return (JSONObject)jsonResponse.get("attributes"); - - } - - // API patch function on users doesnt work rn, it throws 500 errors, so it's probably not written yet - @SuppressWarnings("unchecked") - public void setPassword(String id, String password) - { - JSONObject json = new JSONObject(); - json.put("password", password); - - try - { - FUtil.sendRequest(URL + "/api/application/users/" + id, "PATCH", ADMIN_HEADERS, json.toJSONString()); - } - catch (IOException e) - { - FLog.severe(e); - } - } - - public String getURL() - { - return URL; - } - - public String getServerKey() - { - return SERVER_KEY; - } - - public String getAdminKey() - { - return ADMIN_KEY; - } - - public List getServerHeaders() - { - return SERVER_HEADERS; - } - - public List getAdminHeaders() - { - return ADMIN_HEADERS; - } - - public boolean isEnabled() - { - return enabled; - } - - public void setEnabled(boolean enabled) - { - this.enabled = enabled; - } -} \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java index d18fb0b9..9517e4dd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java @@ -72,7 +72,6 @@ public class TotalFreedomMod extends JavaPlugin public CommandLoader cl; // Services public WorldManager wm; - public LogViewer lv; public AdminList al; public ActivityLog acl; public RankManager rm; @@ -119,7 +118,6 @@ public class TotalFreedomMod extends JavaPlugin public WorldRestrictions wr; public EntityWiper ew; public VanishHandler vh; - public Pterodactyl ptero; // // Bridges public BukkitTelnetBridge btb; @@ -284,7 +282,6 @@ public class TotalFreedomMod extends JavaPlugin { // Start services wm = new WorldManager(); - lv = new LogViewer(); sql = new SQLite(); al = new AdminList(); acl = new ActivityLog(); @@ -312,7 +309,6 @@ public class TotalFreedomMod extends JavaPlugin gr = new GameRuleHandler(); ew = new EntityWiper(); vh = new VanishHandler(); - ptero = new Pterodactyl(); } private void initAdminUtils() diff --git a/src/main/java/me/totalfreedom/totalfreedommod/VanishHandler.java b/src/main/java/me/totalfreedom/totalfreedommod/VanishHandler.java index 7d1e586d..8e62c11c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/VanishHandler.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/VanishHandler.java @@ -1,6 +1,8 @@ package me.totalfreedom.totalfreedommod; import me.totalfreedom.totalfreedommod.util.FLog; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; @@ -13,7 +15,6 @@ import org.bukkit.scheduler.BukkitRunnable; public class VanishHandler extends FreedomService { - @Override public void onStart() { @@ -29,40 +30,32 @@ public class VanishHandler extends FreedomService { Player player = event.getPlayer(); - for (Player p : server.getOnlinePlayers()) - { - if (!plugin.al.isAdmin(player) && plugin.al.isVanished(p.getName())) - { - player.hidePlayer(plugin, p); - } - } + server.getOnlinePlayers().stream().filter(pl -> !plugin.al.isAdmin(player) + && plugin.al.isVanished(pl.getUniqueId())).forEach(pl -> player.hidePlayer(plugin, pl)); - for (Player p : server.getOnlinePlayers()) - { - if (!plugin.al.isAdmin(p) && plugin.al.isVanished(player.getName())) - { - p.hidePlayer(plugin, player); - } - } + server.getOnlinePlayers().stream().filter(pl -> !plugin.al.isAdmin(pl) + && plugin.al.isVanished(player.getUniqueId())).forEach(pl -> pl.hidePlayer(plugin, player)); - if (plugin.al.isVanished(player.getName())) + if (plugin.al.isVanished(player.getUniqueId())) { plugin.esb.setVanished(player.getName(), true); FLog.info(player.getName() + " joined while still vanished."); plugin.al.messageAllAdmins(ChatColor.YELLOW + player.getName() + " has joined silently."); - event.setJoinMessage(null); + event.joinMessage(null); new BukkitRunnable() { @Override public void run() { - if (!plugin.al.isVanished(player.getName())) + if (plugin.al.isVanished(player.getUniqueId())) + { + player.sendActionBar(Component.text("You are hidden from other players.").color(NamedTextColor.GOLD)); + } + else { this.cancel(); } - - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(ChatColor.GOLD + "You are hidden from other players.")); } }.runTaskTimer(plugin, 0L, 4L); } @@ -73,9 +66,9 @@ public class VanishHandler extends FreedomService { Player player = event.getPlayer(); - if (plugin.al.isVanished(player.getName())) + if (plugin.al.isVanished(player.getUniqueId())) { - event.setQuitMessage(null); + event.quitMessage(null); FLog.info(player.getName() + " left while still vanished."); plugin.al.messageAllAdmins(ChatColor.YELLOW + player.getName() + " has left silently."); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java index 535b5cd3..c3353d32 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java @@ -4,7 +4,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; -import me.totalfreedom.totalfreedommod.LogViewer.LogsRegistrationMode; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -25,7 +24,6 @@ public class Admin private Boolean commandSpy = false; private Boolean potionSpy = false; private String acFormat = null; - private String pteroID = null; public Admin(Player player) { @@ -46,7 +44,6 @@ public class Admin this.commandSpy = resultSet.getBoolean("command_spy"); this.potionSpy = resultSet.getBoolean("potion_spy"); this.acFormat = resultSet.getString("ac_format"); - this.pteroID = resultSet.getString("ptero_id"); } catch (SQLException e) { @@ -65,8 +62,7 @@ public class Admin .append("- Rank: ").append(rank.getName()).append("\n") .append("- Is Active: ").append(active).append("\n") .append("- Potion Spy: ").append(potionSpy).append("\n") - .append("- Admin Chat Format: ").append(acFormat).append("\n") - .append("- Pterodactyl ID: ").append(pteroID).append("\n"); + .append("- Admin Chat Format: ").append(acFormat).append("\n"); return output.toString(); } @@ -83,7 +79,6 @@ public class Admin put("command_spy", commandSpy); put("potion_spy", potionSpy); put("ac_format", acFormat); - put("ptero_id", pteroID); }}; return map; } @@ -188,8 +183,6 @@ public class Admin } } - - plugin.lv.updateLogsRegistration(null, getName(), LogsRegistrationMode.DELETE); } } @@ -247,14 +240,4 @@ public class Admin { this.acFormat = acFormat; } - - public String getPteroID() - { - return pteroID; - } - - public void setPteroID(String pteroID) - { - this.pteroID = pteroID; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java index 8073713c..84ec6d15 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java @@ -17,7 +17,7 @@ import org.bukkit.entity.Player; public class AdminList extends FreedomService { - public static final List vanished = new ArrayList<>(); + public static final List vanished = new ArrayList<>(); private final Set allAdmins = Sets.newHashSet(); // Includes disabled admins // Only active admins below private final Set activeAdmins = Sets.newHashSet(); @@ -25,11 +25,6 @@ public class AdminList extends FreedomService private final Map nameTable = Maps.newHashMap(); private final Map ipTable = Maps.newHashMap(); - public static List getVanished() - { - return vanished; - } - @Override public void onStart() { @@ -99,16 +94,6 @@ public class AdminList extends FreedomService return isAdmin(sender); } - public List getActiveAdminNames() - { - List names = new ArrayList(); - for (Admin admin : activeAdmins) - { - names.add(admin.getName()); - } - return names; - } - public boolean isAdmin(CommandSender sender) { if (!(sender instanceof Player)) @@ -321,9 +306,9 @@ public class AdminList extends FreedomService updateTables(); } - public boolean isVanished(String player) + public boolean isVanished(UUID uuid) { - return vanished.contains(player); + return vanished.contains(uuid); } public Set getAllAdmins() diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java index 42871f45..90c63c5b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java @@ -121,17 +121,6 @@ public class Ban reason); } - public static Ban forPlayerFuzzy(Player player, CommandSender by, Date expiry, String reason) - { - return new Ban(player.getName(), - player.getUniqueId(), - FUtil.getFuzzyIp(FUtil.getIp(player)), - by.getName(), - Date.from(Instant.now()), - expiry, - reason); - } - public static SimpleDateFormat getDateFormat() { return DATE_FORMAT; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java index 03b6465a..23e60e58 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.banning; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.sql.ResultSet; @@ -14,7 +13,6 @@ import java.util.Map; import java.util.Set; import java.util.UUID; import me.totalfreedom.totalfreedommod.FreedomService; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.entity.Player; @@ -30,8 +28,6 @@ public class BanManager extends FreedomService private final Map nameBans = Maps.newHashMap(); private final Map uuidBans = Maps.newHashMap(); private final Map ipBans = Maps.newHashMap(); - private final List unbannableUsernames = Lists.newArrayList(); - // @Override @@ -70,11 +66,6 @@ public class BanManager extends FreedomService updateViews(); FLog.info("Loaded " + ipBans.size() + " IP bans and " + nameBans.size() + " username bans."); - - // Load unbannable usernames - unbannableUsernames.clear(); - unbannableUsernames.addAll(ConfigEntry.FAMOUS_PLAYERS.getStringList()); - FLog.info("Loaded " + unbannableUsernames.size() + " unbannable usernames."); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java index 492deea9..03fe28d9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java @@ -1,14 +1,10 @@ package me.totalfreedom.totalfreedommod.blocking; -import java.util.List; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.util.Groups; import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.block.Banner; import org.bukkit.block.Skull; -import org.bukkit.block.banner.Pattern; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -187,17 +183,5 @@ public class BlockBlocker extends FreedomService break; } } - - if (Groups.BANNERS.contains(event.getBlockPlaced().getType())) - { - Banner banner = (Banner)event.getBlockPlaced().getState(); - List patterns = banner.getPatterns(); - - if (patterns.size() >= 2) - { - banner.setPatterns(patterns.subList(0, 2)); - player.sendMessage(ChatColor.GRAY + "Your banner had too many patterns on it, so some were removed."); - } - } } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java index bc2ec9ba..a70fce45 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java @@ -163,12 +163,9 @@ public class EventBlocker extends FreedomService if (ConfigEntry.ENABLE_PET_PROTECT.getBoolean()) { Entity entity = event.getEntity(); - if (entity instanceof Tameable) + if (entity instanceof Tameable tameable && tameable.isTamed()) { - if (((Tameable) entity).isTamed()) - { - event.setCancelled(true); - } + event.setCancelled(true); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java index 2074f3e5..514de44e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java @@ -203,12 +203,9 @@ public class CommandBlocker extends FreedomService } // Validate sub command - if (entry.getSubCommand() != null) + if (entry.getSubCommand() != null && (subCommand == null || !subCommand.startsWith(entry.getSubCommand()))) { - if (subCommand == null || !subCommand.startsWith(entry.getSubCommand())) - { - return false; - } + return false; } if (entry.getRank().hasPermission(sender)) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java index d9e75846..95aa5a7b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java @@ -90,7 +90,10 @@ public class BukkitTelnetBridge extends FreedomService playerTags.put("tfm.playerdata.getTag", plugin.pl.getPlayer(player).getTag()); - playerTags.put("tfm.essentialsBridge.getNickname", plugin.esb.getNickname(player.getName())); + if (server.getPluginManager().isPluginEnabled("Essentials")) + { + playerTags.put("tfm.essentialsBridge.getNickname", plugin.esb.getNickname(player.getName())); + } } } @@ -101,12 +104,9 @@ public class BukkitTelnetBridge extends FreedomService try { final Plugin bukkitTelnet = server.getPluginManager().getPlugin("BukkitTelnet"); - if (bukkitTelnet != null) + if (bukkitTelnet instanceof BukkitTelnet) { - if (bukkitTelnet instanceof BukkitTelnet) - { - bukkitTelnetPlugin = (BukkitTelnet)bukkitTelnet; - } + bukkitTelnetPlugin = (BukkitTelnet)bukkitTelnet; } } catch (Exception ex) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java index 2653c8ef..f5ba0c7a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java @@ -1,81 +1,58 @@ package me.totalfreedom.totalfreedommod.bridge; -import java.io.File; -import java.sql.*; -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; +import java.util.concurrent.CompletableFuture; + import me.totalfreedom.totalfreedommod.FreedomService; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import net.coreprotect.CoreProtect; import net.coreprotect.CoreProtectAPI; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.World; +import net.coreprotect.utility.Util; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; public class CoreProtectBridge extends FreedomService { - public static Map> HISTORY_MAP = new HashMap<>(); - private final List tables = Arrays.asList("co_sign", "co_session", "co_container", "co_block"); + //-- Block Inspector --// + private static final Component name = Component.text("Block Inspector").color(TextColor.color(0x30ade4)); + private static final Component header = Component.text("---- ").append(name) + .append(Component.text(" ---- ")).colorIfAbsent(NamedTextColor.WHITE); + private static final Component prefix = name.append(Component.text(" - ").color(NamedTextColor.WHITE)) + .colorIfAbsent(NamedTextColor.WHITE); + //-- + private final HashMap cooldownMap = new HashMap<>(); + private HashMap> historyMap; - private final HashMap cooldown = new HashMap<>(); + //---------------------// private CoreProtectAPI coreProtectAPI = null; - private BukkitTask wiper; public static Long getSecondsLeft(long prevTime, int timeAdd) { return prevTime / 1000L + timeAdd - System.currentTimeMillis() / 1000L; } - // Unix timestamp converter taken from Functions class in CoreProtect, not my code - public static String getTimeAgo(int logTime, int currentTime) - { - StringBuilder message = new StringBuilder(); - double timeSince = (double)currentTime - ((double)logTime + 0.0D); - timeSince /= 60.0D; - if (timeSince < 60.0D) - { - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/m ago"); - } - - if (message.length() == 0) - { - timeSince /= 60.0D; - if (timeSince < 24.0D) - { - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/h ago"); - } - } - - if (message.length() == 0) - { - timeSince /= 24.0D; - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/d ago"); - } - - return message.toString(); - } - @Override public void onStart() { + if (isEnabled()) + { + historyMap = new HashMap<>(); + } } @Override @@ -88,7 +65,7 @@ public class CoreProtectBridge extends FreedomService CoreProtect coreProtect = null; try { - final Plugin coreProtectPlugin = Bukkit.getServer().getPluginManager().getPlugin("CoreProtect"); + final Plugin coreProtectPlugin = server.getPluginManager().getPlugin("CoreProtect"); assert coreProtectPlugin != null; if (coreProtectPlugin instanceof CoreProtect) { @@ -129,6 +106,11 @@ public class CoreProtectBridge extends FreedomService public boolean isEnabled() { + if (!server.getPluginManager().isPluginEnabled("CoreProtect")) + { + return false; + } + final CoreProtect coreProtect = getCoreProtect(); return coreProtect != null && coreProtect.isEnabled(); @@ -137,13 +119,13 @@ public class CoreProtectBridge extends FreedomService // Rollback the specified player's edits that were in the last 24 hours. public void rollback(final String name) { - final CoreProtectAPI coreProtect = getCoreProtectAPI(); - if (!isEnabled()) { return; } + final CoreProtectAPI coreProtect = getCoreProtectAPI(); + new BukkitRunnable() { @Override @@ -157,13 +139,13 @@ public class CoreProtectBridge extends FreedomService // Reverts a rollback for the specified player's edits that were in the last 24 hours. public void restore(final String name) { - final CoreProtectAPI coreProtect = getCoreProtectAPI(); - if (!isEnabled()) { return; } + final CoreProtectAPI coreProtect = getCoreProtectAPI(); + new BukkitRunnable() { @Override @@ -174,264 +156,182 @@ public class CoreProtectBridge extends FreedomService }.runTaskAsynchronously(plugin); } - public File getDatabase() + public boolean hasHistory(Player player) { - if (!isEnabled()) - { - return null; - } - - return (new File(getCoreProtect().getDataFolder(), "database.db")); + return historyMap.containsKey(player.getUniqueId()); } - public double getDBSize() + public FUtil.PaginationList getHistoryForPlayer(Player player) { - double bytes = getDatabase().length(); - double kilobytes = (bytes / 1024); - double megabytes = (kilobytes / 1024); - return (megabytes / 1024); + return historyMap.get(player.getUniqueId()); } - public void clearDatabase(World world) + public void showPageToPlayer(Player player, FUtil.PaginationList results, int pageNum) { - clearDatabase(world, false); - } - - // Wipes DB for the specified world - public void clearDatabase(World world, Boolean shutdown) - { - if (!ConfigEntry.COREPROTECT_MYSQL_ENABLED.getBoolean()) - { - return; - } - final CoreProtect coreProtect = getCoreProtect(); - - if (coreProtect == null) + if (player == null || !player.isOnline()) { return; } - /* As CoreProtect doesn't have an API method for deleting all of the data for a specific world - we have to do this manually via SQL */ - Connection connection; - try + List page = results.getPage(pageNum); + + if (page == null || page.isEmpty()) { - String host = ConfigEntry.COREPROTECT_MYSQL_HOST.getString(); - String port = ConfigEntry.COREPROTECT_MYSQL_PORT.getString(); - String username = ConfigEntry.COREPROTECT_MYSQL_USERNAME.getString(); - String password = ConfigEntry.COREPROTECT_MYSQL_PASSWORD.getString(); - String database = ConfigEntry.COREPROTECT_MYSQL_DATABASE.getString(); - String url = host + ":" + port + "/" + database + "?user=" + username + "&password=" + password + "&useSSL=false"; - connection = DriverManager.getConnection("jdbc:sql://" + url); - final PreparedStatement statement = connection.prepareStatement("SELECT id FROM co_world WHERE world = ?"); - statement.setQueryTimeout(30); - - // Obtain world ID from CoreProtect database - statement.setString(1, world.getName()); - ResultSet resultSet = statement.executeQuery(); - String worldID = null; - while (resultSet.next()) - { - worldID = String.valueOf(resultSet.getInt("id")); - } - - // Ensure the world ID is not null - - if (worldID == null) - { - FLog.warning("Failed to obtain the world ID for the " + world.getName()); - return; - } - - // Iterate through each table and delete their data if the world ID matches - for (String table : tables) - { - final PreparedStatement statement1 = connection.prepareStatement("DELETE FROM ? WHERE wid = ?"); - statement1.setString(1, table); - statement1.setString(2, worldID); - statement1.executeQuery(); - } - - connection.close(); - + player.sendMessage(prefix.append(Component.text("No results were found.", NamedTextColor.WHITE))); } - catch (SQLException e) + else { - FLog.warning("Failed to delete the CoreProtect data for the " + world.getName()); + // This shouldn't change at all in any of the other entries, so this should be safe + Component location = Component.text(String.format("(%s, %s, %s)", results.get(0).getX(), + results.get(0).getY(), results.get(0).getZ())); + final long time = System.currentTimeMillis() / 1000; + + player.sendMessage(header.append(location.color(NamedTextColor.GRAY).decorate(TextDecoration.ITALIC))); + page.forEach(entry -> + { + TextComponent.Builder line = Component.text(); + + // Time + line.append(Component.text(Util.getTimeSince(entry.getTime(), time, false)) + .color(NamedTextColor.GRAY)); + + // Action + Component action = Component.text(" interacted with "); + Component symbol = Component.text(" - ", NamedTextColor.WHITE); + switch (entry.getActionId()) + { + case 0 -> + { + action = Component.text(" broke "); + symbol = Component.text(" - ", NamedTextColor.RED); + } + case 1 -> + { + action = Component.text(" placed "); + symbol = Component.text(" + ", NamedTextColor.GREEN); + } + case 2 -> action = Component.text(" clicked "); + default -> + { + // Do nothing (shuts Codacy up) + } + } + // Symbol, player, action, block + line.append(symbol).append(Component.text(entry.getPlayer()).color(TextColor.color(0x30ade4))) + .append(action.color(NamedTextColor.WHITE)).append( + Component.text(entry.getBlockData().getMaterial().name().toLowerCase()) + .color(TextColor.color(0x30ade4))); + + // Rolled back? + if (entry.isRolledBack()) + { + line.decorate(TextDecoration.STRIKETHROUGH); + } + + player.sendMessage(line.append(Component.text(".", NamedTextColor.WHITE)).build()); + }); + + if (results.getPageCount() > 1) + { + player.sendMessage(Component.text("-----", NamedTextColor.WHITE)); + + // Page indicator + TextComponent.Builder indicator = Component.text(); + + // <- + if (pageNum > 1) + { + indicator.append(Component.text("◀ ", NamedTextColor.WHITE).clickEvent( + ClickEvent.runCommand("/ins history " + (pageNum - 1)))); + } + + // Page / + indicator.append(Component.text("Page ", TextColor.color(0x30ade4)).append(Component.text(pageNum + "/" + + results.getPageCount(), NamedTextColor.WHITE))); + + // -> + if (pageNum < results.getPageCount()) + { + indicator.append(Component.text(" ▶", NamedTextColor.WHITE).clickEvent( + ClickEvent.runCommand("/ins history " + (pageNum + 1)))); + } + + // | Use /ins history for advanced navigation + indicator.append(Component.text(" | ", NamedTextColor.GRAY).append(Component.text("Use ", NamedTextColor.WHITE) + .append(Component.text("/ins history ", TextColor.color(0x30ade4)) + .clickEvent(ClickEvent.suggestCommand("/ins history "))) + .append(Component.text(" for advanced navigation", NamedTextColor.WHITE)))); + + player.sendMessage(indicator.build()); + } } } + public CompletableFuture> lookupForPlayer(Block block, Player player) + { + cooldownMap.put(player.getUniqueId(), System.currentTimeMillis()); + CoreProtectAPI api = getCoreProtectAPI(); + + return CompletableFuture.supplyAsync(() -> + { + historyMap.remove(player.getUniqueId()); + FUtil.PaginationList pages = new FUtil.PaginationList<>(10); + api.blockLookup(block, -1).forEach(stringArray -> pages.add(api.parseResult(stringArray))); + historyMap.put(player.getUniqueId(), pages); + return pages; + }); + } + @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerInteract(PlayerInteractEvent event) + public void onInteract(PlayerInteractEvent event) { - Player player = event.getPlayer(); - PlayerData data = plugin.pl.getData(player); - Block block = event.getClickedBlock(); - final CoreProtectAPI coreProtect = getCoreProtectAPI(); - - // TODO: Rewrite this - if (data.hasInspection()) + // The inspector only works if we have CoreProtect installed + if (!isEnabled()) { - int cooldownTime = 3; + return; + } - // Cooldown check - if ((event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK) - && cooldown.containsKey(player.getName())) + Player player = event.getPlayer(); + + if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK) + && plugin.pl.getData(player.getUniqueId()).hasInspection()) + { + event.setCancelled(true); + Block block = event.getClickedBlock(); + Optional cooldown = Optional.ofNullable(cooldownMap.get(player.getUniqueId())); + + if (cooldown.isPresent() && getSecondsLeft(cooldown.get(), 3) > 0L) { - long secondsLeft = getSecondsLeft(cooldown.get(player.getName()), cooldownTime); - if (secondsLeft > 0L) - { - event.setCancelled(true); - player.sendMessage(ChatColor.RED + String.valueOf(secondsLeft) + " seconds left before next query."); - return; - } + player.sendMessage(prefix.append(Component.text("You need to wait ") + .append(Component.text(getSecondsLeft(cooldown.get(), 3))) + .append(Component.text(" seconds before you can make another query.")) + .color(NamedTextColor.WHITE))); + return; } - // Actual lookup time - if (event.getAction() == Action.LEFT_CLICK_BLOCK) + // Time to do a look-up. + if (block != null) { - if (block != null) + /* This is a hack to make it so that when you right-click, the coordinates that get used depend on + * what's in your hand. Non-blocks use the block you clicked directly, but blocks use wherever the + * block was supposed to be placed. */ + ItemStack hand = player.getInventory().getItemInMainHand(); + if (event.getAction() == Action.RIGHT_CLICK_BLOCK && hand.getType().isBlock() && hand.getType() != Material.AIR) { - event.setCancelled(true); - List lookup = coreProtect.blockLookup(block, -1); - - if (!plugin.al.isAdmin(player)) - { - cooldown.put(player.getName(), System.currentTimeMillis()); - } - - if (lookup != null) - { - if (lookup.isEmpty()) - { - player.sendMessage(net.md_5.bungee.api.ChatColor.of("#30ade4") + "Block Inspector " + ChatColor.WHITE + "- " + "No block data found for this location"); - return; - } - - HISTORY_MAP.remove(event.getPlayer()); - HISTORY_MAP.put(event.getPlayer(), new FUtil.PaginationList<>(10)); - FUtil.PaginationList paged = HISTORY_MAP.get(event.getPlayer()); - - player.sendMessage("---- " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "Block Inspector" + ChatColor.WHITE + " ---- " + - ChatColor.GRAY + "(x" + block.getX() + "/" + "y" + block.getY() + "/" + "z" + block.getZ() + ")"); - - for (String[] value : lookup) - { - CoreProtectAPI.ParseResult result = coreProtect.parseResult(value); - BlockData bl = result.getBlockData(); - - String s; - String st = ""; - - if (result.getActionString().equals("Placement")) - { - s = " placed "; - } - else if (result.getActionString().equals("Removal")) - { - s = " broke "; - } - else - { - s = " interacted with "; - } - - if (result.isRolledBack()) - { - st += "§m"; - } - - int time = (int)(System.currentTimeMillis() / 1000L); - - paged.add(ChatColor.GRAY + getTimeAgo(result.getTime(), time) + ChatColor.WHITE + " - " + net.md_5.bungee.api.ChatColor.of("#30ade4") + - st + result.getPlayer() + ChatColor.WHITE + st + s + net.md_5.bungee.api.ChatColor.of("#30ade4") + st + bl.getMaterial().toString().toLowerCase()); - } - - List page = paged.getPage(1); - for (String entries : page) - { - player.sendMessage(entries); - } - - player.sendMessage("Page 1/" + paged.getPageCount() + " | To index through the pages, type " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "/ins history "); - } + block = block.getRelative(event.getBlockFace()).getState().getBlock(); } - } - else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) - { - if (block != null) + + lookupForPlayer(block, player).thenAccept(results -> { - BlockState blockState = block.getRelative(event.getBlockFace()).getState(); - Block placedBlock = blockState.getBlock(); - event.setCancelled(true); - List lookup = coreProtect.blockLookup(placedBlock, -1); - - if (lookup.isEmpty()) + if (results.isEmpty()) { - lookup = coreProtect.blockLookup(block, -1); + player.sendMessage(prefix.append(Component.text("No results were found.").color(NamedTextColor.WHITE))); } - - if (!plugin.al.isAdmin(player)) + else { - cooldown.put(player.getName(), System.currentTimeMillis()); + showPageToPlayer(player, results, 1); } - - if (lookup != null) - { - if (lookup.isEmpty()) - { - player.sendMessage(net.md_5.bungee.api.ChatColor.of("#30ade4") + "Block Inspector " + ChatColor.WHITE + "- " + "No block data found for this location"); - return; - } - - HISTORY_MAP.remove(event.getPlayer()); - HISTORY_MAP.put(event.getPlayer(), new FUtil.PaginationList<>(10)); - FUtil.PaginationList paged = HISTORY_MAP.get(event.getPlayer()); - - player.sendMessage("---- " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "Block Inspector" + ChatColor.WHITE + " ---- " + - ChatColor.GRAY + "(x" + block.getX() + "/" + "y" + block.getY() + "/" + "z" + block.getZ() + ")"); - - for (String[] value : lookup) - { - CoreProtectAPI.ParseResult result = coreProtect.parseResult(value); - BlockData bl = result.getBlockData(); - - String s; - String st = ""; - - if (result.getActionString().equals("Placement")) - { - s = " placed "; - } - else if (result.getActionString().equals("Removal")) - { - s = " broke "; - } - else - { - s = " interacted with "; - } - - if (result.isRolledBack()) - { - st += "§m"; - } - - int time = (int)(System.currentTimeMillis() / 1000L); - - paged.add(ChatColor.GRAY + getTimeAgo(result.getTime(), time) + ChatColor.WHITE + " - " + net.md_5.bungee.api.ChatColor.of("#30ade4") + - st + result.getPlayer() + ChatColor.WHITE + st + s + net.md_5.bungee.api.ChatColor.of("#30ade4") + st + bl.getMaterial().toString().toLowerCase()); - } - - List page = paged.getPage(1); - for (String entries : page) - { - player.sendMessage(entries); - } - - player.sendMessage("Page 1/" + paged.getPageCount() + " | To index through the pages, type " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "/ins history "); - } - } + }); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java index 56e2937d..8764c915 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java @@ -204,13 +204,6 @@ public class EssentialsBridge extends FreedomService } } - // TODO: Actually use this for something or remove it. - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerQuit(PlayerQuitEvent event) - { - Player player = event.getPlayer(); - } - public boolean isEnabled() { final Essentials ess = getEssentialsPlugin(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminmode.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminmode.java index 83415650..51ebb4f1 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminmode.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminmode.java @@ -6,6 +6,7 @@ import java.util.List; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; +import net.kyori.adventure.text.Component; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -33,13 +34,8 @@ public class Command_adminmode extends FreedomCommand { ConfigEntry.ADMIN_ONLY_MODE.setBoolean(true); FUtil.adminAction(sender.getName(), "Closing the server to non-admins", true); - for (Player player : server.getOnlinePlayers()) - { - if (!isAdmin(player)) - { - player.kickPlayer("Server is now closed to non-admins."); - } - } + server.getOnlinePlayers().stream().filter(player -> !isAdmin(player)).forEach(player -> + player.kick(Component.text("The server is now closed to non-admins."))); return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java index 6a7697d7..3e6610eb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java @@ -1,30 +1,21 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.rank.Rank; +import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.attribute.Attribute; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.Arrays; @CommandPermissions(level = Rank.OP, source = SourceType.BOTH) @CommandParameters(description = "Lists all possible attributes.", usage = "/") public class Command_attributelist extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - StringBuilder list = new StringBuilder("All possible attributes: "); - - for (Attribute attribute : Attribute.values()) - { - list.append(attribute.name()).append(", "); - } - - // Remove extra comma at the end of the list - list = new StringBuilder(list.substring(0, list.length() - 2)); - - msg(list.toString()); + msg("All possible attributes: " + FUtil.listToString(Arrays.stream(Attribute.values()).map(Enum::name).toList())); return true; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_blockedit.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_blockedit.java index cba22999..9a32d157 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_blockedit.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_blockedit.java @@ -5,134 +5,106 @@ import me.totalfreedom.totalfreedommod.punishments.Punishment; import me.totalfreedom.totalfreedommod.punishments.PunishmentType; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.List; +import java.util.Optional; + @CommandPermissions(level = Rank.ADMIN, source = SourceType.BOTH) -@CommandParameters(description = "Restricts/unrestricts block modification abilities for everyone on the server or a certain player.", usage = "/ [[-s] [reason] | list | purge | all]") +@CommandParameters(description = "Restricts/restores block modification abilities for everyone on the server or a certain player.", usage = "/ [ [reason] | list | purge | all]") public class Command_blockedit extends FreedomCommand { - @Override public boolean run(final CommandSender sender, final Player playerSender, final Command cmd, final String commandLabel, String[] args, final boolean senderIsConsole) { - if (args.length == 0) + if (args.length > 0) { - return false; - } - - if (args[0].equals("list")) - { - msg("The following have block modification abilities restricted:"); - int count = 0; - for (Player player : server.getOnlinePlayers()) + switch (args[0].toLowerCase()) { - final FPlayer info = plugin.pl.getPlayer(player); - if (info.isEditBlocked()) + case "list" -> { - msg("- " + player.getName()); - ++count; + List list = server.getOnlinePlayers().stream().filter(player -> + plugin.pl.getPlayer(player).isEditBlocked()).sorted().toList(); + + // Oh dear god, why do I have to do it like this? + msg("There " + (list.size() != 1 ? "are " : "is ") + list.size() + " player" + + (list.size() != 1 ? "s" : "") + " online with restricted block modification abilities" + + (list.size() > 0 ? ":" : ".")); + + list.forEach(player -> msg("- " + player.getName())); } - } - - if (count == 0) - { - msg("- none"); - } - return true; - } - - if (args[0].equals("purge")) - { - FUtil.adminAction(sender.getName(), "Unblocking block modification abilities for all players", true); - int count = 0; - for (final Player player : this.server.getOnlinePlayers()) - { - final FPlayer info = plugin.pl.getPlayer(player); - if (info.isEditBlocked()) + case "purge" -> { - info.setEditBlocked(false); - ++count; - } - } - msg("Unblocked all block modification abilities for " + count + " players."); - return true; - } + FUtil.adminAction(sender.getName(), "Restoring block modification abilities for all players", true); - if (args[0].equals("all")) - { - FUtil.adminAction(sender.getName(), "Blocking block modification abilities for all non-admins", true); - int counter = 0; - for (final Player player : this.server.getOnlinePlayers()) - { - if (!plugin.al.isAdmin(player)) + List list = server.getOnlinePlayers().stream().filter(player -> + plugin.pl.getPlayer(player).isEditBlocked()).toList(); + + list.forEach(player -> + { + plugin.pl.getPlayer(player).setEditBlocked(false); + msg(player, "Your block modification abilities have been restored.", ChatColor.GREEN); + }); + + msg("Restored block modification abilities for " + list.size() + " player" + + (list.size() != 1 ? "s" : "") + "."); + } + case "all", "-a" -> { - final FPlayer playerdata = plugin.pl.getPlayer(player); - playerdata.setEditBlocked(true); - ++counter; + FUtil.adminAction(sender.getName(), "Restricting block modification abilities for all non-admins", true); + + List list = server.getOnlinePlayers().stream().filter(player -> + !plugin.al.isAdmin(player)).toList(); + + list.forEach(player -> + { + plugin.pl.getPlayer(player).setEditBlocked(true); + msg(player, "Your block modification abilities have been restricted.", ChatColor.RED); + }); + + msg("Restricted block modification abilities for " + list.size() + " player" + + (list.size() != 1 ? "s" : "") + "."); } + default -> Optional.ofNullable(getPlayer(args[0])).ifPresentOrElse(player -> + { + FPlayer fPlayer = plugin.pl.getPlayer(player); + + if (fPlayer.isEditBlocked()) + { + FUtil.adminAction(sender.getName(), "Restoring block modification abilities for " + player.getName(), true); + fPlayer.setEditBlocked(false); + msg("Restored block modification abilities for " + player.getName() + "."); + msg(player, "Your block modification abilities have been restored.", ChatColor.GREEN); + } + else + { + if (plugin.al.isAdmin(player)) + { + msg(player.getName() + " is an admin, and as such cannot have their block modification abilities restricted.", ChatColor.RED); + } + else + { + FUtil.adminAction(sender.getName(), "Restricting block modification abilities for " + player.getName(), true); + fPlayer.setEditBlocked(true); + msg("Restricted block modification abilities for " + player.getName() + "."); + msg(player, "Your block modification abilities have been restricted.", ChatColor.RED); + + plugin.pul.logPunishment(new Punishment(player.getName(), FUtil.getIp(player), + sender.getName(), PunishmentType.BLOCKEDIT, null)); + } + } + + }, () -> msg(PLAYER_NOT_FOUND)); } - msg("Blocked block modification abilities for " + counter + " players."); return true; } - - final boolean smite = args[0].equals("-s"); - if (smite) - { - args = (String[])ArrayUtils.subarray(args, 1, args.length); - if (args.length < 1) - { - return false; - } - } - - final Player player2 = getPlayer(args[0]); - if (player2 == null) - { - msg(PLAYER_NOT_FOUND); - return true; - } - - String reason = null; - if (args.length > 1) - { - reason = StringUtils.join(args, " ", 1, args.length); - } - - final FPlayer pd = plugin.pl.getPlayer(player2); - if (pd.isEditBlocked()) - { - FUtil.adminAction(sender.getName(), "Unblocking block modification abilities for " + player2.getName(), true); - pd.setEditBlocked(false); - msg("Unblocking block modification abilities for " + player2.getName()); - msg(player2, "Your block modification abilities have been restored.", ChatColor.RED); - } else { - if (plugin.al.isAdmin(player2)) - { - msg(player2.getName() + " is an admin, and cannot have their block edits blocked."); - return true; - } - - FUtil.adminAction(sender.getName(), "Blocking block modification abilities for " + player2.getName(), true); - pd.setEditBlocked(true); - - if (smite) - { - Command_smite.smite(sender, player2, reason); - } - - msg(player2, "Your block modification abilities have been blocked.", ChatColor.RED); - msg("Blocked all block modification abilities for " + player2.getName()); - - plugin.pul.logPunishment(new Punishment(player2.getName(), FUtil.getIp(player2), sender.getName(), PunishmentType.BLOCKEDIT, null)); + return false; } - return true; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cage.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cage.java index c7992547..ddcc6ed0 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cage.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cage.java @@ -21,7 +21,7 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Place a cage around someone with certain blocks, or someone's player head.", usage = "/ [head | block] [playername | blockname]") public class Command_cage extends FreedomCommand { - + @Override public boolean run(final CommandSender sender, final Player playerSender, final Command cmd, final String commandLabel, final String[] args, final boolean senderIsConsole) { if (args.length == 0) @@ -33,11 +33,8 @@ public class Command_cage extends FreedomCommand if (args[0].equalsIgnoreCase("purge")) { FUtil.adminAction(sender.getName(), "Uncaging all players", true); - for (Player player : server.getOnlinePlayers()) - { - final FPlayer fPlayer = plugin.pl.getPlayer(player); - fPlayer.getCageData().setCaged(false); - } + server.getOnlinePlayers().stream().map(player -> plugin.pl.getPlayer(player)).forEach(fPlayer -> + fPlayer.getCageData().setCaged(false)); return true; } @@ -62,7 +59,7 @@ public class Command_cage extends FreedomCommand final String s = args[1]; switch (s) { - case "head": + case "head" -> { outerMaterial = Material.PLAYER_HEAD; if (args.length >= 3) @@ -73,9 +70,8 @@ public class Command_cage extends FreedomCommand { outerMaterial = Material.SKELETON_SKULL; } - break; } - case "block": + case "block" -> { if (args.length >= 3) { @@ -85,7 +81,6 @@ public class Command_cage extends FreedomCommand if (Material.matchMaterial(args[2]) != null && Material.matchMaterial(args[2]).isBlock()) { outerMaterial = Material.matchMaterial(args[2]); - break; } else { @@ -98,7 +93,7 @@ public class Command_cage extends FreedomCommand return false; } } - default: + default -> { return false; } @@ -156,7 +151,7 @@ public class Command_cage extends FreedomCommand { if (args[1].equals("block")) { - return FUtil.getAllMaterialNames(); + return Arrays.stream(Material.values()).map(Enum::name).toList(); } else if (args[1].equals("head")) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cleanchat.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cleanchat.java index 6bcf50ed..96b5c172 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cleanchat.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cleanchat.java @@ -10,20 +10,17 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Clears the chat.", usage = "/", aliases = "cc") public class Command_cleanchat extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - for (Player player : server.getOnlinePlayers()) + server.getOnlinePlayers().stream().filter(player -> !plugin.al.isAdmin(player)).forEach(player -> { - if (!plugin.al.isAdmin(player)) + for (int i = 0; i < 100; i++) { - for (int i = 0; i < 100; i++) - { - msg(player, ""); - } + msg(player, ""); } - } + }); + FUtil.adminAction(sender.getName(), "Cleared chat", true); return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java index ea0e0b3d..067389ed 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java @@ -3,6 +3,9 @@ package me.totalfreedom.totalfreedommod.command; import java.util.Arrays; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; @@ -15,20 +18,19 @@ import org.bukkit.inventory.meta.ItemMeta; @CommandParameters(description = "Get a stick of happiness.", usage = "/") public class Command_debugstick extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { ItemStack itemStack = new ItemStack(Material.DEBUG_STICK); ItemMeta itemMeta = itemStack.getItemMeta(); assert itemMeta != null; - itemMeta.setDisplayName(ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "Stick of Happiness"); - List lore = Arrays.asList( - ChatColor.RED + "This is the most powerful stick in the game.", - ChatColor.DARK_BLUE + "You can left click to select what you want to change.", - ChatColor.DARK_GREEN + "And then you can right click to change it!", - ChatColor.DARK_PURPLE + "Isn't technology amazing?"); - itemMeta.setLore(lore); + itemMeta.displayName(Component.text("Stick of Happiness", NamedTextColor.GOLD).decorate(TextDecoration.BOLD)); + itemMeta.lore(Arrays.asList( + Component.text("This is the most powerful stick in the game.", NamedTextColor.RED), + Component.text("You can left click to select what you want to change.", NamedTextColor.DARK_BLUE), + Component.text("And then you can right click to change it!", NamedTextColor.DARK_GREEN), + Component.text("Isn't technology amazing?", NamedTextColor.DARK_PURPLE) + )); itemStack.setItemMeta(itemMeta); playerSender.getInventory().addItem(itemStack); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_denick.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_denick.java index cc90c8f2..259e1ade 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_denick.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_denick.java @@ -21,12 +21,7 @@ public class Command_denick extends FreedomCommand } FUtil.adminAction(sender.getName(), "Removing all nicknames", false); - - for (Player player : server.getOnlinePlayers()) - { - plugin.esb.setNickname(player.getName(), null); - } - + server.getOnlinePlayers().forEach(player -> plugin.esb.setNickname(player.getName(), null)); return true; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deop.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deop.java index 1cdddbe6..19057d23 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deop.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deop.java @@ -32,16 +32,14 @@ public class Command_deop extends FreedomCommand final List matchedPlayerNames = new ArrayList<>(); for (Player player : server.getOnlinePlayers()) { - if (player.getName().toLowerCase().contains(targetName) || player.getDisplayName().toLowerCase().contains(targetName) - || player.getName().contains(targetName) || player.getDisplayName().contains(targetName)) + if ((player.getName().toLowerCase().contains(targetName) || player.getDisplayName().toLowerCase().contains(targetName) + || player.getName().contains(targetName) || player.getDisplayName().contains(targetName)) && + player.isOp() && !plugin.al.isVanished(player.getUniqueId())) { - if (player.isOp() && !plugin.al.isVanished(player.getName())) - { - matchedPlayerNames.add(player.getName()); - player.setOp(false); - msg(player, YOU_ARE_NOT_OP); - plugin.rm.updateDisplay(player); - } + matchedPlayerNames.add(player.getName()); + player.setOp(false); + msg(player, YOU_ARE_NOT_OP); + plugin.rm.updateDisplay(player); } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java index 8e6f4187..22a7461b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java @@ -52,7 +52,6 @@ public class Command_doom extends FreedomCommand admin.setActive(false); plugin.al.save(admin); plugin.al.updateTables(); - plugin.ptero.updateAccountStatus(admin); if (plugin.dc.enabled && ConfigEntry.DISCORD_ROLE_SYNC.getBoolean()) { Discord.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID()); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java index b6d154b6..6700cc7f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.stream.IntStream; + import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.ChatColor; @@ -19,18 +21,6 @@ import org.bukkit.inventory.ItemStack; @CommandParameters(description = "Enchant items.", usage = "/ [level] | remove >") public class Command_enchant extends FreedomCommand { - - public static List stringNumberRange(int min, int max) - { - List range = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - range.add(String.valueOf(i)); - } - - return range; - } - @SuppressWarnings("deprecation") @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) @@ -73,30 +63,23 @@ public class Command_enchant extends FreedomCommand } else if (args[0].equalsIgnoreCase("addall")) { - for (Enchantment ench : Enchantment.values()) + Arrays.stream(Enchantment.values()).filter(enchantment -> enchantment.canEnchantItem(item)).forEach(ench -> { try { - if (ench.canEnchantItem(item)) - { - item.addEnchantment(ench, ench.getMaxLevel()); - } + item.addEnchantment(ench, ench.getMaxLevel()); } catch (Exception ex) { msg("Could not add enchantment: " + ench.getName()); } - } + }); msg("Added all possible enchantments for this item."); } else if (args[0].equalsIgnoreCase("reset")) { - for (Enchantment ench : item.getEnchantments().keySet()) - { - item.removeEnchantment(ench); - } - + item.getEnchantments().keySet().forEach(item::removeEnchantment); msg("Removed all enchantments."); } else @@ -251,21 +234,18 @@ public class Command_enchant extends FreedomCommand return getEnchantments(item); } } - else if (args.length == 3) + else if (args.length == 3 && args[0].equals("add")) { - if (args[0].equals("add")) + Enchantment enchantment = Enchantment.getByName(args[1].toUpperCase()); + if (enchantment != null) { - Enchantment enchantment = Enchantment.getByName(args[1].toUpperCase()); - if (enchantment != null) + if (!unsafe) { - if (!unsafe) - { - return stringNumberRange(1, enchantment.getMaxLevel()); - } - else - { - return Collections.singletonList("[level]"); - } + return IntStream.rangeClosed(1, enchantment.getMaxLevel()).mapToObj(String::valueOf).toList(); + } + else + { + return Collections.singletonList("[level]"); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_inspect.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_inspect.java index 87ab52a1..ea019c00 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_inspect.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_inspect.java @@ -1,23 +1,30 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Collections; import java.util.List; -import me.totalfreedom.totalfreedommod.bridge.CoreProtectBridge; +import java.util.Optional; +import java.util.stream.IntStream; + import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @CommandPermissions(level = Rank.OP, source = SourceType.ONLY_IN_GAME) -@CommandParameters(description = "Block inspector tool for operators", usage = "/ [history] ", aliases = "ins") +@CommandParameters(description = "Block inspector tool for operators.", usage = "/ [history] [page]", aliases = "ins") public class Command_inspect extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { + if (!plugin.cpb.isEnabled()) + { + msg("CoreProtect is not enabled on this server."); + return true; + } + if (args.length == 0) { PlayerData playerData = plugin.pl.getData(playerSender); @@ -39,31 +46,40 @@ public class Command_inspect extends FreedomCommand } catch (NumberFormatException e) { - msg("Invalid number", ChatColor.RED); - } - } - - FUtil.PaginationList paged = CoreProtectBridge.HISTORY_MAP.get(playerSender); - if (paged != null) - { - if (pageIndex < 1 || pageIndex > paged.getPageCount()) - { - msg("Not a valid page number", ChatColor.RED); + msg("Invalid number.", ChatColor.RED); return true; } - - msg("---- " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "Block Inspector" + ChatColor.WHITE + " ---- ", ChatColor.WHITE); - - List page = paged.getPage(pageIndex); - for (String entries : page) - { - msg(entries); - } - - msg("Page " + pageIndex + "/" + paged.getPageCount() + " | To index through the pages, type " + net.md_5.bungee.api.ChatColor.of("#30ade4") + "/ins history ", ChatColor.WHITE); - return true; } + + int godDammit = pageIndex; + Optional.ofNullable(plugin.cpb.getHistoryForPlayer(playerSender)).ifPresentOrElse(page -> + plugin.cpb.showPageToPlayer(playerSender, page, godDammit), + () -> msg("You haven't inspected anything yet!", ChatColor.RED)); + + return true; + } + else + { + return false; + } + } + + @Override + public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) + { + if (args.length == 1) + { + return Collections.singletonList("history"); + } + else if (args.length == 2 && args[0].equalsIgnoreCase("history") && plugin.cpb.isEnabled() + && sender instanceof Player player && plugin.cpb.hasHistory(player)) + { + return IntStream.rangeClosed(1, plugin.cpb.getHistoryForPlayer(player).getPageCount()).limit(50) + .mapToObj(String::valueOf).toList(); + } + else + { + return Collections.emptyList(); } - return true; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java index 01598b32..b4964a37 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java @@ -46,7 +46,7 @@ public class Command_invis extends FreedomCommand for (Player player : server.getOnlinePlayers()) { - if (player.hasPotionEffect(PotionEffectType.INVISIBILITY) && !plugin.al.isVanished(player.getName())) + if (player.hasPotionEffect(PotionEffectType.INVISIBILITY) && !plugin.al.isVanished(player.getUniqueId())) { players.add(player.getName()); if (clear && !plugin.al.isAdmin(player)) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_kicknoob.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_kicknoob.java index c009264e..11a59232 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_kicknoob.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_kicknoob.java @@ -2,7 +2,8 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.ChatColor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,20 +12,13 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Kick all non-admins on server.", usage = "/", aliases = "kickall") public class Command_kicknoob extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { FUtil.adminAction(sender.getName(), "Disconnecting all non-admins", true); - for (Player player : server.getOnlinePlayers()) - { - if (!plugin.al.isAdmin(player)) - { - player.kickPlayer(ChatColor.RED + "All non-admins were kicked by " + sender.getName() + "."); - } - } - + server.getOnlinePlayers().stream().filter(player -> !plugin.al.isAdmin(player)).forEach(player -> + player.kick(Component.text("All non-admins were kicked by " + sender.getName() + ".", NamedTextColor.RED))); return true; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java index fc592793..68db4ed8 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java @@ -1,9 +1,6 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.admin.Admin; -import me.totalfreedom.totalfreedommod.admin.AdminList; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.rank.Displayable; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import net.md_5.bungee.api.ChatColor; @@ -12,63 +9,37 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.List; @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH) -@CommandParameters(description = "Lists the real names of all online players.", usage = "/ [-s | -f | -v]", aliases = "who,lsit") +@CommandParameters(description = "Lists the real names of all online players.", usage = "/ [-a | -v]", aliases = "who,lsit") public class Command_list extends FreedomCommand { - + @Override public boolean run(final CommandSender sender, final Player playerSender, final Command cmd, final String commandLabel, final String[] args, final boolean senderIsConsole) { if (args.length > 1) { return false; } - if (FUtil.isFromHostConsole(sender.getName())) - { - List names = new ArrayList<>(); - for (Player player : server.getOnlinePlayers()) - { - if (!plugin.al.isVanished(player.getName())) - { - names.add(player.getName()); - } - } - msg("There are " + names.size() + "/" + server.getMaxPlayers() + " players online:\n" + StringUtils.join(names, ", "), ChatColor.WHITE); - return true; - } + ListFilter listFilter; if (args.length == 1) { - String s = args[0]; - switch (s) + switch (args[0].toLowerCase()) { - case "-s": - case "-a": - { - listFilter = ListFilter.ADMINS; - break; - } - case "-v": + case "-s", "-a" -> listFilter = ListFilter.ADMINS; + case "-v" -> { checkRank(Rank.ADMIN); listFilter = ListFilter.VANISHED_ADMINS; - break; } - case "-t": + case "-t" -> { checkRank(Rank.ADMIN); listFilter = ListFilter.TELNET_SESSIONS; - break; } - case "-f": - { - listFilter = ListFilter.FAMOUS_PLAYERS; - break; - } - default: + default -> { return false; } @@ -78,74 +49,42 @@ public class Command_list extends FreedomCommand { listFilter = ListFilter.PLAYERS; } - StringBuilder onlineStats = new StringBuilder(); - StringBuilder onlineUsers = new StringBuilder(); - List n = new ArrayList<>(); + String onlineStats; + List players; if (listFilter == ListFilter.TELNET_SESSIONS && plugin.al.isAdmin(sender)) { - List connectedAdmins = plugin.btb.getConnectedAdmins(); - onlineStats.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(connectedAdmins.size()) - .append(ChatColor.BLUE) - .append(" admins connected to telnet."); - for (Admin admin : connectedAdmins) - { - n.add(admin.getName()); - } + players = plugin.btb.getConnectedAdmins().stream().map(Admin::getName).toList(); + onlineStats = ChatColor.BLUE + "There are " + ChatColor.RED + players.size() + ChatColor.BLUE + + " admins connected to telnet."; } else { - onlineStats.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(FUtil.getFakePlayerCount()) - .append(ChatColor.BLUE) - .append(" out of a maximum ") - .append(ChatColor.RED) - .append(server.getMaxPlayers()) - .append(ChatColor.BLUE) - .append(" players online."); - for (Player p : server.getOnlinePlayers()) - { - if (listFilter == ListFilter.ADMINS && !plugin.al.isAdmin(p)) - { - continue; - } - if (listFilter == ListFilter.ADMINS && plugin.al.isVanished(p.getName())) - { - continue; - } - if (listFilter == ListFilter.VANISHED_ADMINS && !plugin.al.isVanished(p.getName())) - { - continue; - } - if (listFilter == ListFilter.FAMOUS_PLAYERS && !ConfigEntry.FAMOUS_PLAYERS.getList().contains(p.getName().toLowerCase())) - { - continue; - } - if (listFilter == ListFilter.PLAYERS && plugin.al.isVanished(p.getName())) - { - continue; - } + onlineStats = ChatColor.BLUE + "There are " + ChatColor.RED + FUtil.getFakePlayerCount() + ChatColor.BLUE + + " out of a maximum " + ChatColor.RED + server.getMaxPlayers() + ChatColor.BLUE + " players online."; - final Displayable display = plugin.rm.getDisplay(p); - n.add(display.getColoredTag() + p.getName()); - } + players = server.getOnlinePlayers().stream().filter(pl -> + (listFilter == ListFilter.ADMINS && plugin.al.isAdmin(pl) && !plugin.al.isVanished(pl.getUniqueId())) + || (listFilter == ListFilter.VANISHED_ADMINS && plugin.al.isVanished(pl.getUniqueId())) + || (listFilter == ListFilter.PLAYERS && !plugin.al.isVanished(pl.getUniqueId()))).map(player -> + plugin.rm.getDisplay(player).getColoredTag() + player.getName()).toList(); } - String playerType = listFilter.toString().toLowerCase().replace('_', ' '); - onlineUsers.append("Connected ") - .append(playerType) - .append(": ") - .append(StringUtils.join(n, ChatColor.WHITE + ", ")); + + String onlineUsers = "Connected " + listFilter.name().toLowerCase().replace('_', ' ') + ": " + ChatColor.WHITE + + StringUtils.join(players, ChatColor.WHITE + ", " + ChatColor.WHITE); + if (senderIsConsole) { - msg(ChatColor.stripColor(onlineStats.toString())); - msg(ChatColor.stripColor(onlineUsers.toString())); + msg(ChatColor.stripColor(onlineStats)); + msg(ChatColor.stripColor(onlineUsers)); } else { - msg(onlineStats.toString()); - msg(onlineUsers.toString()); + msg(onlineStats); + msg(onlineUsers); } - n.clear(); + return true; } @@ -154,7 +93,6 @@ public class Command_list extends FreedomCommand PLAYERS, ADMINS, VANISHED_ADMINS, - TELNET_SESSIONS, - FAMOUS_PLAYERS + TELNET_SESSIONS } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_logs.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_logs.java deleted file mode 100644 index e95d29b8..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_logs.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.totalfreedom.totalfreedommod.command; - -import me.totalfreedom.totalfreedommod.LogViewer.LogsRegistrationMode; -import me.totalfreedom.totalfreedommod.rank.Rank; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -@CommandPermissions(level = Rank.ADMIN, source = SourceType.ONLY_IN_GAME) -@CommandParameters(description = "Register your connection with the TFM logviewer.", usage = "/ [off]") -public class Command_logs extends FreedomCommand -{ - - @Override - public boolean run(final CommandSender sender, final Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) - { - LogsRegistrationMode mode = LogsRegistrationMode.ADD; - if (args.length == 1 && "off".equalsIgnoreCase(args[0])) - { - mode = LogsRegistrationMode.DELETE; - } - plugin.lv.updateLogsRegistration(sender, playerSender, mode); - - return true; - } -} diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java index 575ccf8e..990c1c6b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java @@ -3,15 +3,15 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.GameRuleHandler; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; +import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @CommandPermissions(level = Rank.ADMIN, source = SourceType.BOTH) -@CommandParameters(description = "Control mob limiting parameters.", usage = "/ |dragon|giant|ghast|slime>") +@CommandParameters(description = "Control mob limiting parameters.", usage = "/ | dragon | giant | ghast | slime>") public class Command_moblimiter extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -20,47 +20,35 @@ public class Command_moblimiter extends FreedomCommand return false; } - if (args[0].equalsIgnoreCase("on")) + switch (args[0].toLowerCase()) { - ConfigEntry.MOB_LIMITER_ENABLED.setBoolean(true); - } - else if (args[0].equalsIgnoreCase("off")) - { - ConfigEntry.MOB_LIMITER_ENABLED.setBoolean(false); - } - else if (args[0].equalsIgnoreCase("dragon")) - { - ConfigEntry.MOB_LIMITER_DISABLE_DRAGON.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_DRAGON.getBoolean()); - } - else if (args[0].equalsIgnoreCase("giant")) - { - ConfigEntry.MOB_LIMITER_DISABLE_GIANT.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_GIANT.getBoolean()); - } - else if (args[0].equalsIgnoreCase("slime")) - { - ConfigEntry.MOB_LIMITER_DISABLE_SLIME.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_SLIME.getBoolean()); - } - else if (args[0].equalsIgnoreCase("ghast")) - { - ConfigEntry.MOB_LIMITER_DISABLE_GHAST.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_GHAST.getBoolean()); - } - else - { - if (args.length < 2) + case "on" -> ConfigEntry.MOB_LIMITER_ENABLED.setBoolean(true); + case "off" -> ConfigEntry.MOB_LIMITER_ENABLED.setBoolean(false); + case "dragon" -> ConfigEntry.MOB_LIMITER_DISABLE_DRAGON.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_DRAGON.getBoolean()); + case "giant" -> ConfigEntry.MOB_LIMITER_DISABLE_GIANT.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_GIANT.getBoolean()); + case "slime" -> ConfigEntry.MOB_LIMITER_DISABLE_SLIME.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_SLIME.getBoolean()); + case "ghast" -> ConfigEntry.MOB_LIMITER_DISABLE_GHAST.setBoolean(!ConfigEntry.MOB_LIMITER_DISABLE_GHAST.getBoolean()); + case "setmax" -> { - return false; - } + if (args.length < 2) + { + return false; + } - if (args[0].equalsIgnoreCase("setmax")) - { try { ConfigEntry.MOB_LIMITER_MAX.setInteger(Math.max(0, Math.min(2000, Integer.parseInt(args[1])))); } - catch (NumberFormatException ignored) + catch (Exception ex) { + msg("Invalid number: " + args[1], ChatColor.RED); + return true; } } + default -> + { + // Shut the fuck up Codacy! + } } if (ConfigEntry.MOB_LIMITER_ENABLED.getBoolean()) @@ -78,7 +66,6 @@ public class Command_moblimiter extends FreedomCommand } plugin.gr.setGameRule(GameRuleHandler.GameRule.DO_MOB_SPAWNING, !ConfigEntry.MOB_LIMITER_ENABLED.getBoolean()); - return true; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java index 7d726cbd..9850b5c3 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -16,17 +15,6 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Purge all mobs in all worlds.", usage = "/ [name]", aliases = "mp") public class Command_mobpurge extends FreedomCommand { - - public static List getAllMobNames() - { - List names = new ArrayList<>(); - for (EntityType entityType : Groups.MOB_TYPES) - { - names.add(entityType.name()); - } - return names; - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -67,7 +55,7 @@ public class Command_mobpurge extends FreedomCommand { if (args.length == 1) { - return getAllMobNames(); + return Groups.MOB_TYPES.stream().map(Enum::name).toList(); } return Collections.emptyList(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mute.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mute.java index e66c0c73..dc2ee775 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mute.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mute.java @@ -1,10 +1,6 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import me.totalfreedom.totalfreedommod.player.FPlayer; +import java.util.*; import me.totalfreedom.totalfreedommod.punishments.Punishment; import me.totalfreedom.totalfreedommod.punishments.PunishmentType; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -20,7 +16,6 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Mutes a player with brute force.", usage = "/ <[-s | -q] [reason] | list | purge | all>", aliases = "stfu") public class Command_mute extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -29,134 +24,110 @@ public class Command_mute extends FreedomCommand return false; } - if (args[0].equalsIgnoreCase("list")) + switch (args[0].toLowerCase()) { - msg("Muted players:"); - FPlayer info; - int count = 0; - for (Player mp : server.getOnlinePlayers()) + case "list" -> { - info = plugin.pl.getPlayer(mp); - if (info.isMuted()) + msg("Muted players:"); + List list = server.getOnlinePlayers().stream().filter(player -> + plugin.pl.getPlayer(player).isMuted()).toList(); + + if (list.size() > 0) + list.forEach(player -> msg("- " + player.getName())); + else + msg("- none"); + } + case "purge" -> + { + FUtil.adminAction(sender.getName(), "Unmuting all players", true); + List list = server.getOnlinePlayers().stream().filter(player -> + plugin.pl.getPlayer(player).isMuted()).toList(); + + list.forEach(player -> { - msg("- " + mp.getName()); - count++; - } - } - if (count == 0) - { - msg("- none"); - } + plugin.pl.getPlayer(player).setMuted(false); + player.sendTitle(ChatColor.RED + "You have been unmuted.", + ChatColor.YELLOW + "Be sure to follow the rules!", 20, 100, 60); + }); - return true; - } - - if (args[0].equalsIgnoreCase("purge")) - { - FUtil.adminAction(sender.getName(), "Unmuting all players.", true); - FPlayer info; - int count = 0; - for (Player mp : server.getOnlinePlayers()) + msg("Unmuted " + list.size() + " player" + (list.size() != 1 ? "s" : "") + "."); + } + case "all" -> { - info = plugin.pl.getPlayer(mp); - if (info.isMuted()) + FUtil.adminAction(sender.getName(), "Muting all non-admins", true); + List list = server.getOnlinePlayers().stream().filter(player -> + !plugin.al.isAdmin(player)).toList(); + + list.forEach(player -> { - info.setMuted(false); - mp.sendTitle(ChatColor.RED + "You've been unmuted.", ChatColor.YELLOW + "Be sure to follow the rules!", 20, 100, 60); - count++; - } + plugin.pl.getPlayer(player).setMuted(true); + player.sendTitle(ChatColor.RED + "You've been muted globally.", + ChatColor.YELLOW + "Please be patient and you will be unmuted shortly.", 20, 100, 60); + }); + + msg("Muted " + list.size() + " player" + (list.size() != 1 ? "s" : "") + "."); } - plugin.mu.MUTED_PLAYERS.clear(); - msg("Unmuted " + count + " players."); - return true; - } - - if (args[0].equalsIgnoreCase("all")) - { - FUtil.adminAction(sender.getName(), "Muting all non-admins", true); - - FPlayer playerdata; - int counter = 0; - for (Player player : server.getOnlinePlayers()) + default -> { - if (!plugin.al.isAdmin(player)) + boolean quiet = args[0].equalsIgnoreCase("-q"); + boolean smite = args[0].equalsIgnoreCase("-s"); + + // Handling the -q parameter + if (quiet || smite) { - player.sendTitle(ChatColor.RED + "You've been muted globally.", ChatColor.YELLOW + "Please be patient and you will be unmuted shortly.", 20, 100, 60); - playerdata = plugin.pl.getPlayer(player); - playerdata.setMuted(true); - counter++; + if (args.length == 1) return false; + args = ArrayUtils.subarray(args, 1, args.length); } + + // Handling the (optional) reason + String reason = args.length > 1 ? StringUtils.join(args, " ", 1, args.length) : null; + + // Showtime + Optional.ofNullable(getPlayer(args[0])).ifPresentOrElse(player -> + { + if (plugin.al.isAdmin(player)) + { + msg(player.getName() + " is an admin, and as such can't be muted.", ChatColor.RED); + return; + } + else if (plugin.pl.getPlayer(player).isMuted()) + { + msg(player.getName() + " is already muted.", ChatColor.RED); + return; + } + + // Don't broadcast the mute if it was quiet + if (!quiet) + { + FUtil.adminAction(sender.getName(), "Muting " + player.getName(), true); + } + + // Smite the player if we're supposed to + if (smite) + { + Command_smite.smite(sender, player, reason, true, false); + } + + // Mutes the player + plugin.pl.getPlayer(player).setMuted(true); + + // Notify the player that they have been muted + player.sendTitle(ChatColor.RED + "You've been muted.", + ChatColor.YELLOW + "Be sure to follow the rules!", 20, 100, 60); + msg(player, "You have been muted by " + ChatColor.YELLOW + sender.getName() + + ChatColor.RED + ".", ChatColor.RED); + + // Give them the reason if one is present. + if (reason != null) + { + msg(player, "Reason: " + ChatColor.YELLOW + reason, ChatColor.RED); + } + + msg((quiet ? "Quietly m" : "M") + "uted " + player.getName() + "."); + plugin.pul.logPunishment(new Punishment(player.getName(), FUtil.getIp(player), sender.getName(), + PunishmentType.MUTE, reason)); + }, () -> msg(PLAYER_NOT_FOUND)); } - - msg("Muted " + counter + " players."); - return true; - } - - // -s option (smite) - boolean smite = args[0].equals("-s"); - // -q option (shadowmute) - boolean quiet = args[0].equals("-q"); - if (smite || quiet) - { - args = ArrayUtils.subarray(args, 1, args.length); - - if (args.length < 1) - { - return false; - } - } - - final Player player = getPlayer(args[0]); - if (player == null) - { - msg(PLAYER_NOT_FOUND); - return true; - } - - String reason = null; - if (args.length > 1) - { - reason = StringUtils.join(args, " ", 1, args.length); - } - - FPlayer playerdata = plugin.pl.getPlayer(player); - if (plugin.al.isAdmin(player)) - { - msg(player.getName() + " is an admin, and can't be muted."); - return true; - } - - if (!playerdata.isMuted()) - { - playerdata.setMuted(true); - player.sendTitle(ChatColor.RED + "You've been muted.", ChatColor.YELLOW + "Be sure to follow the rules!", 20, 100, 60); - - if (quiet) - { - msg("Muted " + player.getName() + " quietly"); - return true; // doesn't announce reason - } - - FUtil.adminAction(sender.getName(), "Muting " + player.getName(), true); - - if (reason != null) - { - msg(player, ChatColor.RED + "Reason: " + ChatColor.YELLOW + reason); - } - - if (smite) - { - Command_smite.smite(sender, player, reason); - } - - msg(player, "You have been muted by " + ChatColor.YELLOW + sender.getName(), ChatColor.RED); - msg("Muted " + player.getName()); - - plugin.pul.logPunishment(new Punishment(player.getName(), FUtil.getIp(player), sender.getName(), PunishmentType.MUTE, reason)); - } - else - { - msg(ChatColor.RED + "That player is already muted."); } return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java index 1c38639c..ffc8c56b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java @@ -217,42 +217,33 @@ public class Command_myadmin extends FreedomCommand } else if (args.length == 2) { - if (args[0].equals("-o")) + if (args[0].equalsIgnoreCase("-o")) { return FUtil.getPlayerList(); } else { - if (doubleArguments.contains(args[0])) + if (doubleArguments.contains(args[0]) && args[0].equalsIgnoreCase("clearip")) { - if (args[0].equals("clearip")) - { - List ips = plugin.al.getAdmin(sender).getIps(); - ips.remove(FUtil.getIp((Player)sender)); - return ips; - } + List ips = plugin.al.getAdmin(sender).getIps(); + ips.remove(FUtil.getIp((Player)sender)); + return ips; } } } - else if (args.length == 3) + else if (args.length == 3 && args[0].equalsIgnoreCase("-o")) { - if (args[0].equals("-o")) - { - List options = new ArrayList<>(); - options.addAll(singleArguments); - options.addAll(doubleArguments); - return options; - } + List options = new ArrayList<>(); + options.addAll(singleArguments); + options.addAll(doubleArguments); + return options; } - else if (args.length == 4) + else if (args.length == 4 && args[0].equalsIgnoreCase("-o") && args[2].equalsIgnoreCase("clearip")) { - if (args[0].equals("-o") && args[2].equals("clearip")) + Admin admin = plugin.al.getEntryByName(args[1]); + if (admin != null) { - Admin admin = plugin.al.getEntryByName(args[1]); - if (admin != null) - { - return admin.getIps(); - } + return admin.getIps(); } } return FUtil.getPlayerList(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java index fef2ee56..76e7d125 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java @@ -74,11 +74,11 @@ public class Command_nickfilter extends FreedomCommand player = getPlayerByDisplayName(displayName); - if (player == null || plugin.al.isVanished(player.getName()) && !plugin.al.isAdmin(sender)) + if (player == null || plugin.al.isVanished(player.getUniqueId()) && !plugin.al.isAdmin(sender)) { player = getPlayerByDisplayNameAlt(displayName); - if (player == null || !plugin.al.isVanished(player.getName()) && !plugin.al.isAdmin(sender)) + if (player == null || !plugin.al.isVanished(player.getUniqueId()) && !plugin.al.isAdmin(sender)) { msg("Can't find player by nickname: " + displayName); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickgradient.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickgradient.java index 3fba2d4f..402459c5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickgradient.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickgradient.java @@ -15,10 +15,15 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Essentials Interface Command - Rainbowify your nickname.", usage = "/ ", aliases = "nickgr") public class Command_nickgradient extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { + if (!server.getPluginManager().isPluginEnabled("Essentials")) + { + msg("Essentials is not enabled on this server."); + return true; + } + if (args.length != 3) { return false; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nicknyan.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nicknyan.java index 706b54d5..251680cf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nicknyan.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nicknyan.java @@ -2,20 +2,25 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.Arrays; @CommandPermissions(level = Rank.OP, source = SourceType.ONLY_IN_GAME) @CommandParameters(description = "Essentials Interface Command - Randomize the colors of your nickname.", usage = "/ < | off>") public class Command_nicknyan extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { + if (!server.getPluginManager().isPluginEnabled("Essentials")) + { + msg("Essentials is not enabled on this server."); + return true; + } + if (args.length != 1) { return false; @@ -41,32 +46,24 @@ public class Command_nicknyan extends FreedomCommand return true; } - for (Player player : Bukkit.getOnlinePlayers()) + + if (server.getOnlinePlayers().stream().anyMatch(player -> player != playerSender + && (player.getName().equalsIgnoreCase(nickPlain) + || ChatColor.stripColor(plugin.esb.getNickname(player.getName())).trim().equalsIgnoreCase(nickPlain)))) { - if (player == playerSender) - { - continue; - } - if (player.getName().equalsIgnoreCase(nickPlain) || ChatColor.stripColor(player.getDisplayName()).trim().equalsIgnoreCase(nickPlain)) - { - msg("That nickname is already in use."); - return true; - } + msg("That nickname is already in use."); + return true; } final StringBuilder newNick = new StringBuilder(); - - final char[] chars = nickPlain.toCharArray(); - for (char c : chars) - { - newNick.append(FUtil.randomChatColor()).append(c); - } + Arrays.stream(nickPlain.chars().toArray()).forEach(character -> newNick.append(FUtil.randomChatColor()) + .append(Character.toString(character))); newNick.append(ChatColor.WHITE); plugin.esb.setNickname(sender.getName(), newNick.toString()); - msg("Your nickname is now: " + newNick.toString()); + msg("Your nickname is now: " + newNick); return true; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickrainbow.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickrainbow.java index d82b4f30..94de311f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickrainbow.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickrainbow.java @@ -12,10 +12,15 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Essentials Interface Command - Rainbowify your nickname.", usage = "/ ") public class Command_nickrainbow extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { + if (!server.getPluginManager().isPluginEnabled("Essentials")) + { + msg("Essentials is not enabled on this server."); + return true; + } + if (args.length != 1) { return false; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_op.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_op.java index ece9abba..496df3ae 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_op.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_op.java @@ -33,16 +33,14 @@ public class Command_op extends FreedomCommand List matchedPlayerNames = new ArrayList<>(); for (final Player player : server.getOnlinePlayers()) { - if (player.getName().toLowerCase().contains(targetName) || player.getDisplayName().toLowerCase().contains(targetName) - || player.getName().contains(targetName) || player.getDisplayName().contains(targetName)) + if ((player.getName().toLowerCase().contains(targetName) || player.getDisplayName().toLowerCase().contains(targetName) + || player.getName().contains(targetName) || player.getDisplayName().contains(targetName)) && + !player.isOp() && !plugin.al.isVanished(player.getUniqueId())) { - if (!player.isOp() && !plugin.al.isVanished(player.getName())) - { - matchedPlayerNames.add(player.getName()); - player.setOp(true); - msg(player, YOU_ARE_OP); - plugin.rm.updateDisplay(player); - } + matchedPlayerNames.add(player.getName()); + player.setOp(true); + msg(player, YOU_ARE_OP); + plugin.rm.updateDisplay(player); } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_opall.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_opall.java index 45ff1689..3cd46e01 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_opall.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_opall.java @@ -10,13 +10,12 @@ import org.bukkit.entity.Player; @CommandParameters(description = "OP everyone on the server.", usage = "/") public class Command_opall extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { FUtil.adminAction(sender.getName(), "Opping all players on the server", false); - for (Player player : server.getOnlinePlayers()) + server.getOnlinePlayers().forEach(player -> { if (!player.isOp()) { @@ -28,7 +27,7 @@ public class Command_opall extends FreedomCommand { player.recalculatePermissions(); } - } + }); return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java deleted file mode 100644 index 364d58ff..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java +++ /dev/null @@ -1,114 +0,0 @@ -package me.totalfreedom.totalfreedommod.command; - -import com.google.common.base.Strings; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import me.totalfreedom.totalfreedommod.admin.Admin; -import me.totalfreedom.totalfreedommod.player.PlayerData; -import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -@CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.ONLY_IN_GAME) -@CommandParameters(description = "Manage your Pterodactyl panel account", usage = "/ ") -public class Command_panel extends FreedomCommand -{ - - @Override - public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) - { - - if (!plugin.ptero.isEnabled()) - { - msg("Pterodactyl integration is currently disabled.", ChatColor.RED); - return true; - } - - PlayerData playerData = getData(playerSender); - - if (playerData.getDiscordID() == null) - { - msg("You must have a linked discord account.", ChatColor.RED); - return true; - } - - if (args.length == 0) - { - return false; - } - - if (args[0].equalsIgnoreCase("create")) - { - msg("Creating your Pterodactyl account...", ChatColor.GREEN); - Admin admin = getAdmin(playerSender); - - if (admin.getPteroID() != null) - { - msg("You already have a Pterodactyl account.", ChatColor.RED); - return true; - } - - String username = sender.getName(); - String password = FUtil.randomString(30); - - String id = plugin.ptero.createAccount(username, password); - if (Strings.isNullOrEmpty(id)) - { - msg("Failed to create your Pterodactyl account.", ChatColor.RED); - return true; - } - - plugin.ptero.addAccountToServer(id); - - admin.setPteroID(id); - plugin.al.save(admin); - plugin.al.updateTables(); - - plugin.dc.sendPteroInfo(playerData, username, password); - msg("Successfully created your Pterodactyl account. Check your DMs from " + plugin.dc.formatBotTag() + " on discord to get your credentials.", ChatColor.GREEN); - return true; - } - else if (args[0].equalsIgnoreCase("delete")) - { - msg("Deleting your Pterodactyl account...", ChatColor.GREEN); - Admin admin = getAdmin(playerSender); - - if (admin.getPteroID() == null) - { - msg("You do not have a Pterodactyl account.", ChatColor.RED); - return true; - } - - boolean deleted = plugin.ptero.deleteAccount(admin.getPteroID()); - - if (!deleted) - { - msg("Failed to delete your Pterodactyl account.", ChatColor.RED); - return true; - } - - admin.setPteroID(null); - plugin.al.save(admin); - plugin.al.updateTables(); - - msg("Successfully deleted your Pterodactyl account.", ChatColor.GREEN); - return true; - } - return false; - } - - @Override - public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) - { - if (args.length == 1 && plugin.al.isSeniorAdmin(sender)) - { - return Arrays.asList("create", "delete"); - } - - return Collections.emptyList(); - } -} \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java index 1dbc5579..9e262500 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java @@ -1,9 +1,6 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; import me.totalfreedom.totalfreedommod.rank.Rank; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; @@ -17,116 +14,109 @@ import org.bukkit.plugin.PluginManager; @CommandParameters(description = "Enable, disable, or reload a specified plugin, as well as list all plugins on the server.", usage = "/ < > | list>", aliases = "plc") public class Command_plugincontrol extends FreedomCommand { - private final List UNTOUCHABLE_PLUGINS = Arrays.asList(plugin.getName()); @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - if (args.length == 0 || args.length > 2) - { - return false; - } - final PluginManager pm = server.getPluginManager(); - if (args.length == 1) + /* This is the way it is because there was too much "if the arguments aren't enough then return false" in the + * original code in addition to the stupid amount of "if something isn't right then do some boilerplate stuff + * then return true". Codacy complained, so I aggressively optimized this to keep it quiet. */ + switch (args.length) { - if (args[0].equalsIgnoreCase("list")) + case 1 -> { - for (Plugin serverPlugin : pm.getPlugins()) + if (args[0].equalsIgnoreCase("list")) { - final String version = serverPlugin.getDescription().getVersion(); - msg(ChatColor.GRAY + "- " + (serverPlugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED) + serverPlugin.getName() - + ChatColor.GOLD + (!version.isEmpty() ? " v" + version : "") + " by " - + StringUtils.join(serverPlugin.getDescription().getAuthors(), ", ")); + Arrays.stream(pm.getPlugins()).forEach(pl -> + { + final String version = pl.getDescription().getVersion(); + msg(ChatColor.GRAY + "- " + (pl.isEnabled() ? ChatColor.GREEN : ChatColor.RED) + pl.getName() + + ChatColor.GOLD + (!version.isEmpty() ? " v" + version : "") + " by " + + StringUtils.join(pl.getDescription().getAuthors(), ", ")); + }); + + return true; } - - return true; } - - return false; - } - - if (args[0].equals("enable")) - { - final Plugin target = getPlugin(args[1]); - if (target == null) + case 2 -> { - msg("Plugin not found!"); - return true; - } + Plugin pl = pm.getPlugin(args[1]); - if (target.isEnabled()) + if (pl != null) + { + switch (args[0].toLowerCase()) + { + case "enable" -> + { + if (pl.isEnabled()) + { + msg(pl.getName() + " is already enabled."); + return true; + } + + pm.enablePlugin(pl); + + if (pl.isEnabled()) + { + msg(pl.getName() + " is now enabled."); + } + else + { + msg("An error occurred whilst attempting to enable " + pl.getName() + "."); + } + return true; + } + case "disable" -> + { + if (!pl.isEnabled()) + { + msg(pl.getName() + " is already disabled."); + return true; + } + else if (UNTOUCHABLE_PLUGINS.contains(pl.getName())) + { + msg(pl.getName() + " can't be disabled."); + return true; + } + + pm.disablePlugin(pl); + + msg(pl.getName() + " is now disabled."); + return true; + } + case "reload" -> + { + if (UNTOUCHABLE_PLUGINS.contains(pl.getName())) + { + msg(pl.getName() + " can't be reloaded."); + return true; + } + + pm.disablePlugin(pl); + pm.enablePlugin(pl); + + msg(pl.getName() + " has been reloaded."); + return true; + } + default -> + { + // Do nothing. This is here to please Codacy. + } + } + } + else + { + msg("Plugin not found!"); + return true; + } + } + default -> { - msg("Plugin is already enabled."); - return true; + // Ditto } - - pm.enablePlugin(target); - - if (!pm.isPluginEnabled(target)) - { - msg("Error enabling plugin " + target.getName()); - return true; - } - - msg(target.getName() + " is now enabled."); - return true; - } - - if (args[0].equals("disable")) - { - final Plugin target = getPlugin(args[1]); - if (target == null) - { - msg("Plugin not found!"); - return true; - } - - if (!target.isEnabled()) - { - msg("Plugin is already disabled."); - return true; - } - - if (UNTOUCHABLE_PLUGINS.contains(target.getName())) - { - msg("You cannot disable " + target.getName()); - return true; - } - - pm.disablePlugin(target); - - if (pm.isPluginEnabled(target)) - { - msg("Error disabling plugin " + target.getName()); - return true; - } - - msg(target.getName() + " is now disabled."); - return true; - } - - if (args[0].equals("reload")) - { - final Plugin target = getPlugin(args[1]); - if (target == null) - { - msg("Plugin not found!"); - return true; - } - - if (UNTOUCHABLE_PLUGINS.contains(target.getName())) - { - msg("You cannot reload " + target.getName()); - return true; - } - - pm.disablePlugin(target); - pm.enablePlugin(target); - msg(target.getName() + " reloaded."); - return true; } return false; @@ -143,51 +133,12 @@ public class Command_plugincontrol extends FreedomCommand { return Arrays.asList("enable", "disable", "reload", "list"); } - else if (args.length == 2) + else if (args.length == 2 && !args[0].equalsIgnoreCase("list")) { - if (!args[0].equals("list")) - { - return getAllPluginNames(); - } + return Arrays.stream(server.getPluginManager().getPlugins()).map(Plugin::getName) + .filter(pl -> !UNTOUCHABLE_PLUGINS.contains(pl)).toList(); } return Collections.emptyList(); } - - public List getAllPluginNames() - { - List names = new ArrayList<>(); - for (Plugin plugin : server.getPluginManager().getPlugins()) - { - if (!UNTOUCHABLE_PLUGINS.contains(plugin.getName())) - { - names.add(plugin.getName()); - } - } - names.remove(plugin.getName()); - return names; - } - - public Plugin getPlugin(String name) - { - for (Plugin serverPlugin : server.getPluginManager().getPlugins()) - { - if (serverPlugin.getName().equalsIgnoreCase(name)) - { - return serverPlugin; - } - } - - if (name.length() >= 3) - { - for (Plugin serverPlugin : server.getPluginManager().getPlugins()) - { - if (serverPlugin.getName().toLowerCase().contains(name.toLowerCase())) - { - return serverPlugin; - } - } - } - return null; - } -} +} \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java index feab9776..d8db4b9b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java @@ -6,7 +6,6 @@ import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; -import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -21,8 +20,6 @@ import org.bukkit.potion.PotionEffectType; aliases = "effect") public class Command_potion extends FreedomCommand { - - @SuppressWarnings("deprecation") @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -32,15 +29,8 @@ public class Command_potion extends FreedomCommand { if (args[0].equalsIgnoreCase("list")) { - List potionEffectTypeNames = new ArrayList<>(); - for (PotionEffectType potion_effect_type : PotionEffectType.values()) - { - if (potion_effect_type != null) - { - potionEffectTypeNames.add(potion_effect_type.getName()); - } - } - msg("Potion effect types: " + StringUtils.join(potionEffectTypeNames, ", "), ChatColor.AQUA); + msg("Potion effect types: " + FUtil.listToString(Arrays.stream(PotionEffectType.values()) + .map(PotionEffectType::getName).toList()), ChatColor.AQUA); } else if (args[0].equalsIgnoreCase("clearall")) { @@ -50,14 +40,9 @@ public class Command_potion extends FreedomCommand return true; } - FUtil.adminAction(sender.getName(), "Cleared all potion effects from all players", true); - for (Player target : server.getOnlinePlayers()) - { - for (PotionEffect potion_effect : target.getActivePotionEffects()) - { - target.removePotionEffect(potion_effect.getType()); - } - } + FUtil.adminAction(sender.getName(), "Clearing all potion effects from all players", true); + server.getOnlinePlayers().forEach(target -> target.getActivePotionEffects().forEach(effect -> + target.removePotionEffect(effect.getType()))); } } @@ -86,7 +71,7 @@ public class Command_potion extends FreedomCommand if (target == null) { - msg(FreedomCommand.PLAYER_NOT_FOUND, ChatColor.RED); + msg(PLAYER_NOT_FOUND, ChatColor.RED); return true; } @@ -95,7 +80,8 @@ public class Command_potion extends FreedomCommand target.removePotionEffect(potion_effect.getType()); } - msg("Cleared all active potion effects " + (!target.equals(playerSender) ? "from player " + target.getName() + "." : "from yourself."), ChatColor.AQUA); + msg("Cleared all active potion effects " + (!target.equals(playerSender) ? "from player " + + target.getName() + "." : "from yourself."), ChatColor.AQUA); } break; } @@ -117,7 +103,7 @@ public class Command_potion extends FreedomCommand target = getPlayer(args[4]); - if (target == null || plugin.al.isVanished(target.getName()) && !plugin.al.isAdmin(sender)) + if (target == null || plugin.al.isVanished(target.getUniqueId()) && !plugin.al.isAdmin(sender)) { msg(PLAYER_NOT_FOUND); return true; @@ -132,44 +118,41 @@ public class Command_potion extends FreedomCommand } } - PotionEffectType potion_effect_type = PotionEffectType.getByName(args[1]); - if (potion_effect_type == null) + PotionEffectType effectType = PotionEffectType.getByName(args[1]); + if (effectType == null) { - msg("Invalid potion effect type.", ChatColor.AQUA); + msg("Invalid potion effect: " + args[1], ChatColor.AQUA); return true; } int duration; try { - duration = Integer.parseInt(args[2]); - duration = Math.min(duration, 100000); + duration = Math.min(Integer.parseInt(args[2]), 100000); } catch (NumberFormatException ex) { - msg("Invalid potion duration.", ChatColor.RED); + msg("Invalid duration: " + args[2], ChatColor.RED); return true; } int amplifier; try { - amplifier = Integer.parseInt(args[3]); - amplifier = Math.min(amplifier, 100000); + amplifier = Math.min(Integer.parseInt(args[3]), 100000); } catch (NumberFormatException ex) { - msg("Invalid potion amplifier.", ChatColor.RED); + msg("Invalid potion amplifier: " + args[3], ChatColor.RED); return true; } - PotionEffect new_effect = potion_effect_type.createEffect(duration, amplifier); - target.addPotionEffect(new_effect, true); - msg( - "Added potion effect: " + new_effect.getType().getName() - + ", Duration: " + new_effect.getDuration() - + ", Amplifier: " + new_effect.getAmplifier() - + (!target.equals(playerSender) ? " to player " + target.getName() + "." : " to yourself."), ChatColor.AQUA); + PotionEffect new_effect = effectType.createEffect(duration, amplifier); + target.addPotionEffect(new_effect); + msg("Added potion effect: " + new_effect.getType().getName() + + ", Duration: " + new_effect.getDuration() + + ", Amplifier: " + new_effect.getAmplifier() + + (!target.equals(playerSender) ? " to player " + target.getName() + "." : " to yourself."), ChatColor.AQUA); } break; } @@ -186,7 +169,7 @@ public class Command_potion extends FreedomCommand { switch (args.length) { - case 1: + case 1 -> { List arguments = new ArrayList<>(Arrays.asList("list", "clear", "add")); if (plugin.al.isAdmin(sender)) @@ -195,72 +178,46 @@ public class Command_potion extends FreedomCommand } return arguments; } - - case 2: + case 2 -> { - if (args[0].equals("clear")) + if (args[0].equalsIgnoreCase("clear")) { if (plugin.al.isAdmin(sender)) { return FUtil.getPlayerList(); } } - else if (args[0].equals("add")) + else if (args[0].equalsIgnoreCase("add")) { - return getAllPotionTypes(); + return Arrays.stream(PotionEffectType.values()).map(PotionEffectType::getName).toList(); } - break; } - - case 3: + case 3 -> { - if (args[0].equals("add")) + if (args[0].equalsIgnoreCase("add")) { return Collections.singletonList(""); } - break; } - - case 4: + case 4 -> { - if (args[0].equals("add")) + if (args[0].equalsIgnoreCase("add")) { return Collections.singletonList(""); } - break; } - - case 5: + case 5 -> { - if (plugin.al.isAdmin(sender)) + if (plugin.al.isAdmin(sender) && args[0].equalsIgnoreCase("add")) { - if (args[0].equals("add")) - { - return FUtil.getPlayerList(); - } + return FUtil.getPlayerList(); } - break; } - - default: + default -> { - break; } } return Collections.emptyList(); } - - public List getAllPotionTypes() - { - List types = new ArrayList<>(); - for (PotionEffectType potionEffectType : PotionEffectType.values()) - { - if (potionEffectType != null) - { - types.add(potionEffectType.getName()); - } - } - return types; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ride.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ride.java index 30a1883b..25623bd0 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ride.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ride.java @@ -84,19 +84,22 @@ public class Command_ride extends FreedomCommand return true; } - if (args.length >= 2) + if (args.length >= 2 && args[0].equalsIgnoreCase("mode")) { - if (args[0].equalsIgnoreCase("mode")) + try { - if (args[1].equalsIgnoreCase("normal") || args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("ask")) - { - PlayerData playerDataSender = plugin.pl.getData(playerSender); - playerDataSender.setRideMode(args[1].toLowerCase()); - plugin.pl.save(playerDataSender); - msg("Ride mode is now set to " + args[1].toLowerCase() + "."); - return true; - } + PlayerData.RideMode mode = PlayerData.RideMode.valueOf(args[1].toUpperCase()); + PlayerData playerDataSender = plugin.pl.getData(playerSender); + playerDataSender.setRideMode(mode); + plugin.pl.save(playerDataSender); + msg("Ride mode is now set to " + mode.name().toLowerCase() + "."); } + catch (IllegalArgumentException ex) + { + msg("Invalid mode.", ChatColor.RED); + } + + return true; } final Player player = getPlayer(args[0], true); @@ -114,13 +117,13 @@ public class Command_ride extends FreedomCommand return true; } - if (playerData.getRideMode().equals("off") && !isAdmin(sender)) + if (playerData.getRideMode() == PlayerData.RideMode.OFF && !isAdmin(sender)) { msg("That player cannot be ridden.", ChatColor.RED); return true; } - if (playerData.getRideMode().equals("ask") && !FUtil.isExecutive(playerSender.getName())) + if (playerData.getRideMode() == PlayerData.RideMode.ASK && !FUtil.isExecutive(playerSender.getName())) { msg("Sent a request to the player.", ChatColor.GREEN); msg(player, sender.getName() + " has requested to ride you.", ChatColor.AQUA); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java index ee5c63b5..2fab3cf2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java @@ -112,8 +112,6 @@ public class Command_saconfig extends FreedomCommand Discord.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID()); } - plugin.ptero.updateAccountStatus(admin); - msg("Set " + admin.getName() + "'s rank to " + rank.getName()); return true; } @@ -210,7 +208,6 @@ public class Command_saconfig extends FreedomCommand Discord.syncRoles(admin, plugin.pl.getData(player).getDiscordID()); } } - plugin.ptero.updateAccountStatus(admin); final FPlayer fPlayer = plugin.pl.getPlayer(player); if (fPlayer.getFreezeData().isFrozen()) @@ -265,8 +262,6 @@ public class Command_saconfig extends FreedomCommand Discord.syncRoles(admin, plugin.pl.getData(adminName).getDiscordID()); } - plugin.ptero.updateAccountStatus(admin); - return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_seed.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_seed.java index ff489582..c1381fa9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_seed.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_seed.java @@ -1,19 +1,17 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.rank.Rank; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.api.chat.TranslatableComponent; -import net.md_5.bungee.api.chat.hover.content.Text; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.generator.WorldInfo; -import java.util.ArrayList; import java.util.List; @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH) @@ -47,34 +45,11 @@ public class Command_seed extends FreedomCommand } } - // If the sender is not a Player, use the usual msg method to - if (senderIsConsole) - { - msg("Seed: [" + ChatColor.GREEN + world.getSeed() + ChatColor.WHITE + "]", ChatColor.WHITE); - } - else - { - // Gets the seed for later uses - String seed = String.valueOf(world.getSeed()); - - // This is a really stupid hack to get things to play nicely, but it works so I don't give a damn - BaseComponent[] components = {new TranslatableComponent("chat.copy.click")}; - TextComponent seedAsComponent = new TextComponent(seed); - - // Style the message like in vanilla Minecraft. - seedAsComponent.setColor(ChatColor.GREEN.asBungee()); - seedAsComponent.setClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, seed)); - seedAsComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(components))); - - // Enclose the seed with brackets - TextComponent seedString = new TextComponent("["); - seedString.addExtra(seedAsComponent); - seedString.addExtra("]"); - - // Send the message to the player. - TranslatableComponent response = new TranslatableComponent("commands.seed.success", seedString); - playerSender.spigot().sendMessage(response); - } + sender.sendMessage(Component.translatable("commands.seed.success", + Component.text("[", NamedTextColor.WHITE).append(Component.text(world.getSeed(), NamedTextColor.GREEN) + .clickEvent(ClickEvent.copyToClipboard(String.valueOf(world.getSeed()))) + .hoverEvent(HoverEvent.showText(Component.translatable("chat.copy")))) + .append(Component.text("]")))); return true; } @@ -83,13 +58,7 @@ public class Command_seed extends FreedomCommand { if (args.length == 1) { - // Returns a list of worlds on the server and returns it - List worlds = new ArrayList<>(); - for (World world : server.getWorlds()) - { - worlds.add(world.getName()); - } - return worlds; + return server.getWorlds().stream().map(WorldInfo::getName).toList(); } return null; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java index b8430169..2df3c253 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.List; - +import java.util.Optional; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.Location; import org.bukkit.Material; @@ -15,10 +14,9 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH) -@CommandParameters(description = "Set the on/off state of the lever at position x, y, z in world 'worldname'.", usage = "/ ") +@CommandParameters(description = "Set the on/off state of the lever at position x, y, z in world 'worldname'.", usage = "/ ") public class Command_setlever extends FreedomCommand { - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -33,50 +31,38 @@ public class Command_setlever extends FreedomCommand x = Double.parseDouble(args[0]); y = Double.parseDouble(args[1]); z = Double.parseDouble(args[2]); + + // Shows the "Invalid coordinates" message without having to do boilerplate bullshit + if (Math.abs(x) > 29999998 || Math.abs(y) > 29999998 || Math.abs(z) > 29999998) + { + throw new IllegalArgumentException(); + } } - catch (NumberFormatException ex) + catch (IllegalArgumentException ex) { msg("Invalid coordinates."); return true; } - if (x > 29999998 || x < -29999998 || y > 29999998 || y < -29999998 || z > 29999998 || z < -29999998) + Optional optionalWorld = server.getWorlds().stream().filter(world -> + world.getName().equalsIgnoreCase(args[3])).findAny(); + + if (optionalWorld.isEmpty()) { - msg("Coordinates cannot be larger than 29999998 or smaller than -29999998 blocks."); + msg("Invalid world: " + args[3]); return true; } - World world = null; - final String needleWorldName = args[3].trim(); - final List worlds = server.getWorlds(); - for (final World testWorld : worlds) - { - if (testWorld.getName().trim().equalsIgnoreCase(needleWorldName)) - { - world = testWorld; - break; - } - } - - if (world == null) - { - msg("Invalid world name."); - return true; - } - - final Location leverLocation = new Location(world, x, y, z); - - final boolean leverOn = (args[4].trim().equalsIgnoreCase("on") || args[4].trim().equalsIgnoreCase("1")); - + final Location leverLocation = new Location(optionalWorld.get(), x, y, z); final Block targetBlock = leverLocation.getBlock(); if (targetBlock.getType() == Material.LEVER) { BlockState state = targetBlock.getState(); BlockData data = state.getBlockData(); - Switch caster = (Switch)data; + Switch caster = (Switch) data; - caster.setPowered(leverOn); + caster.setPowered(args[4].trim().equalsIgnoreCase("on") || args[4].trim().equalsIgnoreCase("1")); state.setBlockData(data); state.update(); @@ -84,8 +70,7 @@ public class Command_setlever extends FreedomCommand } else { - msg("Target block " + targetBlock + " is not a lever."); - return true; + msg("That block isn't a lever."); } return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java index 2ef26e69..ff6b372b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java @@ -1,11 +1,11 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Arrays; import java.util.List; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.EnumUtils; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; @@ -24,7 +24,7 @@ public class Command_spawnmob extends FreedomCommand { if (args.length > 0 && args[0].equalsIgnoreCase("list")) { - List types = EnumUtils.getEnumList(EntityType.class); + List types = Arrays.stream(EntityType.values()).toList(); String typeList = StringUtils.join(types, ", ").toLowerCase(); msg(typeList); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_status.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_status.java index 17b7578f..99de6a3d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_status.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_status.java @@ -1,7 +1,5 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.HashMap; -import java.util.Map; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.ChatColor; import org.bukkit.World; @@ -13,19 +11,6 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Shows Minecraft server info, such as authentication status.", usage = "/") public class Command_status extends FreedomCommand { - - public static final Map SERVICE_MAP = new HashMap<>(); - - static - { - SERVICE_MAP.put("minecraft.net", "Minecraft.net"); - SERVICE_MAP.put("login.minecraft.net", "Minecraft Logins"); - SERVICE_MAP.put("session.minecraft.net", "Minecraft Multiplayer Sessions"); - SERVICE_MAP.put("account.mojang.com", "Mojang Accounts Website"); - SERVICE_MAP.put("auth.mojang.com", "Mojang Accounts Login"); - SERVICE_MAP.put("skins.minecraft.net", "Minecraft Skins"); - } - @Override public boolean run(final CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tag.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tag.java index 0ae1b9d4..6c151039 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tag.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tag.java @@ -47,7 +47,7 @@ public class Command_tag extends FreedomCommand for (final Player player : server.getOnlinePlayers()) { - if (plugin.al.isVanished(player.getName()) && !plugin.al.isAdmin(sender)) + if (plugin.al.isVanished(player.getUniqueId()) && !plugin.al.isAdmin(sender)) { continue; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java index 28470eb6..586691ac 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java @@ -1,7 +1,5 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.ArrayList; -import java.util.List; import java.util.Objects; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; @@ -21,17 +19,6 @@ import org.bukkit.inventory.ItemStack; usage = "/ ") public class Command_tossmob extends FreedomCommand { - - public static List getAllMobNames() - { - List names = new ArrayList<>(); - for (EntityType entityType : Groups.MOB_TYPES) - { - names.add(entityType.name()); - } - return names; - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -58,7 +45,7 @@ public class Command_tossmob extends FreedomCommand if (args[0].equalsIgnoreCase("list")) { - msg("Supported mobs: " + getAllMobNames(), ChatColor.GREEN); + msg("Supported mobs: " + Groups.MOB_TYPES.stream().map(Enum::name).toList(), ChatColor.GREEN); return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java index 9511b28d..12c3b2c9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java @@ -6,8 +6,8 @@ import me.totalfreedom.totalfreedommod.rank.Displayable; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -19,7 +19,7 @@ import org.bukkit.scheduler.BukkitRunnable; @CommandParameters(description = "Vanish/unvanish yourself.", usage = "/ [-s[ilent]]", aliases = "v") public class Command_vanish extends FreedomCommand { - + @Override public boolean run(final CommandSender sender, final Player playerSender, final Command cmd, final String commandLabel, final String[] args, final boolean senderIsConsole) { Displayable display = plugin.rm.getDisplay(playerSender); @@ -34,7 +34,7 @@ public class Command_vanish extends FreedomCommand } } - if (plugin.al.isVanished(playerSender.getName())) + if (plugin.al.isVanished(playerSender.getUniqueId())) { if (silent) { @@ -44,7 +44,8 @@ public class Command_vanish extends FreedomCommand { msg("You have unvanished.", ChatColor.GOLD); FUtil.bcastMsg(plugin.rm.craftLoginMessage(playerSender, null)); - FUtil.bcastMsg(playerSender.getName() + " joined the game.", ChatColor.YELLOW); + server.broadcast(Component.translatable("multiplayer.player.joined", Component.text(playerSender.getName())) + .color(NamedTextColor.YELLOW)); plugin.dc.messageChatChannel("**" + playerSender.getName() + " joined the server" + "**", true); } @@ -67,7 +68,7 @@ public class Command_vanish extends FreedomCommand } plugin.esb.setVanished(playerSender.getName(), false); playerSender.setPlayerListName(StringUtils.substring(displayName, 0, 16)); - AdminList.vanished.remove(playerSender.getName()); + AdminList.vanished.remove(playerSender.getUniqueId()); } else { @@ -76,9 +77,13 @@ public class Command_vanish extends FreedomCommand @Override public void run() { - if (plugin.al.isVanished(playerSender.getName())) + if (plugin.al.isVanished(playerSender.getUniqueId())) { - playerSender.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(ChatColor.GOLD + "You are hidden from other players.")); + sender.sendActionBar(Component.text("You are hidden from other players.").color(NamedTextColor.GOLD)); + } + else + { + cancel(); } } }.runTaskTimer(plugin, 0L, 4L); @@ -90,23 +95,19 @@ public class Command_vanish extends FreedomCommand else { msg("You have vanished.", ChatColor.GOLD); - FUtil.bcastMsg(playerSender.getName() + " left the game.", ChatColor.YELLOW); + server.broadcast(Component.translatable("multiplayer.player.left", Component.text(playerSender.getName())) + .color(NamedTextColor.YELLOW)); plugin.dc.messageChatChannel("**" + playerSender.getName() + " left the server" + "**", true); } FLog.info(playerSender.getName() + " is now vanished."); plugin.al.messageAllAdmins(ChatColor.YELLOW + sender.getName() + " has vanished and is now only visible to admins."); - for (Player player : server.getOnlinePlayers()) - { - if (!plugin.al.isAdmin(player)) - { - player.hidePlayer(plugin, playerSender); - } - } + server.getOnlinePlayers().stream().filter(player -> !plugin.al.isAdmin(player)).forEach(player -> + player.hidePlayer(plugin,playerSender)); plugin.esb.setVanished(playerSender.getName(), true); - AdminList.vanished.add(playerSender.getName()); + AdminList.vanished.add(playerSender.getUniqueId()); } return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java index 693c7cf9..f8398db4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java @@ -1,11 +1,10 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; + import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; +import org.apache.commons.lang3.StringUtils; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -31,7 +30,8 @@ public class Command_whitelist extends FreedomCommand msg("There are no whitelisted players."); return true; } - msg("Whitelisted players: " + FUtil.playerListToNames(server.getWhitelistedPlayers())); + msg("Whitelisted players: " + FUtil.listToString(server.getWhitelistedPlayers().stream().map(player -> + player.getName() != null ? player.getName() : player.getUniqueId().toString()).toList())); return true; } @@ -187,23 +187,13 @@ public class Command_whitelist extends FreedomCommand } else if (args[0].equals("remove")) { - return getWhitelistedNames(); + return server.getWhitelistedPlayers().stream().map(OfflinePlayer::getName).filter(Objects::nonNull).toList(); } } return Collections.emptyList(); } - public List getWhitelistedNames() - { - List names = new ArrayList<>(); - for (OfflinePlayer player : server.getWhitelistedPlayers()) - { - names.add(player.getName()); - } - return names; - } - public int purge() { int removed = 0; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java index ac819030..4ec832f3 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -15,17 +16,6 @@ import org.bukkit.entity.Player; @CommandParameters(description = "See who has an item and optionally clear the specified item.", usage = "/ [clear]", aliases = "wh") public class Command_whohas extends FreedomCommand { - - public static List getAllMaterials() - { - List names = new ArrayList<>(); - for (Material material : Material.values()) - { - names.add(material.name()); - } - return names; - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -49,19 +39,16 @@ public class Command_whohas extends FreedomCommand for (final Player player : server.getOnlinePlayers()) { - if (!plugin.al.isAdmin(sender) && plugin.al.isVanished(player.getName())) + if (!plugin.al.isAdmin(sender) && plugin.al.isVanished(player.getUniqueId())) { continue; } if (player.getInventory().contains(material)) { players.add(player.getName()); - if (plugin.al.isAdmin(sender)) + if (plugin.al.isAdmin(sender) && doClear && !plugin.al.isAdmin(player)) { - if (doClear && !plugin.al.isAdmin(player)) - { - player.getInventory().remove(material); - } + player.getInventory().remove(material); } } } @@ -83,7 +70,7 @@ public class Command_whohas extends FreedomCommand { if (args.length == 1) { - return getAllMaterials(); + return Arrays.stream(Material.values()).map(Enum::name).toList(); } if (args.length == 2 && plugin.al.isAdmin(sender)) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java b/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java index ed826d46..00304f35 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java @@ -217,12 +217,9 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter protected Player getPlayer(String name, Boolean nullVanished) { Player player = Bukkit.getPlayer(name); - if (player != null) + if (player != null && nullVanished && plugin.al.isVanished(player.getUniqueId()) && !plugin.al.isAdmin(sender)) { - if (nullVanished && plugin.al.isVanished(player.getName()) && !plugin.al.isAdmin(sender)) - { - return null; - } + return null; } return player; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java index 4c58eb10..019d7843 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java @@ -90,12 +90,6 @@ public enum ConfigEntry DISCORD_SERVER_OWNER_ROLE_ID(String.class, "discord.server_owner_role_id"), DISCORD_INVITE_LINK(String.class, "discord.invite_link"), // - PTERO_URL(String.class, "ptero.url"), - PTERO_DEFAULT_EMAIL_DOMAIN(String.class, "ptero.default_email_domain"), - PTERO_SERVER_UUID(String.class, "ptero.server_uuid"), - PTERO_ADMIN_KEY(String.class, "ptero.admin_key"), - PTERO_SERVER_KEY(String.class, "ptero.server_key"), - // SHOP_ENABLED(Boolean.class, "shop.enabled"), SHOP_TITLE(String.class, "shop.title"), SHOP_PREFIX(String.class, "shop.prefix"), @@ -145,9 +139,6 @@ public enum ConfigEntry AUTOKICK_THRESHOLD(Double.class, "autokick.threshold"), AUTOKICK_TIME(Integer.class, "autokick.time"), // - LOGS_SECRET(String.class, "logs.secret"), - LOGS_URL(String.class, "logs.url"), - // FLATLANDS_GENERATE(Boolean.class, "flatlands.generate"), FLATLANDS_GENERATE_PARAMS(String.class, "flatlands.generate_params"), // @@ -164,7 +155,6 @@ public enum ConfigEntry WILDCARD_BLOCKED_COMMANDS(List.class, "blocked_commands.wildcard"), FORBIDDEN_WORDS(List.class, "forbidden_words"), HOST_SENDER_NAMES(List.class, "host_sender_names"), - FAMOUS_PLAYERS(List.class, "famous_players"), ADMIN_ONLY_MODE(Boolean.class, "admin_only_mode"), ADMIN_INFO(List.class, "admininfo"), VOTING_INFO(List.class, "votinginfo"), @@ -185,19 +175,6 @@ public enum ConfigEntry this.configName = configName; } - public static ConfigEntry findConfigEntry(String name) - { - name = name.toLowerCase().replace("_", ""); - for (ConfigEntry entry : values()) - { - if (entry.toString().toLowerCase().replace("_", "").equals(name)) - { - return entry; - } - } - return null; - } - public Class getType() { return type; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java index 248d6090..156d4582 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java @@ -39,6 +39,7 @@ import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.internal.utils.concurrent.CountingThreadFactory; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang3.RandomStringUtils; import org.bukkit.GameRule; @@ -47,6 +48,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; @@ -195,15 +197,18 @@ public class Discord extends FreedomService catch (LoginException e) { FLog.warning("An invalid token for Discord integration was provided, the bot will not enable."); + enabled = false; } catch (IllegalArgumentException e) { FLog.warning("Discord integration failed to start."); + enabled = false; } catch (NoClassDefFoundError e) { FLog.warning("The JDA plugin is not installed, therefore the discord bot cannot start."); FLog.warning("To resolve this error, please download the latest JDA from: https://github.com/AtlasMediaGroup/Minecraft-JDA/releases"); + enabled = false; } } @@ -226,32 +231,6 @@ public class Discord extends FreedomService messageChatChannel("**Message queue cleared**", true); } - public void sendPteroInfo(PlayerData playerData, String username, String password) - { - User user = getUser(playerData.getDiscordID()); - String message = "The following are your Pterodactyl details:\n\nUsername: " + username + "\nPassword: " + password + "\n\nYou can connect to the panel at " + plugin.ptero.URL; - PrivateChannel privateChannel = user.openPrivateChannel().complete(); - privateChannel.sendMessage(message).complete(); - } - - public User getUser(String id) - { - Guild guild = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); - if (guild == null) - { - FLog.severe("Either the bot is not in the Discord server or it doesn't exist. Check the server ID."); - return null; - } - - Member member = guild.getMemberById(id); - if (member == null) - { - return null; - } - - return member.getUser(); - } - public String generateCode(int size) { return RandomStringUtils.randomNumeric(size); @@ -284,7 +263,7 @@ public class Discord extends FreedomService @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { - if (!plugin.al.isVanished(event.getPlayer().getName())) + if (!plugin.al.isVanished(event.getPlayer().getUniqueId())) { messageChatChannel("**" + deformat(event.getPlayer().getName()) + " joined the server" + "**", true); } @@ -293,7 +272,7 @@ public class Discord extends FreedomService @EventHandler(priority = EventPriority.MONITOR) public void onPlayerLeave(PlayerQuitEvent event) { - if (!plugin.al.isVanished(event.getPlayer().getName())) + if (!plugin.al.isVanished(event.getPlayer().getUniqueId())) { messageChatChannel("**" + deformat(event.getPlayer().getName()) + " left the server" + "**", true); } @@ -534,4 +513,17 @@ public class Discord extends FreedomService messageChatChannel("**Server has started**", true); } } + + @EventHandler(ignoreCancelled = true) + public void onAsyncPlayerChat(AsyncPlayerChatEvent event) + { + Player player = event.getPlayer(); + String message = event.getMessage(); + + if (!ConfigEntry.ADMIN_ONLY_MODE.getBoolean() && !server.hasWhitelist() + && !plugin.pl.getPlayer(player).isMuted() && bot != null) + { + messageChatChannel(player.getName() + " \u00BB " + ChatColor.stripColor(message)); + } + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/commands/ListCommand.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/commands/ListCommand.java index a9bd6783..ac3fda2e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/commands/ListCommand.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/commands/ListCommand.java @@ -70,26 +70,20 @@ public class ListCommand extends DiscordCommandImpl Map> displayables = new HashMap<>(); - for (Player onlinePlayer : Bukkit.getOnlinePlayers()) + Bukkit.getOnlinePlayers().stream().filter(player -> !adminList.isVanished(player.getUniqueId())).forEach(player -> { - if (adminList.isVanished(onlinePlayer.getName())) - { - continue; - } - - - Displayable displayable = rankManager.getDisplay(onlinePlayer); - - final String name = Discord.deformat(onlinePlayer.getName()); + final Displayable displayable = rankManager.getDisplay(player); + final String name = Discord.deformat(player.getName()); if (displayables.containsKey(displayable)) { displayables.get(displayable).add(name); - } else + } + else { displayables.put(displayable, new ArrayList<>(List.of(name))); } - } + }); for (Map.Entry> entry : displayables.entrySet()) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java index 177df52a..83b750c2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java @@ -20,7 +20,6 @@ import me.totalfreedom.totalfreedommod.httpd.module.Module_indefbans; import me.totalfreedom.totalfreedommod.httpd.module.Module_index; import me.totalfreedom.totalfreedommod.httpd.module.Module_list; import me.totalfreedom.totalfreedommod.httpd.module.Module_logfile; -import me.totalfreedom.totalfreedommod.httpd.module.Module_logs; import me.totalfreedom.totalfreedommod.httpd.module.Module_players; import me.totalfreedom.totalfreedommod.httpd.module.Module_punishments; import me.totalfreedom.totalfreedommod.httpd.module.Module_schematic; @@ -96,7 +95,6 @@ public class HTTPDaemon extends FreedomService module("help", Module_help.class, false); module("list", Module_list.class, false); module("logfile", Module_logfile.class, true); - module("logs", Module_logs.class, true); module("indefbans", Module_indefbans.class, true); module("players", Module_players.class, false); module("punishments", Module_punishments.class, true); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java index fa2f5f6d..1b523721 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java @@ -37,7 +37,7 @@ public class Module_list extends HTTPDModule for (Player player : Bukkit.getOnlinePlayers()) { - if (plugin.al.isVanished(player.getName())) + if (plugin.al.isVanished(player.getUniqueId())) { continue; } @@ -67,7 +67,7 @@ public class Module_list extends HTTPDModule operators.add(player.getName()); } - if (hasSpecialTitle(player) && plugin.al.isAdmin(player) && !plugin.al.isVanished(player.getName())) + if (hasSpecialTitle(player) && plugin.al.isAdmin(player) && !plugin.al.isVanished(player.getUniqueId())) { Admin admin = plugin.al.getAdmin(player); switch (admin.getRank()) @@ -112,21 +112,13 @@ public class Module_list extends HTTPDModule final Collection onlinePlayers = Bukkit.getOnlinePlayers(); - int count = onlinePlayers.size() - AdminList.vanished.size(); - body.append("

There are ").append(count < 0 ? 0 : count).append("/") + body.append("

There are ").append(FUtil.getFakePlayerCount()).append("/") .append(Bukkit.getMaxPlayers()).append(" players online:

\r\n"); body.append("
    \r\n"); - for (Player player : onlinePlayers) - { - if (plugin.al.isVanished(player.getName())) - { - continue; - } - String tag = plugin.rm.getDisplay(player).getTag(); - body.append("
  • ").append(tag).append(player.getName()).append("
  • \r\n"); - } + onlinePlayers.stream().filter(player -> !plugin.al.isVanished(player.getUniqueId())).forEach(player -> + body.append("
  • ").append(plugin.rm.getDisplay(player).getTag()).append(player.getName()).append("
  • \r\n")); body.append("
\r\n"); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java deleted file mode 100644 index d9925ca3..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.totalfreedom.totalfreedommod.httpd.module; - -import java.io.File; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; -import me.totalfreedom.totalfreedommod.util.FLog; - -public class Module_logs extends Module_file -{ - - public Module_logs(NanoHTTPD.HTTPSession session) - { - super(session); - } - - @Override - public NanoHTTPD.Response getResponse() - { - if (ConfigEntry.LOGS_SECRET.getString().equals(params.get("password")) && !ConfigEntry.LOGS_SECRET.getString().isEmpty()) - { - FLog.info(session.getSocket().getInetAddress() + " is downloading latest.log."); - return serveFile("latest.log", params, new File("./logs")); - } - else - { - return new NanoHTTPD.Response(NanoHTTPD.Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "Incorrect password."); - } - } -} diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java index 059b4009..3633514d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java @@ -1,89 +1,59 @@ package me.totalfreedom.totalfreedommod.httpd.module; -import me.totalfreedom.totalfreedommod.admin.Admin; +import com.google.gson.Gson; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.util.FUtil; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import org.bukkit.entity.HumanEntity; import org.json.simple.JSONArray; import org.json.simple.JSONObject; -public class Module_players extends HTTPDModule -{ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +public class Module_players extends HTTPDModule +{ + private static final Gson gson = new Gson(); + public Module_players(NanoHTTPD.HTTPSession session) { super(session); } @Override - @SuppressWarnings("unchecked") public NanoHTTPD.Response getResponse() { - final JSONObject responseObject = new JSONObject(); + final Map> responseMap = new HashMap<>(); - final JSONArray players = new JSONArray(); - final JSONArray onlineadmins = new JSONArray(); // updated, never queried. - final JSONArray masterbuilders = new JSONArray(); - final JSONArray admins = new JSONArray(); - final JSONArray senioradmins = new JSONArray(); - final JSONArray developers = new JSONArray(); - final JSONArray executives = new JSONArray(); + final List admins = new ArrayList<>(); + final List senioradmins = new ArrayList<>(); - // All online players - for (Player player : Bukkit.getOnlinePlayers()) + plugin.al.getActiveAdmins().stream().filter(admin -> admin.getName() != null).forEach(admin -> { - if (!plugin.al.isVanished(player.getName())) - { - players.add(player.getName()); - if (plugin.al.isAdmin(player)) - { - onlineadmins.add(player.getName()); - } - } - } - - // Admins - for (Admin admin : plugin.al.getActiveAdmins()) - { - final String username = admin.getName(); switch (admin.getRank()) { - case ADMIN: + case ADMIN -> admins.add(admin.getName()); + case SENIOR_ADMIN -> senioradmins.add(admin.getName()); + default -> { - admins.add(username); - break; - } - case SENIOR_ADMIN: - { - senioradmins.add(username); - break; - } - default: - { - // Do nothing - break; + // Do nothing, keeps Codacy quiet } } - } + }); - masterbuilders.addAll(plugin.pl.getMasterBuilderNames()); + responseMap.put("players", server.getOnlinePlayers().stream().filter(player -> + !plugin.al.isVanished(player.getUniqueId())).map(HumanEntity::getName).toList()); + responseMap.put("masterbuilders", plugin.pl.getMasterBuilderNames()); + responseMap.put("admins", admins); + responseMap.put("senioradmins", senioradmins); + responseMap.put("developers", FUtil.DEVELOPER_NAMES); + responseMap.put("assistantexecutives", ConfigEntry.SERVER_ASSISTANT_EXECUTIVES.getStringList()); + responseMap.put("executives", ConfigEntry.SERVER_EXECUTIVES.getStringList()); - // Developers - developers.addAll(FUtil.DEVELOPER_NAMES); - - // Executives - executives.addAll(ConfigEntry.SERVER_EXECUTIVES.getList()); - - responseObject.put("players", players); - responseObject.put("masterbuilders", masterbuilders); - responseObject.put("admins", admins); - responseObject.put("senioradmins", senioradmins); - responseObject.put("developers", developers); - responseObject.put("executives", executives); - - final NanoHTTPD.Response response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_JSON, responseObject.toString()); + final NanoHTTPD.Response response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_JSON, + gson.toJson(responseMap)); response.addHeader("Access-Control-Allow-Origin", "*"); return response; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java b/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java index ced5a67a..d1f74e10 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java @@ -20,10 +20,8 @@ import java.util.UUID; public class FPlayer { - public static final long AUTO_PURGE_TICKS = 5L * 60L * 20L; - private final TotalFreedomMod plugin; private final String name; @@ -40,8 +38,6 @@ public class FPlayer private int messageCount = 0; private int totalBlockDestroy = 0; private int totalBlockPlace = 0; - private int freecamDestroyCount = 0; - private int freecamPlaceCount = 0; private boolean isOrbiting = false; private double orbitStrength = 10.0; private boolean mobThrowerEnabled = false; @@ -52,11 +48,9 @@ public class FPlayer private boolean mp44Firing = false; private BukkitTask lockupScheduleTask = null; private boolean lockedUp = false; - private String lastMessage = ""; private boolean inAdminchat = false; private boolean allCommandsBlocked = false; private String lastCommand = ""; - private boolean cmdspyEnabled = false; private String tag = null; private int warningCount = 0; @@ -82,11 +76,6 @@ public class FPlayer this.ip = ip; } - public static long getAutoPurgeTicks() - { - return AUTO_PURGE_TICKS; - } - public Player getPlayer() { if (player != null && !player.isOnline()) @@ -110,7 +99,6 @@ public class FPlayer // Ensure admins don't have admin functionality when removed (FS-222) public void removeAdminFunctionality() { - this.setCommandSpy(false); this.setAdminChat(false); this.setFuckoffRadius(0); } @@ -120,11 +108,6 @@ public class FPlayer return isOrbiting; } - public void setOrbiting(boolean orbiting) - { - isOrbiting = orbiting; - } - public void startOrbiting(double strength) { this.isOrbiting = true; @@ -186,26 +169,6 @@ public class FPlayer this.totalBlockPlace = 0; } - public int incrementAndGetFreecamDestroyCount() - { - return this.freecamDestroyCount++; - } - - public void resetFreecamDestroyCount() - { - this.freecamDestroyCount = 0; - } - - public int incrementAndGetFreecamPlaceCount() - { - return this.freecamPlaceCount++; - } - - public void resetFreecamPlaceCount() - { - this.freecamPlaceCount = 0; - } - public void enableMobThrower(EntityType mobThrowerCreature, double mobThrowerSpeed) { this.mobThrowerEnabled = true; @@ -294,7 +257,6 @@ public class FPlayer public void setMuted(boolean muted, int minutes) { FUtil.cancel(unmuteTask); - plugin.mu.MUTED_PLAYERS.remove(getPlayer().getName()); unmuteTask = null; if (!muted) @@ -307,8 +269,6 @@ public class FPlayer return; } - plugin.mu.MUTED_PLAYERS.add(getPlayer().getName()); - // TODO: Simplify this into a Consumer lambda? unmuteTask = new BukkitRunnable() { @@ -323,7 +283,6 @@ public class FPlayer else { FUtil.adminAction(ConfigEntry.SERVER_NAME.getString(), "Unmuting " + getName(), false); - plugin.mu.MUTED_PLAYERS.remove(getName()); } } }.runTaskLater(plugin, minutes * (60L * 20L)); @@ -354,16 +313,6 @@ public class FPlayer this.lockedUp = lockedUp; } - public String getLastMessage() - { - return lastMessage; - } - - public void setLastMessage(String message) - { - this.lastMessage = message; - } - public void setAdminChat(boolean inAdminchat) { this.inAdminchat = inAdminchat; @@ -394,16 +343,6 @@ public class FPlayer this.lastCommand = lastCommand; } - public void setCommandSpy(boolean enabled) - { - this.cmdspyEnabled = enabled; - } - - public boolean cmdspyEnabled() - { - return cmdspyEnabled; - } - public String getTag() { return this.tag; @@ -421,16 +360,6 @@ public class FPlayer } } - public int getWarningCount() - { - return this.warningCount; - } - - public void setWarningCount(int warningCount) - { - this.warningCount = warningCount; - } - public void incrementWarnings(boolean quiet) { this.warningCount++; @@ -463,16 +392,6 @@ public class FPlayer return ip; } - public BukkitTask getUnmuteTask() - { - return unmuteTask; - } - - public void setUnmuteTask(BukkitTask unmuteTask) - { - this.unmuteTask = unmuteTask; - } - public FreezeData getFreezeData() { return freezeData; @@ -488,176 +407,11 @@ public class FPlayer this.fuckoffRadius = fuckoffRadius; } - public int getMessageCount() - { - return messageCount; - } - - public void setMessageCount(int messageCount) - { - this.messageCount = messageCount; - } - - public int getTotalBlockDestroy() - { - return totalBlockDestroy; - } - - public void setTotalBlockDestroy(int totalBlockDestroy) - { - this.totalBlockDestroy = totalBlockDestroy; - } - - public int getTotalBlockPlace() - { - return totalBlockPlace; - } - - public void setTotalBlockPlace(int totalBlockPlace) - { - this.totalBlockPlace = totalBlockPlace; - } - - public int getFreecamDestroyCount() - { - return freecamDestroyCount; - } - - public void setFreecamDestroyCount(int freecamDestroyCount) - { - this.freecamDestroyCount = freecamDestroyCount; - } - - public int getFreecamPlaceCount() - { - return freecamPlaceCount; - } - - public void setFreecamPlaceCount(int freecamPlaceCount) - { - this.freecamPlaceCount = freecamPlaceCount; - } - public CageData getCageData() { return cageData; } - public double getOrbitStrength() - { - return orbitStrength; - } - - public void setOrbitStrength(double orbitStrength) - { - this.orbitStrength = orbitStrength; - } - - public boolean isMobThrowerEnabled() - { - return mobThrowerEnabled; - } - - public void setMobThrowerEnabled(boolean mobThrowerEnabled) - { - this.mobThrowerEnabled = mobThrowerEnabled; - } - - public EntityType getMobThrowerEntity() - { - return mobThrowerEntity; - } - - public void setMobThrowerEntity(EntityType mobThrowerEntity) - { - this.mobThrowerEntity = mobThrowerEntity; - } - - public double getMobThrowerSpeed() - { - return mobThrowerSpeed; - } - - public void setMobThrowerSpeed(double mobThrowerSpeed) - { - this.mobThrowerSpeed = mobThrowerSpeed; - } - - public List getMobThrowerQueue() - { - return mobThrowerQueue; - } - - public BukkitTask getMp44ScheduleTask() - { - return mp44ScheduleTask; - } - - public void setMp44ScheduleTask(BukkitTask mp44ScheduleTask) - { - this.mp44ScheduleTask = mp44ScheduleTask; - } - - public boolean isMp44Armed() - { - return mp44Armed; - } - - public void setMp44Armed(boolean mp44Armed) - { - this.mp44Armed = mp44Armed; - } - - public boolean isMp44Firing() - { - return mp44Firing; - } - - public void setMp44Firing(boolean mp44Firing) - { - this.mp44Firing = mp44Firing; - } - - public BukkitTask getLockupScheduleTask() - { - return lockupScheduleTask; - } - - public void setLockupScheduleTask(BukkitTask lockupScheduleTask) - { - this.lockupScheduleTask = lockupScheduleTask; - } - - public boolean isInAdminchat() - { - return inAdminchat; - } - - public void setInAdminchat(boolean inAdminchat) - { - this.inAdminchat = inAdminchat; - } - - public boolean isAllCommandsBlocked() - { - return allCommandsBlocked; - } - - public void setAllCommandsBlocked(boolean allCommandsBlocked) - { - this.allCommandsBlocked = allCommandsBlocked; - } - - public boolean isCmdspyEnabled() - { - return cmdspyEnabled; - } - - public void setCmdspyEnabled(boolean cmdspyEnabled) - { - this.cmdspyEnabled = cmdspyEnabled; - } - public boolean isEditBlocked() { return editBlocked; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java index 680bc98d..bd15bf1e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java @@ -23,7 +23,7 @@ public class PlayerData private Boolean masterBuilder = false; - private String rideMode = "ask"; + private RideMode rideMode = RideMode.ASK; private int coins; @@ -51,7 +51,7 @@ public class PlayerData tag = resultSet.getString("tag"); discordID = resultSet.getString("discord_id"); masterBuilder = resultSet.getBoolean("master_builder"); - rideMode = resultSet.getString("ride_mode"); + rideMode = RideMode.valueOf(resultSet.getString("ride_mode").toUpperCase()); coins = resultSet.getInt("coins"); items.clear(); items.addAll(FUtil.stringToList(resultSet.getString("items"))); @@ -82,7 +82,7 @@ public class PlayerData "- Total Votes: " + totalVotes + "\n" + "- Display Discord: " + displayDiscord + "\n" + "- Tag: " + FUtil.colorize(tag) + ChatColor.GRAY + "\n" + - "- Ride Mode: " + rideMode + "\n" + + "- Ride Mode: " + rideMode.name() + "\n" + "- Login Message: " + loginMessage; } @@ -194,7 +194,7 @@ public class PlayerData put("tag", tag); put("discord_id", discordID); put("master_builder", masterBuilder); - put("ride_mode", rideMode); + put("ride_mode", rideMode.name()); put("coins", coins); put("items", FUtil.listToString(items)); put("total_votes", totalVotes); @@ -249,12 +249,12 @@ public class PlayerData this.masterBuilder = masterBuilder; } - public String getRideMode() + public RideMode getRideMode() { return rideMode; } - public void setRideMode(String rideMode) + public void setRideMode(RideMode rideMode) { this.rideMode = rideMode; } @@ -308,4 +308,11 @@ public class PlayerData { this.inspect = inspect; } + + public enum RideMode + { + ASK, + NORMAL, + OFF + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java b/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java index e1d07e1e..df39351c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java @@ -193,12 +193,10 @@ public class RankManager extends FreedomService } // Broadcast login message - if (isAdmin || FUtil.isDeveloper(player) || plugin.pl.getData(player).isMasterBuilder() || plugin.pl.getData(player).hasLoginMessage()) + if ((isAdmin || FUtil.isDeveloper(player) || plugin.pl.getData(player).isMasterBuilder() + || plugin.pl.getData(player).hasLoginMessage()) && !plugin.al.isVanished(player.getUniqueId())) { - if (!plugin.al.isVanished(player.getName())) - { - FUtil.bcastMsg(craftLoginMessage(player, null)); - } + FUtil.bcastMsg(craftLoginMessage(player, null)); } // Set display diff --git a/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java b/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java index 5eebbb2d..f12fb04d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java @@ -21,6 +21,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; @@ -411,6 +412,25 @@ public class Shop extends FreedomService } + @EventHandler + public void onPlayerChat(AsyncPlayerChatEvent event) + { + String message = event.getMessage(); + Player player = event.getPlayer(); + + if (ConfigEntry.SHOP_ENABLED.getBoolean() && ConfigEntry.SHOP_REACTIONS_ENABLED.getBoolean() + && !plugin.sh.reactionString.isEmpty() && message.equals(plugin.sh.reactionString)) + { + event.setCancelled(true); + PlayerData data = plugin.pl.getData(player); + data.setCoins(data.getCoins() + plugin.sh.coinsPerReactionWin); + plugin.pl.save(data); + plugin.sh.endReaction(player.getName()); + player.sendMessage(ChatColor.GREEN + "You have been given " + ChatColor.GOLD + + plugin.sh.coinsPerReactionWin + ChatColor.GREEN + " coins!"); + } + } + public ShopItem getShopItem(int slot) { for (ShopItem shopItem : ShopItem.values()) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java b/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java index 336c7934..d435537e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java @@ -84,7 +84,7 @@ public class SQLite extends FreedomService { try { - connection.createStatement().execute("CREATE TABLE `admins` (`uuid` VARCHAR NOT NULL, `ips` VARCHAR NOT NULL, `rank` VARCHAR NOT NULL, `active` BOOLEAN NOT NULL, `last_login` LONG NOT NULL, `command_spy` BOOLEAN NOT NULL, `potion_spy` BOOLEAN NOT NULL, `ac_format` VARCHAR, `ptero_id` VARCHAR);"); + connection.createStatement().execute("CREATE TABLE `admins` (`uuid` VARCHAR NOT NULL, `ips` VARCHAR NOT NULL, `rank` VARCHAR NOT NULL, `active` BOOLEAN NOT NULL, `last_login` LONG NOT NULL, `command_spy` BOOLEAN NOT NULL, `potion_spy` BOOLEAN NOT NULL, `ac_format` VARCHAR);"); } catch (SQLException e) { @@ -219,7 +219,7 @@ public class SQLite extends FreedomService { try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO admins VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); + PreparedStatement statement = connection.prepareStatement("INSERT INTO admins VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); statement.setString(1, admin.getUuid().toString()); statement.setString(2, FUtil.listToString(admin.getIps())); statement.setString(3, admin.getRank().toString()); @@ -228,7 +228,6 @@ public class SQLite extends FreedomService statement.setBoolean(6, admin.getCommandSpy()); statement.setBoolean(7, admin.getPotionSpy()); statement.setString(8, admin.getAcFormat()); - statement.setString(9, admin.getPteroID()); statement.executeUpdate(); } catch (SQLException e) @@ -249,7 +248,7 @@ public class SQLite extends FreedomService statement.setString(4, player.getTag()); statement.setString(5, player.getDiscordID()); statement.setBoolean(6, player.isMasterBuilder()); - statement.setString(7, player.getRideMode()); + statement.setString(7, player.getRideMode().name()); statement.setInt(8, player.getCoins()); statement.setString(9, FUtil.listToString(player.getItems())); statement.setInt(10, player.getTotalVotes()); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java index 191e0feb..15fde2b9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java @@ -69,21 +69,6 @@ public class FSync }.runTask(plugin); } - public static void autoEject(final Player player, final String kickMessage) - { - final TotalFreedomMod plugin = TotalFreedomMod.getPlugin(); - new BukkitRunnable() - { - - @Override - public void run() - { - plugin.ae.autoEject(player, kickMessage); - } - - }.runTask(plugin); - } - public static void bcastMsg(final String message, final ChatColor color) { final TotalFreedomMod plugin = TotalFreedomMod.getPlugin(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java index 3fc1bb7a..512c69ea 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java @@ -4,22 +4,17 @@ import com.earth2me.essentials.utils.DateUtil; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.bukkit.*; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerLoginEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.io.*; import java.lang.management.ManagementFactory; -import java.net.HttpURLConnection; -import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; @@ -91,34 +86,12 @@ public class FUtil ChatColor.DARK_PURPLE, ChatColor.LIGHT_PURPLE); private static final SplittableRandom RANDOM = new SplittableRandom(); - private static final String CHARACTER_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - private static final Map TIMEZONE_LOOKUP = new HashMap<>(); public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; + private static final List regxList = Arrays.asList("y", "mo", "w", "d", "h", "m", "s"); static { - for (ChatColor chatColor : CHAT_COLOR_POOL) - { - CHAT_COLOR_NAMES.put(chatColor.name().toLowerCase().replace("_", ""), chatColor); - } - - for (int i = -12; i <= 12; i++) - { - String sec = String.valueOf(i).replace("-", ""); - if (i > -10 && i < 10) - { - sec = "0" + sec; - } - if (i >= 0) - { - sec = "+" + sec; - } - else - { - sec = "-" + sec; - } - TIMEZONE_LOOKUP.put(i, "GMT" + sec + ":00"); - } + CHAT_COLOR_POOL.forEach(color -> CHAT_COLOR_NAMES.put(color.name().toLowerCase().replace("_", ""), color)); } public static void cancel(BukkitTask task) @@ -139,7 +112,9 @@ public class FUtil public static boolean isExecutive(String name) { - return ConfigEntry.SERVER_OWNERS.getStringList().contains(name) || ConfigEntry.SERVER_EXECUTIVES.getStringList().contains(name) || ConfigEntry.SERVER_ASSISTANT_EXECUTIVES.getStringList().contains(name); + return ConfigEntry.SERVER_OWNERS.getStringList().contains(name) + || ConfigEntry.SERVER_EXECUTIVES.getStringList().contains(name) + || ConfigEntry.SERVER_ASSISTANT_EXECUTIVES.getStringList().contains(name); } public static boolean isDeveloper(Player player) @@ -171,15 +146,8 @@ public class FUtil public static List getPlayerList() { - List names = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) - { - if (!TotalFreedomMod.getPlugin().al.isVanished(player.getName())) - { - names.add(player.getName()); - } - } - return names; + return getServer().getOnlinePlayers().stream().filter(player -> + !TotalFreedomMod.getPlugin().al.isVanished(player.getUniqueId())).map(HumanEntity::getName).toList(); } public static String listToString(List list) @@ -233,58 +201,6 @@ public class FUtil } } - public static List getAllMaterialNames() - { - List names = new ArrayList<>(); - for (Material material : Material.values()) - { - names.add(material.name()); - } - return names; - } - - public static Response sendRequest(String endpoint, String method, List headers, String body) throws IOException - { - URL url = new URL(endpoint); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - - connection.setRequestMethod(method); - - if (headers != null) - { - - for (String header : headers) - { - String[] kv = header.split(":"); - connection.setRequestProperty(kv[0], kv[1]); - } - } - - FLog.info(connection.getRequestMethod()); - - if (body != null) - { - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.writeBytes(body); - outputStream.flush(); - outputStream.close(); - } - - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String inputLine; - StringBuilder response = new StringBuilder(); - - while ((inputLine = in.readLine()) != null) - { - response.append(inputLine); - } - - in.close(); - - return new Response(connection.getResponseCode(), response.toString()); - } - public static void bcastMsg(String message, ChatColor color) { bcastMsg(message, color, true); @@ -365,17 +281,6 @@ public class FUtil } } - private static final List regxList = new ArrayList() - {{ - add("y"); - add("mo"); - add("w"); - add("d"); - add("h"); - add("m"); - add("s"); - }}; - private static long a(String parse) { StringBuilder sb = new StringBuilder(); @@ -447,16 +352,6 @@ public class FUtil return FUtil.getUnixTime(Date.from(instant)); } - public static String playerListToNames(Set players) - { - List names = new ArrayList<>(); - for (OfflinePlayer player : players) - { - names.add(player.getName()); - } - return StringUtils.join(names, ", "); - } - public static String dateToString(Date date) { return new SimpleDateFormat(DATE_STORAGE_FORMAT, Locale.ENGLISH).format(date); @@ -517,17 +412,6 @@ public class FUtil return match; } - public static String getFuzzyIp(String ip) - { - final String[] ipParts = ip.split("\\."); - if (ipParts.length == 4) - { - return String.format("%s.%s.*.*", ipParts[0], ipParts[1]); - } - - return ip; - } - public static ChatColor randomChatColor() { return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size())); @@ -593,33 +477,12 @@ public class FUtil return date.getTime(); } - public static String getNMSVersion() - { - String packageName = getServer().getClass().getPackage().getName(); - return packageName.substring(packageName.lastIndexOf('.') + 1); - } - public static int randomInteger(int min, int max) { int range = max - min + 1; return (int) (Math.random() * range) + min; } - public static String randomString(int length) - { - String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789-_=+[]{};:,.<>~"; - StringBuilder randomString = new StringBuilder(); - for (int i = 0; i < length; i++) - { - int selectedCharacter = randomInteger(1, characters.length()) - 1; - - randomString.append(characters.charAt(selectedCharacter)); - } - - return randomString.toString(); - - } - public static String randomAlphanumericString(int length) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789"; @@ -650,76 +513,8 @@ public class FUtil public static void fixCommandVoid(Player player) { - for (Player p : Bukkit.getOnlinePlayers()) - { - for (Entity passengerEntity : p.getPassengers()) - { - if (passengerEntity == player) - { - p.removePassenger(passengerEntity); - } - } - } - } - - public static char getRandomCharacter() - { - return CHARACTER_STRING.charAt(new SplittableRandom().nextInt(CHARACTER_STRING.length())); - } - - public static void give(Player player, Material material, String coloredName, int amount, String... lore) - { - ItemStack stack = new ItemStack(material, amount); - ItemMeta meta = stack.getItemMeta(); - assert meta != null; - meta.setDisplayName(FUtil.colorize(coloredName)); - List loreList = new ArrayList<>(); - for (String entry : lore) - { - loreList.add(FUtil.colorize(entry)); - } - meta.setLore(loreList); - stack.setItemMeta(meta); - player.getInventory().setItem(player.getInventory().firstEmpty(), stack); - } - - public static Player getRandomPlayer() - { - List players = new ArrayList<>(Bukkit.getOnlinePlayers()); - return players.get(randomInteger(0, players.size() - 1)); - } - - // convert the current time - public static int getTimeInTicks(int tz) - { - if (timeZoneOutOfBounds(tz)) - { - return -1; - } - Calendar date = Calendar.getInstance(TimeZone.getTimeZone(TIMEZONE_LOOKUP.get(tz))); - int res = 0; - for (int i = 0; i < date.get(Calendar.HOUR_OF_DAY) - 6; i++) // oh yeah i don't know why this is 6 hours ahead - { - res += 1000; - } - int addExtra = 0; // we're adding extra to account for repeating decimals - for (int i = 0; i < date.get(Calendar.MINUTE); i++) - { - res += 16; - addExtra++; - if (addExtra == 3) - { - res += 1; - addExtra = 0; - } - } - // this is the best it can be. trust me. - return res; - } - - public static boolean timeZoneOutOfBounds(int tz) - { - return tz < -12 || tz > 12; + Bukkit.getOnlinePlayers().forEach(pl -> + pl.getPassengers().stream().filter(entity -> entity == player).forEach(player::removePassenger)); } public static String getIp(Player player) @@ -805,17 +600,10 @@ public class FUtil }.runTaskLater(TotalFreedomMod.getPlugin(), delay); } - public static int getFakePlayerCount() + public static long getFakePlayerCount() { - int i = TotalFreedomMod.getPlugin().al.vanished.size(); - for (String name : TotalFreedomMod.getPlugin().al.vanished) - { - if (Bukkit.getPlayer(name) == null) - { - i--; - } - } - return getServer().getOnlinePlayers().size() - i; + return getServer().getOnlinePlayers().stream().filter(player -> + !TotalFreedomMod.getPlugin().al.isVanished(player.getUniqueId())).count(); } public static double getMeanAverageDouble(double[] doubles) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java b/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java deleted file mode 100644 index 867b3f7f..00000000 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java +++ /dev/null @@ -1,32 +0,0 @@ -package me.totalfreedom.totalfreedommod.util; - -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -public class Response -{ - private final int code; - private final String message; - - public Response(int code, String message) - { - this.code = code; - this.message = message; - } - - public JSONObject getJSONMessage() throws ParseException - { - return (JSONObject)new JSONParser().parse(message); - } - - public int getCode() - { - return code; - } - - public String getMessage() - { - return message; - } -} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 2aa7a488..dea8a9f3 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -89,19 +89,6 @@ discord: # Invite link for your Discord server invite_link: 'https://discord.com/invite/PW4savJR9a' -# Pterodactyl -ptero: - # URL - do not leave a trailing forward slash - url: '' - # The default email domain used to set email addresses for new users - do not include the @ - default_email_domain: 'example.com' - # Server UUID - server_uuid: '' - # Admin panel API key - admin_key: '' - # Server API key - server_key: '' - # The shop shop: # Enable the shop @@ -606,160 +593,10 @@ first_join_info: - "&eThe server's name doesn't mean we have no rules. Do &6/rules &efor a list of them." - "&aNeed help getting started? Do &2/help &aor a list of commands!" -# Famous players - cannot be banned by username -famous_players: - - honeydew - - xephos - - captainsparklez - - truemu - - kiershar - - fvdisco - - sethbling - - gamechap - - bertiechap - - vechs - - antvenom - - chimneyswift - - deadmau5 - - etho - - ethoslab - - skydoesminecraft - - skythekidrs - - tobyturner - - xxslyfoxhoundxx - - paulsoaresjr - - sips_ - - deadlox - - xxslyxx - - jeromeasf - - grum - - evilseph - - cavemanfilms - - herobrine - - whiteboy7thst - - stampylonghead - - stampylongnose - - dantdm - - gizzy14gazza - - furiousdestroyer - - pewdie - - thecampingrusher - - logdotzip - - ssundee - - mrcrainer - - achileis - - donibobes - - itsjerry - - itsharry - - bebopvox - - clankstar - - jollyajax - - b0xx3r - - vareide - - defek7 - - strutt20 - - appleg - - sterling_ - - hypixel - - huskymudkipz - - setosorcerer - - slamacow - - mrcrayfish - - zexyzek - - synhd - - syndicate - - bajancanadian - - actennisac - - bodil40 - - trumu - - huskymudkipz - - dantdm - - skeppy - - badboyhalo - # Mojang staff below this line - - aeplh - - amir343 - - angryem - - ashrafi - - binni - - blurpi - - bopogamel - - boq - - c418 - - carlmanneh - - carnalizer - - carramel - - darngeek - - dinnerbone - - eldrone - - elevenen - - el_hefe_ - - engst - - excitedze - - frukthamster - - fry_ - - grumm - - hampus - - helloiammarsh - - hey - - hoodad - - ianna_na_na - - jeb_ - - jonkagstrom - - kappe - - klumpig - - krisjelbring - - ladyagnes - - lisa - - mahuldur - - mansolson - - marc - - marc_irl - - masseffect - - midnightenforcer - - minecraftchick - - modhelius - - moesh - - mojangjonas - - mojangsta - - mollstam - - neonmaster - - olle - - olofcarlson - - phreakholm - - poipoichen - - pretto - - profmobius - - razzleberryfox - - searge - - searge_dp - - shoghicp - - slicedlime - - sockerpappan - - themogminer - - theopard - - theputtman - - tom__m - - vaktis - - volgar - - vubui - - xlson - - xsson - - yoloswag4lyfe - - zeeraw - - _alcatras - - _tommo_ - - ____fox____ - # Pet Protect - Prevent tamed pets from being killed. petprotect: enabled: true -# Logviewer -logs: - url: '' - secret: '' - # Mojang service checker service_checker_url: http://status.mojang.com/check diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 308beb03..24ea4a9e 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -10,8 +10,12 @@ softdepend: - WorldEdit - WorldGuard - WorldGuardExtraFlags - - TFGuilds - JDA - Votifier authors: [Madgeek1450, Prozza] -api-version: "1.17" \ No newline at end of file +api-version: "1.17" +libraries: + - org.apache.commons:commons-lang3:3.12.0 + - commons-io:commons-io:2.11.0 + - org.jetbrains:annotations:23.0.0 + - org.javassist:javassist:3.29.1-GA \ No newline at end of file