From b1882a2a109196bd3cf478c1e3ae843495ae42e6 Mon Sep 17 00:00:00 2001
From: Business Goose
Date: Thu, 31 Mar 2022 03:00:43 +0100
Subject: [PATCH] =?UTF-8?q?morle=20=F0=9F=98=A2?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../TotalFreedomMod/TotalFreedomMod.java | 2 +-
.../TotalFreedomMod/admin/AdminList.java | 1266 +++++-----
.../TotalFreedomMod/ban/BanManager.java | 4 +-
.../commands/Command_gadmin.java | 2 +-
.../commands/Command_glist.java | 2 +-
.../commands/Command_gtfo.java | 2 +-
.../commands/Command_myadmin.java | 1 +
.../commands/Command_tban.java | 2 +-
.../commands/Command_tempban.java | 2 +-
.../TotalFreedomMod/commands/Commands.java | 214 +-
.../discord/bridge/DiscordBridge.java | 426 ++--
.../listener/PlayerListener.java | 4 +-
.../TotalFreedomMod/player/PlayerData.java | 3 +-
.../TotalFreedomMod/player/PlayerList.java | 1 +
.../TotalFreedomMod/util/Utilities.java | 2072 ++++++++---------
15 files changed, 1922 insertions(+), 2081 deletions(-)
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/TotalFreedomMod.java b/src/main/java/me/StevenLawson/TotalFreedomMod/TotalFreedomMod.java
index 9d3b055..cf49fd7 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/TotalFreedomMod.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/TotalFreedomMod.java
@@ -16,7 +16,7 @@ import me.StevenLawson.TotalFreedomMod.httpd.HTTPDManager;
import me.StevenLawson.TotalFreedomMod.listener.*;
import me.StevenLawson.TotalFreedomMod.player.HeartBeat;
import me.StevenLawson.TotalFreedomMod.player.PlayerList;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import me.StevenLawson.TotalFreedomMod.world.AdminWorld;
import me.StevenLawson.TotalFreedomMod.world.FlatlandsWorld;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/admin/AdminList.java b/src/main/java/me/StevenLawson/TotalFreedomMod/admin/AdminList.java
index c9dc8fa..a73e3d1 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/admin/AdminList.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/admin/AdminList.java
@@ -2,6 +2,16 @@ package me.StevenLawson.TotalFreedomMod.admin;
import com.google.common.base.Function;
import com.google.common.collect.Sets;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
import me.StevenLawson.TotalFreedomMod.Log;
import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
import me.StevenLawson.TotalFreedomMod.commands.Command_logs;
@@ -10,8 +20,8 @@ import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
import me.StevenLawson.TotalFreedomMod.config.MainConfig;
import me.StevenLawson.TotalFreedomMod.deprecated.twitter.TwitterHandler;
import me.StevenLawson.TotalFreedomMod.discord.sender.DiscordCommandSender;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.player.PlayerRank;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import me.StevenLawson.TotalFreedomMod.world.AdminWorld;
import org.bukkit.Bukkit;
@@ -20,673 +30,589 @@ import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.concurrent.TimeUnit;
-
-public class AdminList
-{
- public static final Function SUPERADMIN_SERVICE;
- private static final Map adminList;
- private static final Set superUUIDs;
- private static final Set telnetUUIDs;
- private static final Set seniorUUIDs;
- private static final Set seniorConsoleNames;
- private static final Set superIps;
- private static int cleanThreshold = 24 * 7; // 1 Week in hours
-
- static
- {
- adminList = new HashMap();
- superUUIDs = new HashSet();
- telnetUUIDs = new HashSet();
- seniorUUIDs = new HashSet();
- seniorConsoleNames = new HashSet();
- superIps = new HashSet();
-
- SUPERADMIN_SERVICE = new Function()
- {
-
- @Override
- public Boolean apply(Player f)
- {
- return isSuperAdmin(f);
- }
- };
- }
-
- private AdminList()
- {
- throw new AssertionError();
- }
-
- public static Set getSuperUUIDs()
- {
- return Collections.unmodifiableSet(superUUIDs);
- }
-
- public static Set getTelnetUUIDs()
- {
- return Collections.unmodifiableSet(telnetUUIDs);
- }
-
- public static Set getSeniorUUIDs()
- {
- return Collections.unmodifiableSet(seniorUUIDs);
- }
-
- public static Set getSeniorConsoleNames()
- {
- return Collections.unmodifiableSet(seniorConsoleNames);
- }
-
- public static Set getSuperadminIps()
- {
- return Collections.unmodifiableSet(superIps);
- }
-
- public static Set getAllAdmins()
- {
- return Sets.newHashSet(adminList.values());
- }
-
- public static Set getSuperNames()
- {
- final Set names = new HashSet();
-
- for (Admin admin : adminList.values())
- {
- if (!admin.isActivated())
- {
- continue;
- }
-
- names.add(admin.getLastLoginName());
- }
-
- return Collections.unmodifiableSet(names);
- }
-
- public static Set getLowercaseSuperNames()
- {
- final Set names = new HashSet();
-
- for (Admin admin : adminList.values())
- {
- if (!admin.isActivated())
- {
- continue;
- }
-
- names.add(admin.getLastLoginName().toLowerCase());
- }
-
- return Collections.unmodifiableSet(names);
- }
-
- public static void setUuid(Admin admin, UUID oldUuid, UUID newUuid)
- {
- if (!adminList.containsKey(oldUuid))
- {
- Log.warning("Could not set new UUID for admin " + admin.getLastLoginName() + ", admin is not loaded!");
- return;
- }
-
- if (oldUuid.equals(newUuid))
- {
- Log.warning("could not set new UUID for admin " + admin.getLastLoginName() + ", UUIDs match.");
- return;
- }
-
- // Add new entry
- final Admin newAdmin = new Admin(
- newUuid,
- admin.getLastLoginName(),
- admin.getLastLogin(),
- admin.getCustomLoginMessage(),
- admin.isTelnetAdmin(),
- admin.isSeniorAdmin(),
- admin.isActivated());
- newAdmin.addIps(admin.getIps());
- adminList.put(newUuid, newAdmin);
- save(newAdmin);
-
- // Remove old entry
- adminList.remove(oldUuid);
- final Configuration config = new Configuration(TotalFreedomMod.plugin, TotalFreedomMod.SUPERADMIN_FILENAME, true);
- config.load();
- config.set("admins." + oldUuid, null);
- config.save();
- }
-
- public static void load()
- {
- adminList.clear();
-
- final Configuration config = new Configuration(TotalFreedomMod.plugin, TotalFreedomMod.SUPERADMIN_FILENAME, true);
- config.load();
-
- cleanThreshold = config.getInt("clean_threshold_hours", cleanThreshold);
-
- // Parse old superadmins
- if (config.isConfigurationSection("superadmins"))
- {
- parseOldConfig(config);
- }
-
- if (!config.isConfigurationSection("admins"))
- {
- Log.warning("Missing admins section in superadmin.yml.");
- return;
- }
-
- final ConfigurationSection section = config.getConfigurationSection("admins");
-
- for (String uuidString : section.getKeys(false))
- {
- if (!Utilities.isUniqueId(uuidString))
- {
- Log.warning("Invalid Unique ID: " + uuidString + " in superadmin.yml, ignoring");
- continue;
- }
-
- final UUID uuid = UUID.fromString(uuidString);
-
- final Admin superadmin = new Admin(uuid, section.getConfigurationSection(uuidString));
- adminList.put(uuid, superadmin);
- }
-
- updateIndexLists();
-
- Log.info("Loaded " + adminList.size() + " admins (" + superUUIDs.size() + " active) and " + superIps.size() + " IPs.");
- }
-
- public static void updateIndexLists()
- {
- superUUIDs.clear();
- telnetUUIDs.clear();
- seniorUUIDs.clear();
- seniorConsoleNames.clear();
- superIps.clear();
-
- for (Admin admin : adminList.values())
- {
- if (!admin.isActivated())
- {
- continue;
- }
-
- final UUID uuid = admin.getUniqueId();
-
- superUUIDs.add(uuid);
-
- for (String ip : admin.getIps())
- {
- superIps.add(ip);
- }
-
- if (admin.isTelnetAdmin())
- {
- telnetUUIDs.add(uuid);
- }
-
- if (admin.isSeniorAdmin())
- {
- seniorUUIDs.add(uuid);
-
- seniorConsoleNames.add(admin.getLastLoginName());
- for (String alias : admin.getConsoleAliases())
- {
- seniorConsoleNames.add(alias.toLowerCase());
- }
- }
- }
-
- AdminWorld.getInstance().wipeAccessCache();
- }
-
- private static void parseOldConfig(Configuration config)
- {
- Log.info("Old superadmin configuration found, parsing...");
-
- final ConfigurationSection section = config.getConfigurationSection("superadmins");
-
- int counter = 0;
- int errors = 0;
-
- for (String admin : config.getConfigurationSection("superadmins").getKeys(false))
- {
- final UUID uuid = UUIDManager.getUniqueId(admin);
-
- if (uuid == null)
- {
- errors++;
- Log.warning("Could not convert admin " + admin + ", UUID could not be found!");
- continue;
- }
-
- config.set("admins." + uuid + ".last_login_name", uuid);
- config.set("admins." + uuid + ".is_activated", section.getBoolean(admin + ".is_activated"));
- config.set("admins." + uuid + ".is_telnet_admin", section.getBoolean(admin + ".is_telnet_admin"));
- config.set("admins." + uuid + ".is_senior_admin", section.getBoolean(admin + ".is_senior_admin"));
- config.set("admins." + uuid + ".last_login", section.getString(admin + ".last_login"));
- config.set("admins." + uuid + ".custom_login_message", section.getString(admin + ".custom_login_message"));
- config.set("admins." + uuid + ".console_aliases", section.getStringList(admin + ".console_aliases"));
- config.set("admins." + uuid + ".ips", section.getStringList(admin + ".ips"));
-
- counter++;
- }
-
- config.set("superadmins", null);
- config.save();
-
- Log.info("Done! " + counter + " admins parsed, " + errors + " errors");
- }
-
- public static void saveAll()
- {
- final Configuration config = new Configuration(TotalFreedomMod.plugin, TotalFreedomMod.SUPERADMIN_FILENAME, true);
- config.load();
-
- config.set("clean_threshold_hours", cleanThreshold);
-
- final Iterator> it = adminList.entrySet().iterator();
- while (it.hasNext())
- {
- final Entry pair = it.next();
-
- final UUID uuid = pair.getKey();
- final Admin superadmin = pair.getValue();
-
- config.set("admins." + uuid + ".last_login_name", superadmin.getLastLoginName());
- config.set("admins." + uuid + ".is_activated", superadmin.isActivated());
- config.set("admins." + uuid + ".is_telnet_admin", superadmin.isTelnetAdmin());
- config.set("admins." + uuid + ".is_senior_admin", superadmin.isSeniorAdmin());
- config.set("admins." + uuid + ".last_login", Utilities.dateToString(superadmin.getLastLogin()));
- config.set("admins." + uuid + ".custom_login_message", superadmin.getCustomLoginMessage());
- config.set("admins." + uuid + ".console_aliases", Utilities.removeDuplicates(superadmin.getConsoleAliases()));
- config.set("admins." + uuid + ".ips", Utilities.removeDuplicates(superadmin.getIps()));
- }
-
- config.save();
- }
-
- public static void save(Admin admin)
- {
- if (!adminList.containsValue(admin))
- {
- Log.warning("Could not save admin " + admin.getLastLoginName() + ", admin is not loaded!");
- return;
- }
-
- final Configuration config = new Configuration(TotalFreedomMod.plugin, TotalFreedomMod.SUPERADMIN_FILENAME, true);
- config.load();
-
- final UUID uuid = admin.getUniqueId();
-
- config.set("admins." + uuid + ".last_login_name", admin.getLastLoginName());
- config.set("admins." + uuid + ".is_activated", admin.isActivated());
- config.set("admins." + uuid + ".is_telnet_admin", admin.isTelnetAdmin());
- config.set("admins." + uuid + ".is_senior_admin", admin.isSeniorAdmin());
- config.set("admins." + uuid + ".last_login", Utilities.dateToString(admin.getLastLogin()));
- config.set("admins." + uuid + ".custom_login_message", admin.getCustomLoginMessage());
- config.set("admins." + uuid + ".console_aliases", Utilities.removeDuplicates(admin.getConsoleAliases()));
- config.set("admins." + uuid + ".ips", Utilities.removeDuplicates(admin.getIps()));
-
- config.save();
- }
-
- public static Admin getEntry(Player player)
- {
- return getEntry(UUIDManager.getUniqueId(player));
- }
-
- public static Admin getEntry(UUID uuid)
- {
- return adminList.get(uuid);
- }
-
- @Deprecated
- public static Admin getEntry(String name)
- {
- for (UUID uuid : adminList.keySet())
- {
- if (adminList.get(uuid).getLastLoginName().equalsIgnoreCase(name))
- {
- return adminList.get(uuid);
- }
- }
- return null;
- }
-
- public static Admin getEntryByIp(String ip)
- {
- return getEntryByIp(ip, false);
- }
-
- public static Admin getEntryByIp(String needleIp, boolean fuzzy)
- {
- Iterator> it = adminList.entrySet().iterator();
- while (it.hasNext())
- {
- final Entry pair = it.next();
- final Admin superadmin = pair.getValue();
-
- if (fuzzy)
- {
- for (String haystackIp : superadmin.getIps())
- {
- if (Utilities.fuzzyIpMatch(needleIp, haystackIp, 3))
- {
- return superadmin;
- }
- }
- }
- else
- {
- if (superadmin.getIps().contains(needleIp))
- {
- return superadmin;
- }
- }
- }
- return null;
- }
-
- public static void updateLastLogin(Player player)
- {
- final Admin admin = getEntry(player);
- if (admin == null)
- {
- return;
- }
- admin.setLastLogin(new Date());
- admin.setLastLoginName(player.getName());
- saveAll();
- }
-
- public static boolean isSuperAdminSafe(UUID uuid, String ip)
- {
- if (TotalFreedomMod.server.getOnlineMode() && uuid != null)
- {
- return AdminList.getSuperUUIDs().contains(uuid);
- }
-
- final Admin admin = AdminList.getEntryByIp(ip);
- return admin != null && admin.isActivated();
- }
-
- public static synchronized boolean isSuperAdminSync(CommandSender sender)
- {
- return isSuperAdmin(sender);
- }
-
- public static boolean isSuperAdmin(CommandSender sender)
- {
- if (!(sender instanceof Player))
- {
- return true;
- }
-
- final Player player = (Player) sender;
-
- if (superIps.contains(Utilities.getIp(player)))
- {
- return true;
- }
-
- return Bukkit.getOnlineMode() && superUUIDs.contains(UUIDManager.getUniqueId(player));
- }
-
- public static boolean isTelnetAdmin(CommandSender sender, boolean verifySuperadmin)
- {
- if (verifySuperadmin)
- {
- if (!isSuperAdmin(sender))
- {
- return false;
- }
- }
-
- if (!(sender instanceof Player))
- {
- return true;
- }
-
- final Admin entry = getEntry((Player) sender);
- if (entry != null)
- {
- return entry.isTelnetAdmin();
- }
-
- return false;
- }
-
- public static boolean isSeniorAdmin(CommandSender sender)
- {
- return isSeniorAdmin(sender, false);
- }
-
- public static boolean isSeniorAdmin(CommandSender sender, boolean verifySuperadmin)
- {
- if (verifySuperadmin)
- {
- if (!isSuperAdmin(sender))
- {
- return false;
- }
- }
-
- if (!(sender instanceof Player))
- {
- return seniorConsoleNames.contains(sender.getName())
- || (MainConfig.getBoolean(ConfigurationEntry.CONSOLE_IS_SENIOR) && sender.getName().equals("CONSOLE"));
- }
-
- if(sender instanceof DiscordCommandSender) {
- PlayerRank rank = PlayerRank.fromSender(sender);
-
- if(rank.equals(PlayerRank.SENIOR)) {
- return true;
- }
- }
-
- final Admin entry = getEntry((Player) sender);
- if (entry != null)
- {
- return entry.isSeniorAdmin();
- }
-
- return false;
- }
-
- public static boolean isIdentityMatched(Player player)
- {
- if (!isSuperAdmin(player))
- {
- return false;
- }
-
- if (Bukkit.getOnlineMode())
- {
- return true;
- }
-
- final Admin entry = getEntry(player);
- if (entry == null)
- {
- return false;
- }
-
- return entry.getUniqueId().equals(UUIDManager.getUniqueId(player));
- }
-
- @Deprecated
- public static boolean checkPartialSuperadminIp(String ip, String name)
- {
- ip = ip.trim();
-
- if (superIps.contains(ip))
- {
- return true;
- }
-
- try
- {
- String matchIp = null;
- for (String testIp : superIps)
- {
- if (Utilities.fuzzyIpMatch(ip, testIp, 3))
- {
- matchIp = testIp;
- break;
- }
- }
-
- if (matchIp != null)
- {
- final Admin entry = getEntryByIp(matchIp);
-
- if (entry == null)
- {
- return true;
- }
-
- if (entry.getLastLoginName().equalsIgnoreCase(name))
- {
- if (!entry.getIps().contains(ip))
- {
- entry.addIp(ip);
- }
- saveAll();
- }
- return true;
-
- }
- }
- catch (Exception ex)
- {
- Log.severe(ex);
- }
-
- return false;
- }
-
- public static boolean isAdminImpostor(Player player)
- {
- if (superUUIDs.contains(UUIDManager.getUniqueId(player)))
- {
- return !isSuperAdmin(player);
- }
-
- return false;
- }
-
- public static void addSuperadmin(OfflinePlayer player)
- {
- final UUID uuid = UUIDManager.getUniqueId(player);
- final String ip = Utilities.getIp(player);
- final boolean canSuperIp = !MainConfig.getList(ConfigurationEntry.NOADMIN_IPS).contains(ip);
-
- if (adminList.containsKey(uuid))
- {
- final Admin superadmin = adminList.get(uuid);
- superadmin.setActivated(true);
-
- if (player.isOnline())
- {
- superadmin.setLastLogin(new Date());
-
- if (ip != null && canSuperIp)
- {
- superadmin.addIp(ip);
- }
- }
-
- saveAll();
- updateIndexLists();
- return;
- }
-
- if (ip == null)
- {
- Log.severe("Could not add superadmin: " + Utilities.formatPlayer(player));
- Log.severe("Could not retrieve IP!");
- return;
- }
-
- if (!canSuperIp)
- {
- Log.warning("Could not add superadmin: " + Utilities.formatPlayer(player));
- Log.warning("IP " + ip + " may not be supered.");
- return;
- }
-
- final Admin superadmin = new Admin(
- uuid,
- player.getName(),
- new Date(),
- "",
- false,
- false,
- true);
- superadmin.addIp(ip);
-
- adminList.put(uuid, superadmin);
-
- saveAll();
- updateIndexLists();
- }
-
- public static void removeSuperadmin(OfflinePlayer player)
- {
- final UUID uuid = UUIDManager.getUniqueId(player);
-
- if (!adminList.containsKey(uuid))
- {
- Log.warning("Could not remove admin: " + Utilities.formatPlayer(player));
- Log.warning("Player is not an admin!");
- return;
- }
-
- final Admin superadmin = adminList.get(uuid);
- superadmin.setActivated(false);
- Command_logs.deactivateSuperadmin(superadmin);
-
- saveAll();
- updateIndexLists();
- }
-
- public static void cleanSuperadminList(boolean verbose)
- {
- Iterator> it = adminList.entrySet().iterator();
- while (it.hasNext())
- {
- final Entry pair = it.next();
- final Admin superadmin = pair.getValue();
-
- if (!superadmin.isActivated() || superadmin.isSeniorAdmin())
- {
- continue;
- }
-
- final Date lastLogin = superadmin.getLastLogin();
- final long lastLoginHours = TimeUnit.HOURS.convert(new Date().getTime() - lastLogin.getTime(), TimeUnit.MILLISECONDS);
-
- if (lastLoginHours > cleanThreshold)
- {
- if (verbose)
- {
- Utilities.adminAction("TotalFreedomMod", "Deactivating superadmin " + superadmin.getLastLoginName() + ", inactive for " + lastLoginHours + " hours.", true);
- }
-
- superadmin.setActivated(false);
- Command_logs.deactivateSuperadmin(superadmin);
- TwitterHandler.delTwitter(superadmin.getLastLoginName());
- }
- }
-
- saveAll();
- updateIndexLists();
- }
+public class AdminList {
+
+ public static final Function SUPERADMIN_SERVICE;
+ private static final Map adminList;
+ private static final Set superUUIDs;
+ private static final Set telnetUUIDs;
+ private static final Set seniorUUIDs;
+ private static final Set seniorConsoleNames;
+ private static final Set superIps;
+ private static int cleanThreshold = 24 * 7; // 1 Week in hours
+
+ static {
+ adminList = new HashMap();
+ superUUIDs = new HashSet();
+ telnetUUIDs = new HashSet();
+ seniorUUIDs = new HashSet();
+ seniorConsoleNames = new HashSet();
+ superIps = new HashSet();
+
+ SUPERADMIN_SERVICE = new Function() {
+
+ @Override
+ public Boolean apply(Player f) {
+ return isSuperAdmin(f);
+ }
+ };
+ }
+
+ private AdminList() {
+ throw new AssertionError();
+ }
+
+ public static Set getSuperUUIDs() {
+ return Collections.unmodifiableSet(superUUIDs);
+ }
+
+ public static Set getTelnetUUIDs() {
+ return Collections.unmodifiableSet(telnetUUIDs);
+ }
+
+ public static Set getSeniorUUIDs() {
+ return Collections.unmodifiableSet(seniorUUIDs);
+ }
+
+ public static Set getSeniorConsoleNames() {
+ return Collections.unmodifiableSet(seniorConsoleNames);
+ }
+
+ public static Set getSuperadminIps() {
+ return Collections.unmodifiableSet(superIps);
+ }
+
+ public static Set getAllAdmins() {
+ return Sets.newHashSet(adminList.values());
+ }
+
+ public static Set getSuperNames() {
+ final Set names = new HashSet();
+
+ for (Admin admin : adminList.values()) {
+ if (!admin.isActivated()) {
+ continue;
+ }
+
+ names.add(admin.getLastLoginName());
+ }
+
+ return Collections.unmodifiableSet(names);
+ }
+
+ public static Set getLowercaseSuperNames() {
+ final Set names = new HashSet();
+
+ for (Admin admin : adminList.values()) {
+ if (!admin.isActivated()) {
+ continue;
+ }
+
+ names.add(admin.getLastLoginName().toLowerCase());
+ }
+
+ return Collections.unmodifiableSet(names);
+ }
+
+ public static void setUuid(Admin admin, UUID oldUuid, UUID newUuid) {
+ if (!adminList.containsKey(oldUuid)) {
+ Log.warning("Could not set new UUID for admin " + admin.getLastLoginName()
+ + ", admin is not loaded!");
+ return;
+ }
+
+ if (oldUuid.equals(newUuid)) {
+ Log.warning(
+ "could not set new UUID for admin " + admin.getLastLoginName() + ", UUIDs match.");
+ return;
+ }
+
+ // Add new entry
+ final Admin newAdmin = new Admin(
+ newUuid,
+ admin.getLastLoginName(),
+ admin.getLastLogin(),
+ admin.getCustomLoginMessage(),
+ admin.isTelnetAdmin(),
+ admin.isSeniorAdmin(),
+ admin.isActivated());
+ newAdmin.addIps(admin.getIps());
+ adminList.put(newUuid, newAdmin);
+ save(newAdmin);
+
+ // Remove old entry
+ adminList.remove(oldUuid);
+ final Configuration config = new Configuration(TotalFreedomMod.plugin,
+ TotalFreedomMod.SUPERADMIN_FILENAME, true);
+ config.load();
+ config.set("admins." + oldUuid, null);
+ config.save();
+ }
+
+ public static void load() {
+ adminList.clear();
+
+ final Configuration config = new Configuration(TotalFreedomMod.plugin,
+ TotalFreedomMod.SUPERADMIN_FILENAME, true);
+ config.load();
+
+ cleanThreshold = config.getInt("clean_threshold_hours", cleanThreshold);
+
+ // Parse old superadmins
+ if (config.isConfigurationSection("superadmins")) {
+ parseOldConfig(config);
+ }
+
+ if (!config.isConfigurationSection("admins")) {
+ Log.warning("Missing admins section in superadmin.yml.");
+ return;
+ }
+
+ final ConfigurationSection section = config.getConfigurationSection("admins");
+
+ for (String uuidString : section.getKeys(false)) {
+ if (!Utilities.isUniqueId(uuidString)) {
+ Log.warning("Invalid Unique ID: " + uuidString + " in superadmin.yml, ignoring");
+ continue;
+ }
+
+ final UUID uuid = UUID.fromString(uuidString);
+
+ final Admin superadmin = new Admin(uuid, section.getConfigurationSection(uuidString));
+ adminList.put(uuid, superadmin);
+ }
+
+ updateIndexLists();
+
+ Log.info("Loaded " + adminList.size() + " admins (" + superUUIDs.size() + " active) and "
+ + superIps.size() + " IPs.");
+ }
+
+ public static void updateIndexLists() {
+ superUUIDs.clear();
+ telnetUUIDs.clear();
+ seniorUUIDs.clear();
+ seniorConsoleNames.clear();
+ superIps.clear();
+
+ for (Admin admin : adminList.values()) {
+ if (!admin.isActivated()) {
+ continue;
+ }
+
+ final UUID uuid = admin.getUniqueId();
+
+ superUUIDs.add(uuid);
+
+ for (String ip : admin.getIps()) {
+ superIps.add(ip);
+ }
+
+ if (admin.isTelnetAdmin()) {
+ telnetUUIDs.add(uuid);
+ }
+
+ if (admin.isSeniorAdmin()) {
+ seniorUUIDs.add(uuid);
+
+ seniorConsoleNames.add(admin.getLastLoginName());
+ for (String alias : admin.getConsoleAliases()) {
+ seniorConsoleNames.add(alias.toLowerCase());
+ }
+ }
+ }
+
+ AdminWorld.getInstance().wipeAccessCache();
+ }
+
+ private static void parseOldConfig(Configuration config) {
+ Log.info("Old superadmin configuration found, parsing...");
+
+ final ConfigurationSection section = config.getConfigurationSection("superadmins");
+
+ int counter = 0;
+ int errors = 0;
+
+ for (String admin : config.getConfigurationSection("superadmins").getKeys(false)) {
+ final UUID uuid = UUIDManager.getUniqueId(admin);
+
+ if (uuid == null) {
+ errors++;
+ Log.warning("Could not convert admin " + admin + ", UUID could not be found!");
+ continue;
+ }
+
+ config.set("admins." + uuid + ".last_login_name", uuid);
+ config.set("admins." + uuid + ".is_activated",
+ section.getBoolean(admin + ".is_activated"));
+ config.set("admins." + uuid + ".is_telnet_admin",
+ section.getBoolean(admin + ".is_telnet_admin"));
+ config.set("admins." + uuid + ".is_senior_admin",
+ section.getBoolean(admin + ".is_senior_admin"));
+ config.set("admins." + uuid + ".last_login", section.getString(admin + ".last_login"));
+ config.set("admins." + uuid + ".custom_login_message",
+ section.getString(admin + ".custom_login_message"));
+ config.set("admins." + uuid + ".console_aliases",
+ section.getStringList(admin + ".console_aliases"));
+ config.set("admins." + uuid + ".ips", section.getStringList(admin + ".ips"));
+
+ counter++;
+ }
+
+ config.set("superadmins", null);
+ config.save();
+
+ Log.info("Done! " + counter + " admins parsed, " + errors + " errors");
+ }
+
+ public static void saveAll() {
+ final Configuration config = new Configuration(TotalFreedomMod.plugin,
+ TotalFreedomMod.SUPERADMIN_FILENAME, true);
+ config.load();
+
+ config.set("clean_threshold_hours", cleanThreshold);
+
+ final Iterator> it = adminList.entrySet().iterator();
+ while (it.hasNext()) {
+ final Entry pair = it.next();
+
+ final UUID uuid = pair.getKey();
+ final Admin superadmin = pair.getValue();
+
+ config.set("admins." + uuid + ".last_login_name", superadmin.getLastLoginName());
+ config.set("admins." + uuid + ".is_activated", superadmin.isActivated());
+ config.set("admins." + uuid + ".is_telnet_admin", superadmin.isTelnetAdmin());
+ config.set("admins." + uuid + ".is_senior_admin", superadmin.isSeniorAdmin());
+ config.set("admins." + uuid + ".last_login",
+ Utilities.dateToString(superadmin.getLastLogin()));
+ config.set("admins." + uuid + ".custom_login_message",
+ superadmin.getCustomLoginMessage());
+ config.set("admins." + uuid + ".console_aliases",
+ Utilities.removeDuplicates(superadmin.getConsoleAliases()));
+ config.set("admins." + uuid + ".ips", Utilities.removeDuplicates(superadmin.getIps()));
+ }
+
+ config.save();
+ }
+
+ public static void save(Admin admin) {
+ if (!adminList.containsValue(admin)) {
+ Log.warning(
+ "Could not save admin " + admin.getLastLoginName() + ", admin is not loaded!");
+ return;
+ }
+
+ final Configuration config = new Configuration(TotalFreedomMod.plugin,
+ TotalFreedomMod.SUPERADMIN_FILENAME, true);
+ config.load();
+
+ final UUID uuid = admin.getUniqueId();
+
+ config.set("admins." + uuid + ".last_login_name", admin.getLastLoginName());
+ config.set("admins." + uuid + ".is_activated", admin.isActivated());
+ config.set("admins." + uuid + ".is_telnet_admin", admin.isTelnetAdmin());
+ config.set("admins." + uuid + ".is_senior_admin", admin.isSeniorAdmin());
+ config.set("admins." + uuid + ".last_login", Utilities.dateToString(admin.getLastLogin()));
+ config.set("admins." + uuid + ".custom_login_message", admin.getCustomLoginMessage());
+ config.set("admins." + uuid + ".console_aliases",
+ Utilities.removeDuplicates(admin.getConsoleAliases()));
+ config.set("admins." + uuid + ".ips", Utilities.removeDuplicates(admin.getIps()));
+
+ config.save();
+ }
+
+ public static Admin getEntry(Player player) {
+ return getEntry(UUIDManager.getUniqueId(player));
+ }
+
+ public static Admin getEntry(UUID uuid) {
+ return adminList.get(uuid);
+ }
+
+ @Deprecated
+ public static Admin getEntry(String name) {
+ for (UUID uuid : adminList.keySet()) {
+ if (adminList.get(uuid).getLastLoginName().equalsIgnoreCase(name)) {
+ return adminList.get(uuid);
+ }
+ }
+ return null;
+ }
+
+ public static Admin getEntryByIp(String ip) {
+ return getEntryByIp(ip, false);
+ }
+
+ public static Admin getEntryByIp(String needleIp, boolean fuzzy) {
+ Iterator> it = adminList.entrySet().iterator();
+ while (it.hasNext()) {
+ final Entry pair = it.next();
+ final Admin superadmin = pair.getValue();
+
+ if (fuzzy) {
+ for (String haystackIp : superadmin.getIps()) {
+ if (Utilities.fuzzyIpMatch(needleIp, haystackIp, 3)) {
+ return superadmin;
+ }
+ }
+ } else {
+ if (superadmin.getIps().contains(needleIp)) {
+ return superadmin;
+ }
+ }
+ }
+ return null;
+ }
+
+ public static void updateLastLogin(Player player) {
+ final Admin admin = getEntry(player);
+ if (admin == null) {
+ return;
+ }
+ admin.setLastLogin(new Date());
+ admin.setLastLoginName(player.getName());
+ saveAll();
+ }
+
+ public static boolean isSuperAdminSafe(UUID uuid, String ip) {
+ if (TotalFreedomMod.server.getOnlineMode() && uuid != null) {
+ return AdminList.getSuperUUIDs().contains(uuid);
+ }
+
+ final Admin admin = AdminList.getEntryByIp(ip);
+ return admin != null && admin.isActivated();
+ }
+
+ public static synchronized boolean isSuperAdminSync(CommandSender sender) {
+ return isSuperAdmin(sender);
+ }
+
+ public static boolean isSuperAdmin(CommandSender sender) {
+ if (!(sender instanceof Player)) {
+ return true;
+ }
+
+ final Player player = (Player) sender;
+
+ if (superIps.contains(Utilities.getIp(player))) {
+ return true;
+ }
+
+ return Bukkit.getOnlineMode() && superUUIDs.contains(UUIDManager.getUniqueId(player));
+ }
+
+ public static boolean isTelnetAdmin(CommandSender sender, boolean verifySuperadmin) {
+ if (verifySuperadmin) {
+ if (!isSuperAdmin(sender)) {
+ return false;
+ }
+ }
+
+ if (!(sender instanceof Player)) {
+ return true;
+ }
+
+ final Admin entry = getEntry((Player) sender);
+ if (entry != null) {
+ return entry.isTelnetAdmin();
+ }
+
+ return false;
+ }
+
+ public static boolean isSeniorAdmin(CommandSender sender) {
+ return isSeniorAdmin(sender, false);
+ }
+
+ public static boolean isSeniorAdmin(CommandSender sender, boolean verifySuperadmin) {
+ if (verifySuperadmin) {
+ if (!isSuperAdmin(sender)) {
+ return false;
+ }
+ }
+
+ if (!(sender instanceof Player)) {
+ return seniorConsoleNames.contains(sender.getName())
+ || (MainConfig.getBoolean(ConfigurationEntry.CONSOLE_IS_SENIOR) && sender.getName()
+ .equals("CONSOLE"));
+ }
+
+ if (sender instanceof DiscordCommandSender) {
+ PlayerRank rank = PlayerRank.fromSender(sender);
+
+ if (rank.equals(PlayerRank.SENIOR)) {
+ return true;
+ }
+ }
+
+ final Admin entry = getEntry((Player) sender);
+ if (entry != null) {
+ return entry.isSeniorAdmin();
+ }
+
+ return false;
+ }
+
+ public static boolean isIdentityMatched(Player player) {
+ if (!isSuperAdmin(player)) {
+ return false;
+ }
+
+ if (Bukkit.getOnlineMode()) {
+ return true;
+ }
+
+ final Admin entry = getEntry(player);
+ if (entry == null) {
+ return false;
+ }
+
+ return entry.getUniqueId().equals(UUIDManager.getUniqueId(player));
+ }
+
+ @Deprecated
+ public static boolean checkPartialSuperadminIp(String ip, String name) {
+ ip = ip.trim();
+
+ if (superIps.contains(ip)) {
+ return true;
+ }
+
+ try {
+ String matchIp = null;
+ for (String testIp : superIps) {
+ if (Utilities.fuzzyIpMatch(ip, testIp, 3)) {
+ matchIp = testIp;
+ break;
+ }
+ }
+
+ if (matchIp != null) {
+ final Admin entry = getEntryByIp(matchIp);
+
+ if (entry == null) {
+ return true;
+ }
+
+ if (entry.getLastLoginName().equalsIgnoreCase(name)) {
+ if (!entry.getIps().contains(ip)) {
+ entry.addIp(ip);
+ }
+ saveAll();
+ }
+ return true;
+
+ }
+ } catch (Exception ex) {
+ Log.severe(ex);
+ }
+
+ return false;
+ }
+
+ public static boolean isAdminImpostor(Player player) {
+ if (superUUIDs.contains(UUIDManager.getUniqueId(player))) {
+ return !isSuperAdmin(player);
+ }
+
+ return false;
+ }
+
+ public static void addSuperadmin(OfflinePlayer player) {
+ final UUID uuid = UUIDManager.getUniqueId(player);
+ final String ip = Utilities.getIp(player);
+ final boolean canSuperIp = !MainConfig.getList(ConfigurationEntry.NOADMIN_IPS).contains(ip);
+
+ if (adminList.containsKey(uuid)) {
+ final Admin superadmin = adminList.get(uuid);
+ superadmin.setActivated(true);
+
+ if (player.isOnline()) {
+ superadmin.setLastLogin(new Date());
+
+ if (ip != null && canSuperIp) {
+ superadmin.addIp(ip);
+ }
+ }
+
+ saveAll();
+ updateIndexLists();
+ return;
+ }
+
+ if (ip == null) {
+ Log.severe("Could not add superadmin: " + Utilities.formatPlayer(player));
+ Log.severe("Could not retrieve IP!");
+ return;
+ }
+
+ if (!canSuperIp) {
+ Log.warning("Could not add superadmin: " + Utilities.formatPlayer(player));
+ Log.warning("IP " + ip + " may not be supered.");
+ return;
+ }
+
+ final Admin superadmin = new Admin(
+ uuid,
+ player.getName(),
+ new Date(),
+ "",
+ false,
+ false,
+ true);
+ superadmin.addIp(ip);
+
+ adminList.put(uuid, superadmin);
+
+ saveAll();
+ updateIndexLists();
+ }
+
+ public static void removeSuperadmin(OfflinePlayer player) {
+ final UUID uuid = UUIDManager.getUniqueId(player);
+
+ if (!adminList.containsKey(uuid)) {
+ Log.warning("Could not remove admin: " + Utilities.formatPlayer(player));
+ Log.warning("Player is not an admin!");
+ return;
+ }
+
+ final Admin superadmin = adminList.get(uuid);
+ superadmin.setActivated(false);
+ Command_logs.deactivateSuperadmin(superadmin);
+
+ saveAll();
+ updateIndexLists();
+ }
+
+ public static void cleanSuperadminList(boolean verbose) {
+ Iterator> it = adminList.entrySet().iterator();
+ while (it.hasNext()) {
+ final Entry pair = it.next();
+ final Admin superadmin = pair.getValue();
+
+ if (!superadmin.isActivated() || superadmin.isSeniorAdmin()) {
+ continue;
+ }
+
+ final Date lastLogin = superadmin.getLastLogin();
+ final long lastLoginHours = TimeUnit.HOURS.convert(
+ new Date().getTime() - lastLogin.getTime(), TimeUnit.MILLISECONDS);
+
+ if (lastLoginHours > cleanThreshold) {
+ if (verbose) {
+ Utilities.adminAction("TotalFreedomMod",
+ "Deactivating superadmin " + superadmin.getLastLoginName()
+ + ", inactive for " + lastLoginHours + " hours.", true);
+ }
+
+ superadmin.setActivated(false);
+ Command_logs.deactivateSuperadmin(superadmin);
+ TwitterHandler.delTwitter(superadmin.getLastLoginName());
+ }
+ }
+
+ saveAll();
+ updateIndexLists();
+ }
}
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/ban/BanManager.java b/src/main/java/me/StevenLawson/TotalFreedomMod/ban/BanManager.java
index ca468cf..18a939e 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/ban/BanManager.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/ban/BanManager.java
@@ -5,8 +5,8 @@ import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
import me.StevenLawson.TotalFreedomMod.ban.Ban.BanType;
import me.StevenLawson.TotalFreedomMod.config.Configuration;
import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager.TFM_UuidResolver;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager.TFM_UuidResolver;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.entity.Player;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gadmin.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gadmin.java
index 5e8fdd7..2da4509 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gadmin.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gadmin.java
@@ -2,7 +2,7 @@ package me.StevenLawson.TotalFreedomMod.commands;
import me.StevenLawson.TotalFreedomMod.ban.BanManager;
import me.StevenLawson.TotalFreedomMod.player.PlayerData;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_glist.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_glist.java
index 02bab1b..4125b5c 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_glist.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_glist.java
@@ -6,7 +6,7 @@ import me.StevenLawson.TotalFreedomMod.ban.BanManager;
import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
import me.StevenLawson.TotalFreedomMod.player.Player;
import me.StevenLawson.TotalFreedomMod.player.PlayerList;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gtfo.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gtfo.java
index 70b9d6c..46a35ca 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gtfo.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_gtfo.java
@@ -3,7 +3,7 @@ package me.StevenLawson.TotalFreedomMod.commands;
import me.StevenLawson.TotalFreedomMod.ban.Ban;
import me.StevenLawson.TotalFreedomMod.ban.BanManager;
import me.StevenLawson.TotalFreedomMod.bridge.WorldEditBridge;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import me.StevenLawson.TotalFreedomMod.world.RollbackManager;
import org.apache.commons.lang3.ArrayUtils;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_myadmin.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_myadmin.java
index 3a8c1e7..ba61373 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_myadmin.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_myadmin.java
@@ -14,6 +14,7 @@ public class Command_myadmin extends FreedomCommand {
@Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel,
String[] args, boolean senderIsConsole) {
+
final UUID uuid = sender_p.getUniqueId(); // Get the sender's uuid as a variable.
if (args.length == 1) {
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tban.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tban.java
index d2f9a70..d4ba73c 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tban.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tban.java
@@ -2,7 +2,7 @@ package me.StevenLawson.TotalFreedomMod.commands;
import me.StevenLawson.TotalFreedomMod.ban.Ban;
import me.StevenLawson.TotalFreedomMod.ban.BanManager;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.ChatColor;
import org.bukkit.Location;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tempban.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tempban.java
index ef3abc9..ba009cd 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tempban.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_tempban.java
@@ -2,7 +2,7 @@ package me.StevenLawson.TotalFreedomMod.commands;
import me.StevenLawson.TotalFreedomMod.ban.Ban;
import me.StevenLawson.TotalFreedomMod.ban.BanManager;
-import me.StevenLawson.TotalFreedomMod.player.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Commands.java b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Commands.java
index 2cc25dd..90b0e9d 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Commands.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/commands/Commands.java
@@ -3,110 +3,112 @@ package me.StevenLawson.TotalFreedomMod.commands;
import org.bukkit.plugin.java.JavaPlugin;
public class Commands {
- public static void registerCommands(JavaPlugin plugin) {
- plugin.getCommand("adminmode").setExecutor(new Command_adminmode());
- plugin.getCommand("adminworld").setExecutor(new Command_adminworld());
- plugin.getCommand("blockcmd").setExecutor(new Command_blockcmd());
- plugin.getCommand("cage").setExecutor(new Command_cage());
- plugin.getCommand("cake").setExecutor(new Command_cake());
- plugin.getCommand("cartsit").setExecutor(new Command_cartsit());
- plugin.getCommand("cbtool").setExecutor(new Command_cbtool());
- plugin.getCommand("cmdlist").setExecutor(new Command_cmdlist());
- plugin.getCommand("cmdspy").setExecutor(new Command_cmdspy());
- plugin.getCommand("colorme").setExecutor(new Command_colorme());
- plugin.getCommand("creative").setExecutor(new Command_creative());
- plugin.getCommand("csay").setExecutor(new Command_csay());
- plugin.getCommand("deafen").setExecutor(new Command_deafen());
- plugin.getCommand("debug").setExecutor(new Command_debug());
- plugin.getCommand("denick").setExecutor(new Command_denick());
- plugin.getCommand("deop").setExecutor(new Command_deop());
- plugin.getCommand("deopall").setExecutor(new Command_deopall());
- plugin.getCommand("dispfill").setExecutor(new Command_dispfill());
- plugin.getCommand("doom").setExecutor(new Command_doom());
- plugin.getCommand("enchant").setExecutor(new Command_enchant());
- plugin.getCommand("ender").setExecutor(new Command_ender());
- plugin.getCommand("expel").setExecutor(new Command_expel());
- plugin.getCommand("findip").setExecutor(new Command_findip());
- plugin.getCommand("flatlands").setExecutor(new Command_flatlands());
- plugin.getCommand("fr").setExecutor(new Command_fr());
- plugin.getCommand("fuckoff").setExecutor(new Command_fuckoff());
- plugin.getCommand("gadmin").setExecutor(new Command_gadmin());
- plugin.getCommand("gcmd").setExecutor(new Command_gcmd());
- plugin.getCommand("glist").setExecutor(new Command_glist());
- plugin.getCommand("gtfo").setExecutor(new Command_gtfo());
- plugin.getCommand("halt").setExecutor(new Command_halt());
- plugin.getCommand("health").setExecutor(new Command_health());
- plugin.getCommand("invis").setExecutor(new Command_invis());
- plugin.getCommand("jumppads").setExecutor(new Command_jumppads());
- plugin.getCommand("kicknoob").setExecutor(new Command_kicknoob());
- plugin.getCommand("landmine").setExecutor(new Command_landmine());
- plugin.getCommand("lastcmd").setExecutor(new Command_lastcmd());
- plugin.getCommand("list").setExecutor(new Command_list());
- plugin.getCommand("localspawn").setExecutor(new Command_localspawn());
- plugin.getCommand("lockup").setExecutor(new Command_lockup());
- plugin.getCommand("logs").setExecutor(new Command_logs());
- plugin.getCommand("moblimiter").setExecutor(new Command_moblimiter());
- plugin.getCommand("mp").setExecutor(new Command_mp());
- plugin.getCommand("mp44").setExecutor(new Command_mp44());
- plugin.getCommand("myadmin").setExecutor(new Command_myadmin());
- plugin.getCommand("nether").setExecutor(new Command_nether());
- plugin.getCommand("nf").setExecutor(new Command_nf());
- plugin.getCommand("nickclean").setExecutor(new Command_nickclean());
- plugin.getCommand("nicknyan").setExecutor(new Command_nicknyan());
- plugin.getCommand("o").setExecutor(new Command_o());
- plugin.getCommand("onlinemode").setExecutor(new Command_onlinemode());
- plugin.getCommand("op").setExecutor(new Command_op());
- plugin.getCommand("opall").setExecutor(new Command_opall());
- plugin.getCommand("opme").setExecutor(new Command_opme());
- plugin.getCommand("ops").setExecutor(new Command_ops());
- plugin.getCommand("orbit").setExecutor(new Command_orbit());
- plugin.getCommand("overlord").setExecutor(new Command_overlord());
- plugin.getCommand("permban").setExecutor(new Command_permban());
- plugin.getCommand("plugincontrol").setExecutor(new Command_plugincontrol());
- plugin.getCommand("potion").setExecutor(new Command_potion());
- plugin.getCommand("premium").setExecutor(new Command_premium());
- plugin.getCommand("protectarea").setExecutor(new Command_protectarea());
- plugin.getCommand("purgeall").setExecutor(new Command_purgeall());
- plugin.getCommand("qdeop").setExecutor(new Command_qdeop());
- plugin.getCommand("qop").setExecutor(new Command_qop());
- plugin.getCommand("radar").setExecutor(new Command_radar());
- plugin.getCommand("rank").setExecutor(new Command_rank());
- plugin.getCommand("rawsay").setExecutor(new Command_rawsay());
- plugin.getCommand("rd").setExecutor(new Command_rd());
- plugin.getCommand("report").setExecutor(new Command_report());
- plugin.getCommand("ro").setExecutor(new Command_ro());
- plugin.getCommand("rollback").setExecutor(new Command_rollback());
- plugin.getCommand("saconfig").setExecutor(new Command_saconfig());
- plugin.getCommand("say").setExecutor(new Command_say());
- plugin.getCommand("setl").setExecutor(new Command_setl());
- plugin.getCommand("setlevel").setExecutor(new Command_setlevel());
- plugin.getCommand("setlever").setExecutor(new Command_setlever());
- plugin.getCommand("setspawnworld").setExecutor(new Command_setspawnworld());
- plugin.getCommand("smite").setExecutor(new Command_smite());
- plugin.getCommand("spectator").setExecutor(new Command_spectator());
- plugin.getCommand("status").setExecutor(new Command_status());
- plugin.getCommand("stfu").setExecutor(new Command_stfu());
- plugin.getCommand("stop").setExecutor(new Command_stop());
- plugin.getCommand("survival").setExecutor(new Command_survival());
- plugin.getCommand("tag").setExecutor(new Command_tag());
- plugin.getCommand("tagnyan").setExecutor(new Command_tagnyan());
- plugin.getCommand("tban").setExecutor(new Command_tban());
- plugin.getCommand("tempban").setExecutor(new Command_tempban());
- plugin.getCommand("tfbanlist").setExecutor(new Command_tfbanlist());
- plugin.getCommand("tfipbanlist").setExecutor(new Command_tfipbanlist());
- plugin.getCommand("tfm").setExecutor(new Command_tfm());
- plugin.getCommand("toggle").setExecutor(new Command_toggle());
- plugin.getCommand("tossmob").setExecutor(new Command_tossmob());
- plugin.getCommand("trail").setExecutor(new Command_trail());
- plugin.getCommand("updatetfm").setExecutor(new Command_updatetfm());
- plugin.getCommand("uuid").setExecutor(new Command_uuid());
- plugin.getCommand("warn").setExecutor(new Command_warn());
- plugin.getCommand("whitelist").setExecutor(new Command_whitelist());
- plugin.getCommand("whohas").setExecutor(new Command_whohas());
- plugin.getCommand("wildcard").setExecutor(new Command_wildcard());
- plugin.getCommand("wipeflatlands").setExecutor(new Command_wipeflatlands());
- plugin.getCommand("wipeuserdata").setExecutor(new Command_wipeuserdata());
- plugin.getCommand("whoami").setExecutor(new Command_whoami());
- plugin.getCommand("resetplayer").setExecutor(new Command_resetplayer());
- }
+
+ public static void registerCommands(JavaPlugin plugin) {
+ plugin.getCommand("adminmode").setExecutor(new Command_adminmode());
+ plugin.getCommand("adminworld").setExecutor(new Command_adminworld());
+ plugin.getCommand("blockcmd").setExecutor(new Command_blockcmd());
+ plugin.getCommand("cage").setExecutor(new Command_cage());
+ plugin.getCommand("cake").setExecutor(new Command_cake());
+ plugin.getCommand("cartsit").setExecutor(new Command_cartsit());
+ plugin.getCommand("cbtool").setExecutor(new Command_cbtool());
+ plugin.getCommand("cmdlist").setExecutor(new Command_cmdlist());
+ plugin.getCommand("cmdspy").setExecutor(new Command_cmdspy());
+ plugin.getCommand("colorme").setExecutor(new Command_colorme());
+ plugin.getCommand("creative").setExecutor(new Command_creative());
+ plugin.getCommand("csay").setExecutor(new Command_csay());
+ plugin.getCommand("deafen").setExecutor(new Command_deafen());
+ plugin.getCommand("debug").setExecutor(new Command_debug());
+ plugin.getCommand("denick").setExecutor(new Command_denick());
+ plugin.getCommand("deop").setExecutor(new Command_deop());
+ plugin.getCommand("deopall").setExecutor(new Command_deopall());
+ plugin.getCommand("dispfill").setExecutor(new Command_dispfill());
+ plugin.getCommand("doom").setExecutor(new Command_doom());
+ plugin.getCommand("enchant").setExecutor(new Command_enchant());
+ plugin.getCommand("ender").setExecutor(new Command_ender());
+ plugin.getCommand("expel").setExecutor(new Command_expel());
+ plugin.getCommand("findip").setExecutor(new Command_findip());
+ plugin.getCommand("flatlands").setExecutor(new Command_flatlands());
+ plugin.getCommand("fr").setExecutor(new Command_fr());
+ plugin.getCommand("fuckoff").setExecutor(new Command_fuckoff());
+ plugin.getCommand("gadmin").setExecutor(new Command_gadmin());
+ plugin.getCommand("gcmd").setExecutor(new Command_gcmd());
+ plugin.getCommand("glist").setExecutor(new Command_glist());
+ plugin.getCommand("gtfo").setExecutor(new Command_gtfo());
+ plugin.getCommand("halt").setExecutor(new Command_halt());
+ plugin.getCommand("health").setExecutor(new Command_health());
+ plugin.getCommand("invis").setExecutor(new Command_invis());
+ plugin.getCommand("jumppads").setExecutor(new Command_jumppads());
+ plugin.getCommand("kicknoob").setExecutor(new Command_kicknoob());
+ plugin.getCommand("landmine").setExecutor(new Command_landmine());
+ plugin.getCommand("lastcmd").setExecutor(new Command_lastcmd());
+ plugin.getCommand("list").setExecutor(new Command_list());
+ plugin.getCommand("localspawn").setExecutor(new Command_localspawn());
+ plugin.getCommand("lockup").setExecutor(new Command_lockup());
+ plugin.getCommand("logs").setExecutor(new Command_logs());
+ plugin.getCommand("moblimiter").setExecutor(new Command_moblimiter());
+ plugin.getCommand("mp").setExecutor(new Command_mp());
+ plugin.getCommand("mp44").setExecutor(new Command_mp44());
+ plugin.getCommand("myadmin").setExecutor(new Command_myadmin());
+ plugin.getCommand("nether").setExecutor(new Command_nether());
+ plugin.getCommand("nf").setExecutor(new Command_nf());
+ plugin.getCommand("nickclean").setExecutor(new Command_nickclean());
+ plugin.getCommand("nicknyan").setExecutor(new Command_nicknyan());
+ plugin.getCommand("o").setExecutor(new Command_o());
+ plugin.getCommand("onlinemode").setExecutor(new Command_onlinemode());
+ plugin.getCommand("op").setExecutor(new Command_op());
+ plugin.getCommand("opall").setExecutor(new Command_opall());
+ plugin.getCommand("opme").setExecutor(new Command_opme());
+ plugin.getCommand("ops").setExecutor(new Command_ops());
+ plugin.getCommand("orbit").setExecutor(new Command_orbit());
+ plugin.getCommand("overlord").setExecutor(new Command_overlord());
+ plugin.getCommand("permban").setExecutor(new Command_permban());
+ plugin.getCommand("plugincontrol").setExecutor(new Command_plugincontrol());
+ plugin.getCommand("potion").setExecutor(new Command_potion());
+ plugin.getCommand("premium").setExecutor(new Command_premium());
+ plugin.getCommand("protectarea").setExecutor(new Command_protectarea());
+ plugin.getCommand("purgeall").setExecutor(new Command_purgeall());
+ plugin.getCommand("qdeop").setExecutor(new Command_qdeop());
+ plugin.getCommand("qop").setExecutor(new Command_qop());
+ plugin.getCommand("radar").setExecutor(new Command_radar());
+ plugin.getCommand("rank").setExecutor(new Command_rank());
+ plugin.getCommand("rawsay").setExecutor(new Command_rawsay());
+ plugin.getCommand("rd").setExecutor(new Command_rd());
+ plugin.getCommand("report").setExecutor(new Command_report());
+ plugin.getCommand("ro").setExecutor(new Command_ro());
+ plugin.getCommand("rollback").setExecutor(new Command_rollback());
+ plugin.getCommand("saconfig").setExecutor(new Command_saconfig());
+ plugin.getCommand("say").setExecutor(new Command_say());
+ plugin.getCommand("setl").setExecutor(new Command_setl());
+ plugin.getCommand("setlevel").setExecutor(new Command_setlevel());
+ plugin.getCommand("setlever").setExecutor(new Command_setlever());
+ plugin.getCommand("setspawnworld").setExecutor(new Command_setspawnworld());
+ plugin.getCommand("smite").setExecutor(new Command_smite());
+ plugin.getCommand("spectator").setExecutor(new Command_spectator());
+ plugin.getCommand("status").setExecutor(new Command_status());
+ plugin.getCommand("stfu").setExecutor(new Command_stfu());
+ plugin.getCommand("stop").setExecutor(new Command_stop());
+ plugin.getCommand("survival").setExecutor(new Command_survival());
+ plugin.getCommand("tag").setExecutor(new Command_tag());
+ plugin.getCommand("tagnyan").setExecutor(new Command_tagnyan());
+ plugin.getCommand("tban").setExecutor(new Command_tban());
+ plugin.getCommand("tempban").setExecutor(new Command_tempban());
+ plugin.getCommand("tfbanlist").setExecutor(new Command_tfbanlist());
+ plugin.getCommand("tfipbanlist").setExecutor(new Command_tfipbanlist());
+ plugin.getCommand("tfm").setExecutor(new Command_tfm());
+ plugin.getCommand("toggle").setExecutor(new Command_toggle());
+ plugin.getCommand("tossmob").setExecutor(new Command_tossmob());
+ plugin.getCommand("trail").setExecutor(new Command_trail());
+ plugin.getCommand("updatetfm").setExecutor(new Command_updatetfm());
+ plugin.getCommand("uuid").setExecutor(new Command_uuid());
+ plugin.getCommand("warn").setExecutor(new Command_warn());
+ plugin.getCommand("whitelist").setExecutor(new Command_whitelist());
+ plugin.getCommand("whohas").setExecutor(new Command_whohas());
+ plugin.getCommand("wildcard").setExecutor(new Command_wildcard());
+ plugin.getCommand("wipeflatlands").setExecutor(new Command_wipeflatlands());
+ plugin.getCommand("wipeuserdata").setExecutor(new Command_wipeuserdata());
+ plugin.getCommand("whoami").setExecutor(new Command_whoami());
+ plugin.getCommand("resetplayer").setExecutor(new Command_resetplayer());
+ plugin.getCommand("vanish").setExecutor(new Command_vanish());
+ }
}
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/discord/bridge/DiscordBridge.java b/src/main/java/me/StevenLawson/TotalFreedomMod/discord/bridge/DiscordBridge.java
index 8d2640b..9ec3e4d 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/discord/bridge/DiscordBridge.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/discord/bridge/DiscordBridge.java
@@ -1,11 +1,15 @@
package me.StevenLawson.TotalFreedomMod.discord.bridge;
+import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Pattern;
import me.StevenLawson.TotalFreedomMod.Log;
import me.StevenLawson.TotalFreedomMod.admin.AdminList;
import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
import me.StevenLawson.TotalFreedomMod.config.MainConfig;
import me.StevenLawson.TotalFreedomMod.discord.command.DiscordCommandManager;
-import me.StevenLawson.TotalFreedomMod.player.PlayerRank;
+import me.StevenLawson.TotalFreedomMod.util.Utilities;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
@@ -21,222 +25,234 @@ import org.javacord.api.entity.message.MessageAuthor;
import org.javacord.api.entity.server.Server;
import org.javacord.api.entity.user.User;
import org.javacord.api.event.message.MessageCreateEvent;
-import org.javacord.api.event.message.MessageEvent;
-
-import java.util.Optional;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.regex.Pattern;
public class DiscordBridge {
- private static DiscordApi DISCORD_API;
- private static TextChannel CHANNEL;
- private static TextChannel ADMIN_CHANNEL;
- public static DiscordCommandManager COMMAND_MANAGER;
- private static void onMessageCreateEvent(MessageCreateEvent message) {
- boolean isAdmin = false;
+ private static DiscordApi DISCORD_API;
+ private static TextChannel CHANNEL;
+ private static TextChannel ADMIN_CHANNEL;
+ public static DiscordCommandManager COMMAND_MANAGER;
+
+ private static void onMessageCreateEvent(MessageCreateEvent message) {
+ boolean isAdmin = false;
+
+ try {
+ isAdmin = message.getChannel().getIdAsString()
+ .equalsIgnoreCase(ADMIN_CHANNEL.getIdAsString());
+ } catch (Exception ignored) {
+ }
+
+ String content = message.getMessage().getReadableContent();
+ String prefix = MainConfig.getString(ConfigurationEntry.DISCORD_PREFIX);
+ MessageAuthor author = message.getMessage().getAuthor();
+
+ if (author.isBotUser() || !message.isServerMessage()) {
+ return;
+ }
+ Optional server = message.getServer();
+ Optional user = author.asUser();
+
+ if (prefix == null) {
+ Log.severe("Bot prefix does not exist. Stopping bot...");
+ stop();
+ return;
+ }
+
+ if (!server.isPresent()) {
+ Log.warning(
+ "Discord server wasn't present in message, this may be a sign you've not properly configured the intents for your bot.");
+ return;
+ }
+
+ if (!user.isPresent()) {
+ Log.warning(
+ "Unable to get user of message author. This may be a sign you've not properly configured the intents for your bot.");
+ return;
+ }
+
+ if (content.toLowerCase().startsWith(prefix)) {
+ COMMAND_MANAGER.parse(content, user.get(), server.get(), message.getChannel(), prefix);
+ } else {
+ Optional referenced = message.getMessage().getReferencedMessage();
+
+ String reply = "";
+ if (referenced.isPresent()) {
+ Message replyingTo = referenced.get();
+ reply = String.format(
+ ChatColor.GRAY + "┌ " + ChatColor.YELLOW + "%s" + ChatColor.GRAY + " %s\n"
+ + ChatColor.WHITE, replyingTo.getAuthor().getDiscriminatedName(),
+ replyingTo.getReadableContent());
+ }
+
+ String format = MainConfig.getString(
+ (isAdmin) ? ConfigurationEntry.DISCORD_ADMIN_FORMAT : ConfigurationEntry.DISCORD_FORMAT);
+ format = format.replace("{TAG}", author.getDiscriminatedName());
+ format = format.replace("{USERNAME}", author.getName());
+ BaseComponent[] components = TextComponent.fromLegacyText(
+ ChatColor.translateAlternateColorCodes('&', String.format(format, content)));
+ TextComponent component = new TextComponent(reply);
+
+ component.addExtra(Utilities.fromBaseComponents(components));
+
+ if (message.getMessageAttachments().size() > 0) {
+ int i = 0;
+ for (MessageAttachment messageAttachment : message.getMessageAttachments()) {
+ String url = messageAttachment.getProxyUrl().toString();
+ ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
+ TextComponent warningComponent = new TextComponent(
+ "WARNING: By clicking on this text, your client will open:\n\n");
+ warningComponent.setColor(net.md_5.bungee.api.ChatColor.RED);
+ warningComponent.setBold(true);
+ TextComponent urlComponent = new TextComponent(url);
+ urlComponent.setColor(net.md_5.bungee.api.ChatColor.DARK_AQUA);
+ urlComponent.setUnderlined(true);
+ urlComponent.setBold(false);
+ warningComponent.addExtra(urlComponent);
+ HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT,
+ new BaseComponent[]{warningComponent});
+ TextComponent mediaComponent = new TextComponent(
+ (i == 0 && content.isEmpty()) ? "[Media]" : " [Media]");
+ mediaComponent.setColor(net.md_5.bungee.api.ChatColor.YELLOW);
+ mediaComponent.setClickEvent(clickEvent);
+ mediaComponent.setHoverEvent(hoverEvent);
+ component.addExtra(mediaComponent);
+ i++;
+ }
+ }
+
+ if (isAdmin) {
+ for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
+ if (AdminList.isSuperAdmin(player)) {
+ player.spigot().sendMessage(component);
+ }
+ }
+ } else {
+ Bukkit.spigot().broadcast(component);
+ }
+ Log.info(component.toPlainText());
+ }
+ }
+
+ public static void load() {
+
+ if (Boolean.FALSE.equals(MainConfig.getBoolean(ConfigurationEntry.DISCORD_IS_ENABLED))) {
+ return;
+ }
+
+ try {
+ DISCORD_API = new DiscordApiBuilder()
+ .setToken(MainConfig.getString(ConfigurationEntry.DISCORD_TOKEN))
+ .login()
+ .join();
+
+ Optional channelFuture = DISCORD_API.getTextChannelById(
+ MainConfig.getString(ConfigurationEntry.DISCORD_CHANNEL));
+ Optional adminChannelFuture = DISCORD_API.getTextChannelById(
+ MainConfig.getString(ConfigurationEntry.DISCORD_ADMIN_CHANNEL));
+
+ if (!channelFuture.isPresent()) {
+ Log.warning("TFM 4.3 Reloaded could not find your channel, stopping!");
+
+ return;
+ }
+
+ CHANNEL = channelFuture.get();
+ adminChannelFuture.ifPresent(textChannel -> ADMIN_CHANNEL = textChannel);
+ COMMAND_MANAGER = new DiscordCommandManager();
+ COMMAND_MANAGER.init();
+
+ CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent);
+ if (adminChannelFuture.isPresent()) {
+ ADMIN_CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent);
+ }
+ } catch (Exception e) {
+ Log.warning(
+ "Uh oh! It looks like TFM 4.3 Reloaded Discord couldn't start! Please check you have defined the bot's token & channel and also given it the correct permissions! (Read Messages and Send Messages)");
+ Log.warning("If you've already set that up however, you may to read the exception below.");
+ Log.warning(
+ "If this is a bug with TFM 4.3 Reloaded, please report it at https://github.com/TheDeus-Group/TFM-4.3-Reloaded/issues or https://code.cat.casa/TheDeus-Group/TFM-4.3-Reloaded/issues");
+ e.printStackTrace();
+ return;
+ }
+
+ Log.info("TFM 4.3 Reloaded Discord started.");
+
+ transmitMessage("**Server has started**");
+ }
+
+ public static String sanitizeMessage(String message) {
+ Pattern colors = Pattern.compile("§.", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
+ Pattern pings = Pattern.compile("@", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
+
+ if (message.length() > 2000) {
+ message = message.substring(0, 2000);
+ }
+
+ return message.replaceAll(colors.pattern(), "").replaceAll(pings.pattern(), "@\u200B");
+ }
+
+ public static void transmitMessage(String message) {
+ transmitMessage(message, false);
+ }
+
+ public static void transmitMessage(String message, boolean disconnectAfterwards) {
+ if (CHANNEL == null) {
+ return;
+ }
+ if (!disconnectAfterwards) {
+ CHANNEL.sendMessage(sanitizeMessage(message));
+ } else {
+ try {
+ CHANNEL.sendMessage(sanitizeMessage(message)).get();
+ } catch (Exception ignored) {
+ }
+ CountDownLatch shutdownWaiter = new CountDownLatch(1);
+
+ Thread t = new Thread(() -> {
+ DISCORD_API.addLostConnectionListener(lostConnectionEvent -> shutdownWaiter.countDown());
+ DISCORD_API.disconnect();
try {
- isAdmin = message.getChannel().getIdAsString().equalsIgnoreCase(ADMIN_CHANNEL.getIdAsString());
- } catch (Exception ignored) {}
-
- String content = message.getMessage().getReadableContent();
- String prefix = MainConfig.getString(ConfigurationEntry.DISCORD_PREFIX);
- MessageAuthor author = message.getMessage().getAuthor();
-
- if (author.isBotUser() || !message.isServerMessage()) return;
- Optional server = message.getServer();
- Optional user = author.asUser();
-
- if(prefix == null) {
- Log.severe("Bot prefix does not exist. Stopping bot...");
- stop();
- return;
+ shutdownWaiter.await(30, TimeUnit.SECONDS);
+ } catch (InterruptedException ignored) {
}
+ });
+ t.start();
+ }
+ }
- if(!server.isPresent()) {
- Log.warning("Discord server wasn't present in message, this may be a sign you've not properly configured the intents for your bot.");
- return;
- }
+ public static void transmitAdminMessage(String message) {
+ transmitAdminMessage(message, false);
+ }
- if(!user.isPresent()) {
- Log.warning("Unable to get user of message author. This may be a sign you've not properly configured the intents for your bot.");
- return;
- }
+ public static void transmitAdminMessage(String message, boolean disconnectAfterwards) {
+ if (ADMIN_CHANNEL == null) {
+ return;
+ }
+ if (!disconnectAfterwards) {
+ ADMIN_CHANNEL.sendMessage(sanitizeMessage(message));
+ } else {
+ try {
+ ADMIN_CHANNEL.sendMessage(sanitizeMessage(message)).get();
+ } catch (Exception ignored) {
+ }
+ DISCORD_API.disconnect();
+ }
+ }
- if (content.toLowerCase().startsWith(prefix)) {
- COMMAND_MANAGER.parse(content, user.get(), server.get(), message.getChannel(), prefix);
- } else {
- Optional referenced = message.getMessage().getReferencedMessage();
+ public static void stop() {
- String reply = "";
- if(referenced.isPresent()) {
- Message replyingTo = referenced.get();
- reply = String.format(ChatColor.GRAY + "┌ " + ChatColor.YELLOW + "%s" + ChatColor.GRAY + " %s\n" + ChatColor.WHITE, replyingTo.getAuthor().getDiscriminatedName(), replyingTo.getReadableContent());
- }
-
- String format = MainConfig.getString((isAdmin) ? ConfigurationEntry.DISCORD_ADMIN_FORMAT : ConfigurationEntry.DISCORD_FORMAT);
- format = format.replace("{TAG}", author.getDiscriminatedName());
- format = format.replace("{USERNAME}", author.getName());
- BaseComponent[] components = TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', String.format(format, content)));
- TextComponent component = new TextComponent(reply);
-
- for (BaseComponent baseComponent : components) {
- component.addExtra(baseComponent);
- }
-
- if(message.getMessageAttachments().size() > 0) {
- int i = 0;
- for (MessageAttachment messageAttachment : message.getMessageAttachments()) {
- String url = messageAttachment.getProxyUrl().toString();
- ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
- TextComponent warningComponent = new TextComponent("WARNING: By clicking on this text, your client will open:\n\n");
- warningComponent.setColor(net.md_5.bungee.api.ChatColor.RED);
- warningComponent.setBold(true);
- TextComponent urlComponent = new TextComponent(url);
- urlComponent.setColor(net.md_5.bungee.api.ChatColor.DARK_AQUA);
- urlComponent.setUnderlined(true);
- urlComponent.setBold(false);
- warningComponent.addExtra(urlComponent);
- HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{warningComponent});
- TextComponent mediaComponent = new TextComponent((i == 0 && content.isEmpty()) ? "[Media]" : " [Media]");
- mediaComponent.setColor(net.md_5.bungee.api.ChatColor.YELLOW);
- mediaComponent.setClickEvent(clickEvent);
- mediaComponent.setHoverEvent(hoverEvent);
- component.addExtra(mediaComponent);
- i++;
- }
- }
-
- if(isAdmin) {
- for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
- {
- if (AdminList.isSuperAdmin(player))
- {
- player.spigot().sendMessage(component);
- }
- }
- } else {
- Bukkit.spigot().broadcast(component);
- }
- Log.info(component.toPlainText());
- }
+ if (Boolean.FALSE.equals(MainConfig.getBoolean(ConfigurationEntry.DISCORD_IS_ENABLED))) {
+ return;
}
- public static void load() {
+ transmitMessage("**Server has stopped**", true);
- if (Boolean.FALSE.equals(MainConfig.getBoolean(ConfigurationEntry.DISCORD_IS_ENABLED))) {
- return;
- }
+ Log.info("TFM 4.3 Reloaded Discord stopped.");
+ }
- try {
- DISCORD_API = new DiscordApiBuilder()
- .setToken(MainConfig.getString(ConfigurationEntry.DISCORD_TOKEN))
- .login()
- .join();
-
- Optional channelFuture = DISCORD_API.getTextChannelById(MainConfig.getString(ConfigurationEntry.DISCORD_CHANNEL));
- Optional adminChannelFuture = DISCORD_API.getTextChannelById(MainConfig.getString(ConfigurationEntry.DISCORD_ADMIN_CHANNEL));
-
- if (!channelFuture.isPresent()) {
- Log.warning("TFM 4.3 Reloaded could not find your channel, stopping!");
-
- return;
- }
-
- CHANNEL = channelFuture.get();
- adminChannelFuture.ifPresent(textChannel -> ADMIN_CHANNEL = textChannel);
- COMMAND_MANAGER = new DiscordCommandManager();
- COMMAND_MANAGER.init();
-
- CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent);
- if (adminChannelFuture.isPresent()) {
- ADMIN_CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent);
- }
- } catch (Exception e) {
- Log.warning("Uh oh! It looks like TFM 4.3 Reloaded Discord couldn't start! Please check you have defined the bot's token & channel and also given it the correct permissions! (Read Messages and Send Messages)");
- Log.warning("If you've already set that up however, you may to read the exception below.");
- Log.warning("If this is a bug with TFM 4.3 Reloaded, please report it at https://github.com/TheDeus-Group/TFM-4.3-Reloaded/issues or https://code.cat.casa/TheDeus-Group/TFM-4.3-Reloaded/issues");
- e.printStackTrace();
- return;
- }
-
- Log.info("TFM 4.3 Reloaded Discord started.");
-
- transmitMessage("**Server has started**");
- }
-
- public static String sanitizeMessage(String message) {
- Pattern colors = Pattern.compile("§.", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
- Pattern pings = Pattern.compile("@", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
-
- if (message.length() > 2000) {
- message = message.substring(0, 2000);
- }
-
- return message.replaceAll(colors.pattern(), "").replaceAll(pings.pattern(), "@\u200B");
- }
-
- public static void transmitMessage(String message) {
- transmitMessage(message, false);
- }
-
- public static void transmitMessage(String message, boolean disconnectAfterwards) {
- if (CHANNEL == null) return;
- if (!disconnectAfterwards) {
- CHANNEL.sendMessage(sanitizeMessage(message));
- } else {
- try {
- CHANNEL.sendMessage(sanitizeMessage(message)).get();
- } catch (Exception ignored) {
- }
- CountDownLatch shutdownWaiter = new CountDownLatch(1);
-
- Thread t = new Thread(() -> {
- DISCORD_API.addLostConnectionListener(lostConnectionEvent -> shutdownWaiter.countDown());
- DISCORD_API.disconnect();
-
- try {
- shutdownWaiter.await(30, TimeUnit.SECONDS);
- } catch (InterruptedException ignored) {
- }
- });
- t.start();
- }
- }
-
- public static void transmitAdminMessage(String message) {
- transmitAdminMessage(message, false);
- }
-
- public static void transmitAdminMessage(String message, boolean disconnectAfterwards) {
- if (ADMIN_CHANNEL == null) return;
- if (!disconnectAfterwards) {
- ADMIN_CHANNEL.sendMessage(sanitizeMessage(message));
- } else {
- try {
- ADMIN_CHANNEL.sendMessage(sanitizeMessage(message)).get();
- } catch (Exception ignored) {
- }
- DISCORD_API.disconnect();
- }
- }
-
- public static void stop() {
-
- if (Boolean.FALSE.equals(MainConfig.getBoolean(ConfigurationEntry.DISCORD_IS_ENABLED))) {
- return;
- }
-
- transmitMessage("**Server has stopped**", true);
-
- Log.info("TFM 4.3 Reloaded Discord stopped.");
- }
-
- public static String fullySanitizeDiscordMessage(String message)
- {
- String partiallySanitized = sanitizeMessage(message);
- return partiallySanitized.replaceAll("([`_~*|\\\\])", "\\\\$1");
- }
+ public static String fullySanitizeDiscordMessage(String message) {
+ String partiallySanitized = sanitizeMessage(message);
+ return partiallySanitized.replaceAll("([`_~*|\\\\])", "\\\\$1");
+ }
}
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/listener/PlayerListener.java b/src/main/java/me/StevenLawson/TotalFreedomMod/listener/PlayerListener.java
index 67fba09..45958c8 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/listener/PlayerListener.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/listener/PlayerListener.java
@@ -80,7 +80,9 @@ public class PlayerListener implements Listener {
"I love FreedomForever!", "I'm here to collect my cupcake.", "Do you have any cupcakes?",
"I like pineapple pizza.", "Do you have any pineapple pizza?",
"I dislike Cherry Pepsi Max.",
- "Guys, did you know my father is getting milk? He hasn't been back for hours, I'm worried...");
+ "Guys, did you know my father is getting milk? He hasn't been back for hours, I'm worried...",
+ "My wife's boyfriend is a nice guy.", "My wife's boyfriend got me a new Switch!",
+ "My wife's boyfriend got me a new PS5!");
public static final int MSG_PER_HEARTBEAT = 10;
public static final int DEFAULT_PORT = 25565;
public static final int MAX_XY_COORD = 30000000;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerData.java b/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerData.java
index 6bfb20d..d9130d9 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerData.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerData.java
@@ -1,10 +1,9 @@
package me.StevenLawson.TotalFreedomMod.player;
import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
-import me.StevenLawson.TotalFreedomMod.admin.AdminList;
import me.StevenLawson.TotalFreedomMod.bridge.EssentialsBridge;
-import me.StevenLawson.TotalFreedomMod.commands.AdminLevel;
import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.*;
import org.bukkit.entity.Arrow;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerList.java b/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerList.java
index bfef0fe..06a64fe 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerList.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/player/PlayerList.java
@@ -4,6 +4,7 @@ import com.google.common.collect.Sets;
import me.StevenLawson.TotalFreedomMod.Log;
import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
import me.StevenLawson.TotalFreedomMod.config.Configuration;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.Bukkit;
diff --git a/src/main/java/me/StevenLawson/TotalFreedomMod/util/Utilities.java b/src/main/java/me/StevenLawson/TotalFreedomMod/util/Utilities.java
index 0add9c8..9f57b6e 100644
--- a/src/main/java/me/StevenLawson/TotalFreedomMod/util/Utilities.java
+++ b/src/main/java/me/StevenLawson/TotalFreedomMod/util/Utilities.java
@@ -1,1100 +1,994 @@
package me.StevenLawson.TotalFreedomMod.util;
-import me.StevenLawson.TotalFreedomMod.Log;
-import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
-import me.StevenLawson.TotalFreedomMod.admin.AdminList;
-import me.StevenLawson.TotalFreedomMod.ban.Ban;
-import me.StevenLawson.TotalFreedomMod.ban.BanManager;
-import me.StevenLawson.TotalFreedomMod.discord.bridge.DiscordBridge;
-import me.StevenLawson.TotalFreedomMod.config.Configuration;
-import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
-import me.StevenLawson.TotalFreedomMod.player.Player;
-import me.StevenLawson.TotalFreedomMod.player.*;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.bukkit.*;
-import org.bukkit.block.Block;
-import org.bukkit.block.Skull;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.*;
-import org.bukkit.plugin.Plugin;
-import org.bukkit.util.FileUtil;
-
-import java.io.*;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
-public class Utilities
-{
- private static final Map ejectTracker = new HashMap();
- public static final Map mobtypes = new HashMap();
- // See https://github.com/TotalFreedom/License - None of the listed names may be removed.
- public static final List DEVELOPERS = Arrays.asList("Madgeek1450", "Prozza", "DarthSalmon", "AcidicCyanide", "Wild1145", "WickedGamingUK", "G6_", "videogamesm12", "maniaplay", "evanbt");
- private static final Random RANDOM = new Random();
- public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
- public static final Map CHAT_COLOR_NAMES = new HashMap();
- public static final List CHAT_COLOR_POOL = Arrays.asList(
- ChatColor.DARK_BLUE,
- ChatColor.DARK_GREEN,
- ChatColor.DARK_AQUA,
- ChatColor.DARK_RED,
- ChatColor.DARK_PURPLE,
- ChatColor.GOLD,
- ChatColor.BLUE,
- ChatColor.GREEN,
- ChatColor.AQUA,
- ChatColor.RED,
- ChatColor.LIGHT_PURPLE,
- ChatColor.YELLOW);
-
- static
- {
- for (EntityType type : EntityType.values())
- {
- try
- {
- if (DeprecationUtil.getName_EntityType(type) != null)
- {
- if (Creature.class.isAssignableFrom(type.getEntityClass()))
- {
- mobtypes.put(DeprecationUtil.getName_EntityType(type).toLowerCase(), type);
- }
- }
- }
- catch (Exception ex)
- {
- }
- }
-
- for (ChatColor chatColor : CHAT_COLOR_POOL)
- {
- CHAT_COLOR_NAMES.put(chatColor.name().toLowerCase().replace("_", ""), chatColor);
- }
- }
-
- private Utilities()
- {
- throw new AssertionError();
- }
-
- public static void bcastMsg(String message, ChatColor color, boolean transmitToDiscord) {
- Log.info(message, true);
-
- for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
- player.sendMessage((color == null ? "" : color) + message);
- }
-
- if(transmitToDiscord) {
- DiscordBridge.transmitMessage(message.replaceAll("([`_~*])", "\\\\$1"));
- }
- }
-
- public static void bcastMsg(String message, ChatColor color) {
- bcastMsg(message, color, true);
- }
-
- public static void bcastMsg(String message, boolean transmitToDiscord) {
- bcastMsg(message, null, transmitToDiscord);
- }
-
- public static void bcastMsg(String message)
- {
- Utilities.bcastMsg(message, null);
- }
-
- // Still in use by listeners
- public static void playerMsg(CommandSender sender, String message, ChatColor color)
- {
- sender.sendMessage(color + message);
- }
-
- // Still in use by listeners
- public static void playerMsg(CommandSender sender, String message)
- {
- Utilities.playerMsg(sender, message, ChatColor.GRAY);
- }
-
- public static void setFlying(org.bukkit.entity.Player player, boolean flying)
- {
- player.setAllowFlight(true);
- player.setFlying(flying);
- }
-
- public static void adminAction(String adminName, String action, boolean isRed)
- {
- Utilities.bcastMsg(adminName + " - " + action, (isRed ? ChatColor.RED : ChatColor.AQUA));
- }
-
- public static String getIp(OfflinePlayer player)
- {
- if (player.isOnline())
- {
- return player.getPlayer().getAddress().getAddress().getHostAddress().trim();
- }
-
- final Player entry = PlayerList.getEntry(UUIDManager.getUniqueId(player));
-
- return (entry == null ? null : entry.getIps().get(0));
- }
-
- public static boolean isUniqueId(String uuid)
- {
- try
- {
- UUID.fromString(uuid);
- return true;
- }
- catch (IllegalArgumentException ex)
- {
- return false;
- }
- }
-
- public static String formatLocation(Location location)
- {
- return String.format("%s: (%d, %d, %d)",
- location.getWorld().getName(),
- Math.round(location.getX()),
- Math.round(location.getY()),
- Math.round(location.getZ()));
- }
-
- public static String formatPlayer(OfflinePlayer player)
- {
- return player.getName() + " (" + UUIDManager.getUniqueId(player) + ")";
- }
-
- /**
- * Escapes an IP-address to a config-friendly version.
- *
- * Example:
- *
- * IpUtils.toEscapedString("192.168.1.192"); // 192_168_1_192
- *
- *
- * @param ip The IP-address to escape.
- * @return The config-friendly IP address.
- * @see #fromEscapedString(String)
- */
- public static String toEscapedString(String ip) // BukkitLib @ https://github.com/Pravian/BukkitLib
- {
- return ip.trim().replaceAll("\\.", "_");
- }
-
- /**
- * Un-escapes a config-friendly Ipv4-address.
- *
- * Example:
- *
- * IpUtils.fromEscapedString("192_168_1_192"); // 192.168.1.192
- *
- *
- * @param escapedIp The IP-address to un-escape.
- * @return The config-friendly IP address.
- * @see #toEscapedString(String)
- */
- public static String fromEscapedString(String escapedIp) // BukkitLib @ https://github.com/Pravian/BukkitLib
- {
- return escapedIp.trim().replaceAll("_", "\\.");
- }
-
- public static void gotoWorld(org.bukkit.entity.Player player, String targetWorld)
- {
- if (player == null)
- {
- return;
- }
-
- if (player.getWorld().getName().equalsIgnoreCase(targetWorld))
- {
- playerMsg(player, "Going to main world.", ChatColor.GRAY);
- player.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
- return;
- }
-
- for (World world : Bukkit.getWorlds())
- {
- if (world.getName().equalsIgnoreCase(targetWorld))
- {
- playerMsg(player, "Going to world: " + targetWorld, ChatColor.GRAY);
- player.teleport(world.getSpawnLocation());
- return;
- }
- }
-
- playerMsg(player, "World " + targetWorld + " not found.", ChatColor.GRAY);
- }
-
- public static String decolorize(String string)
- {
- return string.replaceAll("\\u00A7(?=[0-9a-fk-or])", "&");
- }
-
- public static void buildHistory(Location location, int length, PlayerData playerdata)
- {
- final Block center = location.getBlock();
- for (int xOffset = -length; xOffset <= length; xOffset++)
- {
- for (int yOffset = -length; yOffset <= length; yOffset++)
- {
- for (int zOffset = -length; zOffset <= length; zOffset++)
- {
- final Block block = center.getRelative(xOffset, yOffset, zOffset);
- playerdata.insertHistoryBlock(block.getLocation(), block.getType());
- }
- }
- }
- }
-
- public static void generateCube(Location location, int length, Material material)
- {
- final Block center = location.getBlock();
- for (int xOffset = -length; xOffset <= length; xOffset++)
- {
- for (int yOffset = -length; yOffset <= length; yOffset++)
- {
- for (int zOffset = -length; zOffset <= length; zOffset++)
- {
- final Block block = center.getRelative(xOffset, yOffset, zOffset);
- if (block.getType() != material)
- {
- block.setType(material);
- }
- }
- }
- }
- }
-
- public static void generateHollowCube(Location location, int length, Material material)
- {
- final Block center = location.getBlock();
- for (int xOffset = -length; xOffset <= length; xOffset++)
- {
- for (int yOffset = -length; yOffset <= length; yOffset++)
- {
- for (int zOffset = -length; zOffset <= length; zOffset++)
- {
- // Hollow
- if (Math.abs(xOffset) != length && Math.abs(yOffset) != length && Math.abs(zOffset) != length)
- {
- continue;
- }
-
- final Block block = center.getRelative(xOffset, yOffset, zOffset);
-
- if (material != Material.SKULL)
- {
- // Glowstone light
- if (material != Material.GLASS && xOffset == 0 && yOffset == 2 && zOffset == 0)
- {
- block.setType(Material.GLOWSTONE);
- continue;
- }
-
- block.setType(material);
- }
- else // Darth mode
- {
- if (Math.abs(xOffset) == length && Math.abs(yOffset) == length && Math.abs(zOffset) == length)
- {
- block.setType(Material.GLOWSTONE);
- continue;
- }
-
- block.setType(Material.SKULL);
- final Skull skull = (Skull) block.getState();
- skull.setSkullType(SkullType.PLAYER);
- skull.setOwner("Prozza");
- skull.update();
- }
- }
- }
- }
- }
-
- public static void setWorldTime(World world, long ticks)
- {
- long time = world.getTime();
- time -= time % 24000;
- world.setTime(time + 24000 + ticks);
- }
-
- public static void createDefaultConfiguration(final String configFileName)
- {
- final File targetFile = new File(TotalFreedomMod.plugin.getDataFolder(), configFileName);
-
- if (targetFile.exists())
- {
- return;
- }
-
- Log.info("Installing default configuration file template: " + targetFile.getPath());
-
- try
- {
- final InputStream configFileStream = TotalFreedomMod.plugin.getResource(configFileName);
- FileUtils.copyInputStreamToFile(configFileStream, targetFile);
- configFileStream.close();
- }
- catch (IOException ex)
- {
- Log.severe(ex);
- }
- }
-
- public static boolean deleteFolder(final File file)
- {
- if (file.exists() && file.isDirectory())
- {
- return FileUtils.deleteQuietly(file);
- }
- return false;
- }
-
- public static void deleteCoreDumps()
- {
- final File[] coreDumps = new File(".").listFiles(new FileFilter()
- {
- @Override
- public boolean accept(File file)
- {
- return file.getName().startsWith("java.core");
- }
- });
-
- for (File dump : coreDumps)
- {
- Log.info("Removing core dump file: " + dump.getName());
- dump.delete();
- }
- }
-
- public static EntityType getEntityType(String mobname) throws Exception
- {
- mobname = mobname.toLowerCase().trim();
-
- if (!Utilities.mobtypes.containsKey(mobname))
- {
- throw new Exception();
- }
-
- return Utilities.mobtypes.get(mobname);
- }
-
- /**
- * Write the specified InputStream to a file.
- *
- * @param in The InputStream from which to read.
- * @param file The File to write to.
- * @throws IOException
- */
- public static void copy(InputStream in, File file) throws IOException // BukkitLib @ https://github.com/Pravian/BukkitLib
- {
- if (!file.exists())
- {
- file.getParentFile().mkdirs();
- }
-
- final OutputStream out = new FileOutputStream(file);
- byte[] buf = new byte[1024];
- int len;
- while ((len = in.read(buf)) > 0)
- {
- out.write(buf, 0, len);
- }
- out.close();
- in.close();
- }
-
- /**
- * Returns a file at located at the Plugins Data folder.
- *
- * @param plugin The plugin to use
- * @param name The name of the file.
- * @return The requested file.
- */
- public static File getPluginFile(Plugin plugin, String name) // BukkitLib @ https://github.com/Pravian/BukkitLib
- {
- return new File(plugin.getDataFolder(), name);
- }
-
- public static void autoEject(org.bukkit.entity.Player player, String kickMessage)
- {
- EjectMethod method = EjectMethod.STRIKE_ONE;
- final String ip = Utilities.getIp(player);
-
- if (!Utilities.ejectTracker.containsKey(ip))
- {
- Utilities.ejectTracker.put(ip, 0);
- }
-
- int kicks = Utilities.ejectTracker.get(ip);
- kicks += 1;
-
- Utilities.ejectTracker.put(ip, kicks);
-
- if (kicks <= 1)
- {
- method = EjectMethod.STRIKE_ONE;
- }
- else if (kicks == 2)
- {
- method = EjectMethod.STRIKE_TWO;
- }
- else if (kicks >= 3)
- {
- method = EjectMethod.STRIKE_THREE;
- }
-
- Log.info("AutoEject -> name: " + player.getName() + " - player ip: " + ip + " - method: " + method);
-
- player.setOp(false);
- player.setGameMode(GameMode.SURVIVAL);
- player.getInventory().clear();
-
- switch (method)
- {
- case STRIKE_ONE:
- {
- final Calendar cal = new GregorianCalendar();
- cal.add(Calendar.MINUTE, 1);
- final Date expires = cal.getTime();
-
- Utilities.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 1 minute.");
-
- BanManager.addIpBan(new Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
- BanManager.addUuidBan(new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", expires, kickMessage));
- player.kickPlayer(kickMessage);
-
- break;
- }
- case STRIKE_TWO:
- {
- final Calendar c = new GregorianCalendar();
- c.add(Calendar.MINUTE, 3);
- final Date expires = c.getTime();
-
- Utilities.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 3 minutes.");
-
- BanManager.addIpBan(new Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
- BanManager.addUuidBan(new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", expires, kickMessage));
- player.kickPlayer(kickMessage);
- break;
- }
- case STRIKE_THREE:
- {
- String[] ipAddressParts = ip.split("\\.");
-
- BanManager.addIpBan(new Ban(ip, player.getName(), "AutoEject", null, kickMessage));
- BanManager.addIpBan(new Ban(ipAddressParts[0] + "." + ipAddressParts[1] + ".*.*", player.getName(), "AutoEject", null, kickMessage));
- BanManager.addUuidBan(new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", null, kickMessage));
-
- Utilities.bcastMsg(ChatColor.RED + player.getName() + " has been banned.");
-
- player.kickPlayer(kickMessage);
- break;
- }
- }
- }
-
- public static Date parseDateOffset(String time)
- {
- Pattern timePattern = Pattern.compile(
- "(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
- + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
- Matcher m = timePattern.matcher(time);
- int years = 0;
- int months = 0;
- int weeks = 0;
- int days = 0;
- int hours = 0;
- int minutes = 0;
- int seconds = 0;
- boolean found = false;
- while (m.find())
- {
- if (m.group() == null || m.group().isEmpty())
- {
- continue;
- }
- for (int i = 0; i < m.groupCount(); i++)
- {
- if (m.group(i) != null && !m.group(i).isEmpty())
- {
- found = true;
- break;
- }
- }
- if (found)
- {
- if (m.group(1) != null && !m.group(1).isEmpty())
- {
- years = Integer.parseInt(m.group(1));
- }
- if (m.group(2) != null && !m.group(2).isEmpty())
- {
- months = Integer.parseInt(m.group(2));
- }
- if (m.group(3) != null && !m.group(3).isEmpty())
- {
- weeks = Integer.parseInt(m.group(3));
- }
- if (m.group(4) != null && !m.group(4).isEmpty())
- {
- days = Integer.parseInt(m.group(4));
- }
- if (m.group(5) != null && !m.group(5).isEmpty())
- {
- hours = Integer.parseInt(m.group(5));
- }
- if (m.group(6) != null && !m.group(6).isEmpty())
- {
- minutes = Integer.parseInt(m.group(6));
- }
- if (m.group(7) != null && !m.group(7).isEmpty())
- {
- seconds = Integer.parseInt(m.group(7));
- }
- break;
- }
- }
- if (!found)
- {
- return null;
- }
-
- Calendar c = new GregorianCalendar();
-
- if (years > 0)
- {
- c.add(Calendar.YEAR, years);
- }
- if (months > 0)
- {
- c.add(Calendar.MONTH, months);
- }
- if (weeks > 0)
- {
- c.add(Calendar.WEEK_OF_YEAR, weeks);
- }
- if (days > 0)
- {
- c.add(Calendar.DAY_OF_MONTH, days);
- }
- if (hours > 0)
- {
- c.add(Calendar.HOUR_OF_DAY, hours);
- }
- if (minutes > 0)
- {
- c.add(Calendar.MINUTE, minutes);
- }
- if (seconds > 0)
- {
- c.add(Calendar.SECOND, seconds);
- }
-
- return c.getTime();
- }
-
- public static String playerListToNames(Set players)
- {
- List names = new ArrayList();
- for (OfflinePlayer player : players)
- {
- names.add(player.getName());
- }
- return StringUtils.join(names, ", ");
- }
-
- @SuppressWarnings("unchecked")
- public static Map getSavedFlags()
- {
- Map flags = null;
-
- File input = new File(TotalFreedomMod.plugin.getDataFolder(), TotalFreedomMod.SAVED_FLAGS_FILENAME);
- if (input.exists())
- {
- try
- {
- FileInputStream fis = new FileInputStream(input);
- ObjectInputStream ois = new ObjectInputStream(fis);
- flags = (HashMap) ois.readObject();
- ois.close();
- fis.close();
- }
- catch (Exception ex)
- {
- Log.severe(ex);
- }
- }
-
- return flags;
- }
-
- public static boolean getSavedFlag(String flag) throws Exception
- {
- Boolean flagValue = null;
-
- Map flags = Utilities.getSavedFlags();
-
- if (flags != null)
- {
- if (flags.containsKey(flag))
- {
- flagValue = flags.get(flag);
- }
- }
-
- if (flagValue != null)
- {
- return flagValue.booleanValue();
- }
- else
- {
- throw new Exception();
- }
- }
-
- public static void setSavedFlag(String flag, boolean value)
- {
- Map flags = Utilities.getSavedFlags();
-
- if (flags == null)
- {
- flags = new HashMap();
- }
-
- flags.put(flag, value);
-
- try
- {
- final FileOutputStream fos = new FileOutputStream(new File(TotalFreedomMod.plugin.getDataFolder(), TotalFreedomMod.SAVED_FLAGS_FILENAME));
- final ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(flags);
- oos.close();
- fos.close();
- }
- catch (Exception ex)
- {
- Log.severe(ex);
- }
- }
-
- public static void createBackups(String file)
- {
- createBackups(file, false);
- }
-
- public static void createBackups(String file, boolean onlyWeekly)
- {
- final String save = file.split("\\.")[0];
- final Configuration config = new Configuration(TotalFreedomMod.plugin, "backup/backup.yml", false);
- config.load();
-
- // Weekly
- if (!config.isInt(save + ".weekly"))
- {
- performBackup(file, "weekly");
- config.set(save + ".weekly", Utilities.getUnixTime());
- }
- else
- {
- int lastBackupWeekly = config.getInt(save + ".weekly");
-
- if (lastBackupWeekly + 3600 * 24 * 7 < Utilities.getUnixTime())
- {
- performBackup(file, "weekly");
- config.set(save + ".weekly", Utilities.getUnixTime());
- }
- }
-
- if (onlyWeekly)
- {
- config.save();
- return;
- }
-
- // Daily
- if (!config.isInt(save + ".daily"))
- {
- performBackup(file, "daily");
- config.set(save + ".daily", Utilities.getUnixTime());
- }
- else
- {
- int lastBackupDaily = config.getInt(save + ".daily");
-
- if (lastBackupDaily + 3600 * 24 < Utilities.getUnixTime())
- {
- performBackup(file, "daily");
- config.set(save + ".daily", Utilities.getUnixTime());
- }
- }
-
- config.save();
- }
-
- private static void performBackup(String file, String type)
- {
- Log.info("Backing up " + file + " to " + file + "." + type + ".bak");
- final File backupFolder = new File(TotalFreedomMod.plugin.getDataFolder(), "backup");
-
- if (!backupFolder.exists())
- {
- backupFolder.mkdirs();
- }
-
- final File oldYaml = new File(TotalFreedomMod.plugin.getDataFolder(), file);
- final File newYaml = new File(backupFolder, file + "." + type + ".bak");
- FileUtil.copy(oldYaml, newYaml);
- }
-
- public static String dateToString(Date date)
- {
- return new SimpleDateFormat(DATE_STORAGE_FORMAT, Locale.ENGLISH).format(date);
- }
-
- public static Date stringToDate(String dateString)
- {
- try
- {
- return new SimpleDateFormat(DATE_STORAGE_FORMAT, Locale.ENGLISH).parse(dateString);
- }
- catch (ParseException pex)
- {
- return new Date(0L);
- }
- }
-
- @SuppressWarnings("unchecked")
- public static boolean isFromHostConsole(String senderName)
- {
- return ConfigurationEntry.HOST_SENDER_NAMES.getList().contains(senderName.toLowerCase());
- }
-
- public static List removeDuplicates(List oldList)
- {
- List newList = new ArrayList();
- for (String entry : oldList)
- {
- if (!newList.contains(entry))
- {
- newList.add(entry);
- }
- }
- return newList;
- }
-
- public static boolean fuzzyIpMatch(String a, String b, int octets)
- {
- boolean match = true;
-
- String[] aParts = a.split("\\.");
- String[] bParts = b.split("\\.");
-
- if (aParts.length != 4 || bParts.length != 4)
- {
- return false;
- }
-
- if (octets > 4)
- {
- octets = 4;
- }
- else if (octets < 1)
- {
- octets = 1;
- }
-
- for (int i = 0; i < octets && i < 4; i++)
- {
- if (aParts[i].equals("*") || bParts[i].equals("*"))
- {
- continue;
- }
-
- if (!aParts[i].equals(bParts[i]))
- {
- match = false;
- break;
- }
- }
-
- 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 int replaceBlocks(Location center, Material fromMaterial, Material toMaterial, int radius)
- {
- int affected = 0;
-
- Block centerBlock = center.getBlock();
- for (int xOffset = -radius; xOffset <= radius; xOffset++)
- {
- for (int yOffset = -radius; yOffset <= radius; yOffset++)
- {
- for (int zOffset = -radius; zOffset <= radius; zOffset++)
- {
- Block block = centerBlock.getRelative(xOffset, yOffset, zOffset);
-
- if (block.getType().equals(fromMaterial))
- {
- if (block.getLocation().distanceSquared(center) < (radius * radius))
- {
- block.setType(toMaterial);
- affected++;
- }
- }
- }
- }
- }
-
- return affected;
- }
-
- public static void downloadFile(String url, File output) throws java.lang.Exception
- {
- downloadFile(url, output, false);
- }
-
- public static void downloadFile(String url, File output, boolean verbose) throws java.lang.Exception
- {
- final URL website = new URL(url);
- ReadableByteChannel rbc = Channels.newChannel(website.openStream());
- FileOutputStream fos = new FileOutputStream(output);
- fos.getChannel().transferFrom(rbc, 0, 1 << 24);
- fos.close();
-
- if (verbose)
- {
- Log.info("Downloaded " + url + " to " + output + ".");
- }
- }
-
- public static void adminChatMessage(CommandSender sender, String message, boolean senderIsConsole)
- {
- String name = sender.getName() + " " + PlayerRank.fromSender(sender).getPrefix() + ChatColor.WHITE;
- Log.info("[ADMIN] " + name + ": " + message);
- String adminChatMessage = "[" + ChatColor.AQUA + "ADMIN" + ChatColor.WHITE + "] " + ChatColor.DARK_RED + name + ": " + ChatColor.AQUA + message;
-
- for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
- {
- if (AdminList.isSuperAdmin(player))
- {
- player.sendMessage(adminChatMessage);
- }
- }
-
- DiscordBridge.transmitAdminMessage(adminChatMessage.replaceAll("([`_~*])", "\\\\$1"));
- }
-
- //getField: Borrowed from WorldEdit
- @SuppressWarnings("unchecked")
- public static T getField(Object from, String name)
- {
- Class> checkClass = from.getClass();
- do
- {
- try
- {
- Field field = checkClass.getDeclaredField(name);
- field.setAccessible(true);
- return (T) field.get(from);
-
- }
- catch (NoSuchFieldException ex)
- {
- }
- catch (IllegalAccessException ex)
- {
- }
- }
- while (checkClass.getSuperclass() != Object.class
- && ((checkClass = checkClass.getSuperclass()) != null));
-
- return null;
- }
-
- public static ChatColor randomChatColor()
- {
- return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size()));
- }
-
- public static String colorize(String string)
- {
- return ChatColor.translateAlternateColorCodes('&', string);
- }
-
- public static long getUnixTime()
- {
- return System.currentTimeMillis() / 1000L;
- }
-
- public static Date getUnixDate(long unix)
- {
- return new Date(unix * 1000);
- }
-
- public static long getUnixTime(Date date)
- {
- if (date == null)
- {
- return 0;
- }
-
- return date.getTime() / 1000L;
- }
-
- public static String getNmsVersion()
- {
- String packageName = Bukkit.getServer().getClass().getPackage().getName();
- return packageName.substring(packageName.lastIndexOf('.') + 1);
-
- }
-
- public static void reportAction(org.bukkit.entity.Player reporter, org.bukkit.entity.Player reported, String report)
- {
- for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
- {
- if (AdminList.isSuperAdmin(player))
- {
- playerMsg(player, ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter.getName() + " has reported " + reported.getName() + " for " + report);
- }
- }
- }
-
- public static class TFM_EntityWiper
- {
- private static final List> WIPEABLES = new ArrayList>();
-
- static
- {
- WIPEABLES.add(EnderCrystal.class);
- WIPEABLES.add(EnderSignal.class);
- WIPEABLES.add(ExperienceOrb.class);
- WIPEABLES.add(Projectile.class);
- WIPEABLES.add(FallingBlock.class);
- WIPEABLES.add(Firework.class);
- WIPEABLES.add(Item.class);
- }
-
- private TFM_EntityWiper()
- {
- throw new AssertionError();
- }
-
- private static boolean canWipe(Entity entity, boolean wipeExplosives, boolean wipeVehicles)
- {
- if (wipeExplosives)
- {
- if (Explosive.class.isAssignableFrom(entity.getClass()))
- {
- return true;
- }
- }
-
- if (wipeVehicles)
- {
- if (Boat.class.isAssignableFrom(entity.getClass()))
- {
- return true;
- }
- else if (Minecart.class.isAssignableFrom(entity.getClass()))
- {
- return true;
- }
- }
-
- Iterator> it = WIPEABLES.iterator();
- while (it.hasNext())
- {
- if (it.next().isAssignableFrom(entity.getClass()))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static int wipeEntities(boolean wipeExplosives, boolean wipeVehicles)
- {
- int removed = 0;
-
- Iterator worlds = Bukkit.getWorlds().iterator();
- while (worlds.hasNext())
- {
- Iterator entities = worlds.next().getEntities().iterator();
- while (entities.hasNext())
- {
- Entity entity = entities.next();
- if (canWipe(entity, wipeExplosives, wipeVehicles))
- {
- entity.remove();
- removed++;
- }
- }
- }
-
- return removed;
- }
- }
-
- public enum EjectMethod
- {
- STRIKE_ONE, STRIKE_TWO, STRIKE_THREE
- }
-
- public static class MethodTimer
- {
- private long lastStart;
- private long total = 0;
-
- public MethodTimer()
- {
- }
-
- public void start()
- {
- this.lastStart = System.currentTimeMillis();
- }
-
- public void update()
- {
- this.total += (System.currentTimeMillis() - this.lastStart);
- }
-
- public long getTotal()
- {
- return this.total;
- }
-
- public void printTotalToLog(String timerName)
- {
- Log.info("DEBUG: " + timerName + " used " + this.getTotal() + " ms.");
- }
- }
+import me.StevenLawson.TotalFreedomMod.Log;
+import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
+import me.StevenLawson.TotalFreedomMod.admin.AdminList;
+import me.StevenLawson.TotalFreedomMod.ban.Ban;
+import me.StevenLawson.TotalFreedomMod.ban.BanManager;
+import me.StevenLawson.TotalFreedomMod.config.Configuration;
+import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
+import me.StevenLawson.TotalFreedomMod.discord.bridge.DiscordBridge;
+import me.StevenLawson.TotalFreedomMod.manager.UUIDManager;
+import me.StevenLawson.TotalFreedomMod.player.Player;
+import me.StevenLawson.TotalFreedomMod.player.PlayerData;
+import me.StevenLawson.TotalFreedomMod.player.PlayerList;
+import me.StevenLawson.TotalFreedomMod.player.PlayerRank;
+import net.md_5.bungee.api.chat.BaseComponent;
+import net.md_5.bungee.api.chat.TextComponent;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.bukkit.Bukkit;
+import org.bukkit.ChatColor;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.SkullType;
+import org.bukkit.World;
+import org.bukkit.block.Block;
+import org.bukkit.block.Skull;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Boat;
+import org.bukkit.entity.Creature;
+import org.bukkit.entity.EnderCrystal;
+import org.bukkit.entity.EnderSignal;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.ExperienceOrb;
+import org.bukkit.entity.Explosive;
+import org.bukkit.entity.FallingBlock;
+import org.bukkit.entity.Firework;
+import org.bukkit.entity.Item;
+import org.bukkit.entity.Minecart;
+import org.bukkit.entity.Projectile;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.util.FileUtil;
+
+public class Utilities {
+
+ private static final Map ejectTracker = new HashMap();
+ public static final Map mobtypes = new HashMap();
+ // See https://github.com/TotalFreedom/License - None of the listed names may be removed.
+ public static final List DEVELOPERS = Arrays.asList("Madgeek1450", "Prozza",
+ "DarthSalmon", "AcidicCyanide", "Wild1145", "WickedGamingUK", "G6_", "videogamesm12",
+ "maniaplay", "evanbt");
+ private static final Random RANDOM = new Random();
+ public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
+ public static final Map CHAT_COLOR_NAMES = new HashMap();
+ public static final List CHAT_COLOR_POOL = Arrays.asList(
+ ChatColor.DARK_BLUE,
+ ChatColor.DARK_GREEN,
+ ChatColor.DARK_AQUA,
+ ChatColor.DARK_RED,
+ ChatColor.DARK_PURPLE,
+ ChatColor.GOLD,
+ ChatColor.BLUE,
+ ChatColor.GREEN,
+ ChatColor.AQUA,
+ ChatColor.RED,
+ ChatColor.LIGHT_PURPLE,
+ ChatColor.YELLOW);
+
+ static {
+ for (EntityType type : EntityType.values()) {
+ try {
+ if (DeprecationUtil.getName_EntityType(type) != null) {
+ if (Creature.class.isAssignableFrom(type.getEntityClass())) {
+ mobtypes.put(DeprecationUtil.getName_EntityType(type).toLowerCase(), type);
+ }
+ }
+ } catch (Exception ex) {
+ }
+ }
+
+ for (ChatColor chatColor : CHAT_COLOR_POOL) {
+ CHAT_COLOR_NAMES.put(chatColor.name().toLowerCase().replace("_", ""), chatColor);
+ }
+ }
+
+ private Utilities() {
+ throw new AssertionError();
+ }
+
+ public static void bcastMsg(String message, ChatColor color, boolean transmitToDiscord) {
+ Log.info(message, true);
+
+ for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
+ player.sendMessage((color == null ? "" : color) + message);
+ }
+
+ if (transmitToDiscord) {
+ DiscordBridge.transmitMessage(message.replaceAll("([`_~*])", "\\\\$1"));
+ }
+ }
+
+ public static void bcastMsg(String message, ChatColor color) {
+ bcastMsg(message, color, true);
+ }
+
+ public static void bcastMsg(String message, boolean transmitToDiscord) {
+ bcastMsg(message, null, transmitToDiscord);
+ }
+
+ public static void bcastMsg(String message) {
+ Utilities.bcastMsg(message, null);
+ }
+
+ // Still in use by listeners
+ public static void playerMsg(CommandSender sender, String message, ChatColor color) {
+ sender.sendMessage(color + message);
+ }
+
+ // Still in use by listeners
+ public static void playerMsg(CommandSender sender, String message) {
+ Utilities.playerMsg(sender, message, ChatColor.GRAY);
+ }
+
+ public static void setFlying(org.bukkit.entity.Player player, boolean flying) {
+ player.setAllowFlight(true);
+ player.setFlying(flying);
+ }
+
+ public static void adminAction(String adminName, String action, boolean isRed) {
+ Utilities.bcastMsg(adminName + " - " + action, (isRed ? ChatColor.RED : ChatColor.AQUA));
+ }
+
+ public static String getIp(OfflinePlayer player) {
+ if (player.isOnline()) {
+ return player.getPlayer().getAddress().getAddress().getHostAddress().trim();
+ }
+
+ final Player entry = PlayerList.getEntry(UUIDManager.getUniqueId(player));
+
+ return (entry == null ? null : entry.getIps().get(0));
+ }
+
+ public static boolean isUniqueId(String uuid) {
+ try {
+ UUID.fromString(uuid);
+ return true;
+ } catch (IllegalArgumentException ex) {
+ return false;
+ }
+ }
+
+ public static String formatLocation(Location location) {
+ return String.format("%s: (%d, %d, %d)",
+ location.getWorld().getName(),
+ Math.round(location.getX()),
+ Math.round(location.getY()),
+ Math.round(location.getZ()));
+ }
+
+ public static String formatPlayer(OfflinePlayer player) {
+ return player.getName() + " (" + UUIDManager.getUniqueId(player) + ")";
+ }
+
+ /**
+ * Escapes an IP-address to a config-friendly version.
+ *
+ * Example:
+ *
+ * IpUtils.toEscapedString("192.168.1.192"); // 192_168_1_192
+ *
+ *
+ * @param ip The IP-address to escape.
+ * @return The config-friendly IP address.
+ * @see #fromEscapedString(String)
+ */
+ public static String toEscapedString(
+ String ip) // BukkitLib @ https://github.com/Pravian/BukkitLib
+ {
+ return ip.trim().replaceAll("\\.", "_");
+ }
+
+ /**
+ * Un-escapes a config-friendly Ipv4-address.
+ *
+ * Example:
+ *
+ * IpUtils.fromEscapedString("192_168_1_192"); // 192.168.1.192
+ *
+ *
+ * @param escapedIp The IP-address to un-escape.
+ * @return The config-friendly IP address.
+ * @see #toEscapedString(String)
+ */
+ public static String fromEscapedString(
+ String escapedIp) // BukkitLib @ https://github.com/Pravian/BukkitLib
+ {
+ return escapedIp.trim().replaceAll("_", "\\.");
+ }
+
+ public static void gotoWorld(org.bukkit.entity.Player player, String targetWorld) {
+ if (player == null) {
+ return;
+ }
+
+ if (player.getWorld().getName().equalsIgnoreCase(targetWorld)) {
+ playerMsg(player, "Going to main world.", ChatColor.GRAY);
+ player.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
+ return;
+ }
+
+ for (World world : Bukkit.getWorlds()) {
+ if (world.getName().equalsIgnoreCase(targetWorld)) {
+ playerMsg(player, "Going to world: " + targetWorld, ChatColor.GRAY);
+ player.teleport(world.getSpawnLocation());
+ return;
+ }
+ }
+
+ playerMsg(player, "World " + targetWorld + " not found.", ChatColor.GRAY);
+ }
+
+ public static String decolorize(String string) {
+ return string.replaceAll("\\u00A7(?=[0-9a-fk-or])", "&");
+ }
+
+ public static void buildHistory(Location location, int length, PlayerData playerdata) {
+ final Block center = location.getBlock();
+ for (int xOffset = -length; xOffset <= length; xOffset++) {
+ for (int yOffset = -length; yOffset <= length; yOffset++) {
+ for (int zOffset = -length; zOffset <= length; zOffset++) {
+ final Block block = center.getRelative(xOffset, yOffset, zOffset);
+ playerdata.insertHistoryBlock(block.getLocation(), block.getType());
+ }
+ }
+ }
+ }
+
+ public static void generateCube(Location location, int length, Material material) {
+ final Block center = location.getBlock();
+ for (int xOffset = -length; xOffset <= length; xOffset++) {
+ for (int yOffset = -length; yOffset <= length; yOffset++) {
+ for (int zOffset = -length; zOffset <= length; zOffset++) {
+ final Block block = center.getRelative(xOffset, yOffset, zOffset);
+ if (block.getType() != material) {
+ block.setType(material);
+ }
+ }
+ }
+ }
+ }
+
+ public static void generateHollowCube(Location location, int length, Material material) {
+ final Block center = location.getBlock();
+ for (int xOffset = -length; xOffset <= length; xOffset++) {
+ for (int yOffset = -length; yOffset <= length; yOffset++) {
+ for (int zOffset = -length; zOffset <= length; zOffset++) {
+ // Hollow
+ if (Math.abs(xOffset) != length && Math.abs(yOffset) != length
+ && Math.abs(zOffset) != length) {
+ continue;
+ }
+
+ final Block block = center.getRelative(xOffset, yOffset, zOffset);
+
+ if (material != Material.SKULL) {
+ // Glowstone light
+ if (material != Material.GLASS && xOffset == 0 && yOffset == 2
+ && zOffset == 0) {
+ block.setType(Material.GLOWSTONE);
+ continue;
+ }
+
+ block.setType(material);
+ } else // Darth mode
+ {
+ if (Math.abs(xOffset) == length && Math.abs(yOffset) == length
+ && Math.abs(zOffset) == length) {
+ block.setType(Material.GLOWSTONE);
+ continue;
+ }
+
+ block.setType(Material.SKULL);
+ final Skull skull = (Skull) block.getState();
+ skull.setSkullType(SkullType.PLAYER);
+ skull.setOwner("Prozza");
+ skull.update();
+ }
+ }
+ }
+ }
+ }
+
+ public static void setWorldTime(World world, long ticks) {
+ long time = world.getTime();
+ time -= time % 24000;
+ world.setTime(time + 24000 + ticks);
+ }
+
+ public static void createDefaultConfiguration(final String configFileName) {
+ final File targetFile = new File(TotalFreedomMod.plugin.getDataFolder(), configFileName);
+
+ if (targetFile.exists()) {
+ return;
+ }
+
+ Log.info("Installing default configuration file template: " + targetFile.getPath());
+
+ try {
+ final InputStream configFileStream = TotalFreedomMod.plugin.getResource(configFileName);
+ FileUtils.copyInputStreamToFile(configFileStream, targetFile);
+ configFileStream.close();
+ } catch (IOException ex) {
+ Log.severe(ex);
+ }
+ }
+
+ public static boolean deleteFolder(final File file) {
+ if (file.exists() && file.isDirectory()) {
+ return FileUtils.deleteQuietly(file);
+ }
+ return false;
+ }
+
+ public static void deleteCoreDumps() {
+ final File[] coreDumps = new File(".").listFiles(new FileFilter() {
+ @Override
+ public boolean accept(File file) {
+ return file.getName().startsWith("java.core");
+ }
+ });
+
+ for (File dump : coreDumps) {
+ Log.info("Removing core dump file: " + dump.getName());
+ dump.delete();
+ }
+ }
+
+ public static EntityType getEntityType(String mobname) throws Exception {
+ mobname = mobname.toLowerCase().trim();
+
+ if (!Utilities.mobtypes.containsKey(mobname)) {
+ throw new Exception();
+ }
+
+ return Utilities.mobtypes.get(mobname);
+ }
+
+ /**
+ * Write the specified InputStream to a file.
+ *
+ * @param in The InputStream from which to read.
+ * @param file The File to write to.
+ * @throws IOException
+ */
+ public static void copy(InputStream in, File file)
+ throws IOException // BukkitLib @ https://github.com/Pravian/BukkitLib
+ {
+ if (!file.exists()) {
+ file.getParentFile().mkdirs();
+ }
+
+ final OutputStream out = new FileOutputStream(file);
+ byte[] buf = new byte[1024];
+ int len;
+ while ((len = in.read(buf)) > 0) {
+ out.write(buf, 0, len);
+ }
+ out.close();
+ in.close();
+ }
+
+ /**
+ * Returns a file at located at the Plugins Data folder.
+ *
+ * @param plugin The plugin to use
+ * @param name The name of the file.
+ * @return The requested file.
+ */
+ public static File getPluginFile(Plugin plugin,
+ String name) // BukkitLib @ https://github.com/Pravian/BukkitLib
+ {
+ return new File(plugin.getDataFolder(), name);
+ }
+
+ public static void autoEject(org.bukkit.entity.Player player, String kickMessage) {
+ EjectMethod method = EjectMethod.STRIKE_ONE;
+ final String ip = Utilities.getIp(player);
+
+ if (!Utilities.ejectTracker.containsKey(ip)) {
+ Utilities.ejectTracker.put(ip, 0);
+ }
+
+ int kicks = Utilities.ejectTracker.get(ip);
+ kicks += 1;
+
+ Utilities.ejectTracker.put(ip, kicks);
+
+ if (kicks <= 1) {
+ method = EjectMethod.STRIKE_ONE;
+ } else if (kicks == 2) {
+ method = EjectMethod.STRIKE_TWO;
+ } else if (kicks >= 3) {
+ method = EjectMethod.STRIKE_THREE;
+ }
+
+ Log.info("AutoEject -> name: " + player.getName() + " - player ip: " + ip + " - method: "
+ + method);
+
+ player.setOp(false);
+ player.setGameMode(GameMode.SURVIVAL);
+ player.getInventory().clear();
+
+ switch (method) {
+ case STRIKE_ONE: {
+ final Calendar cal = new GregorianCalendar();
+ cal.add(Calendar.MINUTE, 1);
+ final Date expires = cal.getTime();
+
+ Utilities.bcastMsg(
+ ChatColor.RED + player.getName() + " has been banned for 1 minute.");
+
+ BanManager.addIpBan(
+ new Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
+ BanManager.addUuidBan(
+ new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", expires,
+ kickMessage));
+ player.kickPlayer(kickMessage);
+
+ break;
+ }
+ case STRIKE_TWO: {
+ final Calendar c = new GregorianCalendar();
+ c.add(Calendar.MINUTE, 3);
+ final Date expires = c.getTime();
+
+ Utilities.bcastMsg(
+ ChatColor.RED + player.getName() + " has been banned for 3 minutes.");
+
+ BanManager.addIpBan(
+ new Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
+ BanManager.addUuidBan(
+ new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", expires,
+ kickMessage));
+ player.kickPlayer(kickMessage);
+ break;
+ }
+ case STRIKE_THREE: {
+ String[] ipAddressParts = ip.split("\\.");
+
+ BanManager.addIpBan(new Ban(ip, player.getName(), "AutoEject", null, kickMessage));
+ BanManager.addIpBan(
+ new Ban(ipAddressParts[0] + "." + ipAddressParts[1] + ".*.*", player.getName(),
+ "AutoEject", null, kickMessage));
+ BanManager.addUuidBan(
+ new Ban(UUIDManager.getUniqueId(player), player.getName(), "AutoEject", null,
+ kickMessage));
+
+ Utilities.bcastMsg(ChatColor.RED + player.getName() + " has been banned.");
+
+ player.kickPlayer(kickMessage);
+ break;
+ }
+ }
+ }
+
+ public static Date parseDateOffset(String time) {
+ Pattern timePattern = Pattern.compile(
+ "(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
+ + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
+ Matcher m = timePattern.matcher(time);
+ int years = 0;
+ int months = 0;
+ int weeks = 0;
+ int days = 0;
+ int hours = 0;
+ int minutes = 0;
+ int seconds = 0;
+ boolean found = false;
+ while (m.find()) {
+ if (m.group() == null || m.group().isEmpty()) {
+ continue;
+ }
+ for (int i = 0; i < m.groupCount(); i++) {
+ if (m.group(i) != null && !m.group(i).isEmpty()) {
+ found = true;
+ break;
+ }
+ }
+ if (found) {
+ if (m.group(1) != null && !m.group(1).isEmpty()) {
+ years = Integer.parseInt(m.group(1));
+ }
+ if (m.group(2) != null && !m.group(2).isEmpty()) {
+ months = Integer.parseInt(m.group(2));
+ }
+ if (m.group(3) != null && !m.group(3).isEmpty()) {
+ weeks = Integer.parseInt(m.group(3));
+ }
+ if (m.group(4) != null && !m.group(4).isEmpty()) {
+ days = Integer.parseInt(m.group(4));
+ }
+ if (m.group(5) != null && !m.group(5).isEmpty()) {
+ hours = Integer.parseInt(m.group(5));
+ }
+ if (m.group(6) != null && !m.group(6).isEmpty()) {
+ minutes = Integer.parseInt(m.group(6));
+ }
+ if (m.group(7) != null && !m.group(7).isEmpty()) {
+ seconds = Integer.parseInt(m.group(7));
+ }
+ break;
+ }
+ }
+ if (!found) {
+ return null;
+ }
+
+ Calendar c = new GregorianCalendar();
+
+ if (years > 0) {
+ c.add(Calendar.YEAR, years);
+ }
+ if (months > 0) {
+ c.add(Calendar.MONTH, months);
+ }
+ if (weeks > 0) {
+ c.add(Calendar.WEEK_OF_YEAR, weeks);
+ }
+ if (days > 0) {
+ c.add(Calendar.DAY_OF_MONTH, days);
+ }
+ if (hours > 0) {
+ c.add(Calendar.HOUR_OF_DAY, hours);
+ }
+ if (minutes > 0) {
+ c.add(Calendar.MINUTE, minutes);
+ }
+ if (seconds > 0) {
+ c.add(Calendar.SECOND, seconds);
+ }
+
+ return c.getTime();
+ }
+
+ public static String playerListToNames(Set players) {
+ List names = new ArrayList();
+ for (OfflinePlayer player : players) {
+ names.add(player.getName());
+ }
+ return StringUtils.join(names, ", ");
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Map getSavedFlags() {
+ Map flags = null;
+
+ File input = new File(TotalFreedomMod.plugin.getDataFolder(),
+ TotalFreedomMod.SAVED_FLAGS_FILENAME);
+ if (input.exists()) {
+ try {
+ FileInputStream fis = new FileInputStream(input);
+ ObjectInputStream ois = new ObjectInputStream(fis);
+ flags = (HashMap) ois.readObject();
+ ois.close();
+ fis.close();
+ } catch (Exception ex) {
+ Log.severe(ex);
+ }
+ }
+
+ return flags;
+ }
+
+ public static boolean getSavedFlag(String flag) throws Exception {
+ Boolean flagValue = null;
+
+ Map flags = Utilities.getSavedFlags();
+
+ if (flags != null) {
+ if (flags.containsKey(flag)) {
+ flagValue = flags.get(flag);
+ }
+ }
+
+ if (flagValue != null) {
+ return flagValue.booleanValue();
+ } else {
+ throw new Exception();
+ }
+ }
+
+ public static void setSavedFlag(String flag, boolean value) {
+ Map flags = Utilities.getSavedFlags();
+
+ if (flags == null) {
+ flags = new HashMap();
+ }
+
+ flags.put(flag, value);
+
+ try {
+ final FileOutputStream fos = new FileOutputStream(
+ new File(TotalFreedomMod.plugin.getDataFolder(),
+ TotalFreedomMod.SAVED_FLAGS_FILENAME));
+ final ObjectOutputStream oos = new ObjectOutputStream(fos);
+ oos.writeObject(flags);
+ oos.close();
+ fos.close();
+ } catch (Exception ex) {
+ Log.severe(ex);
+ }
+ }
+
+ public static void createBackups(String file) {
+ createBackups(file, false);
+ }
+
+ public static void createBackups(String file, boolean onlyWeekly) {
+ final String save = file.split("\\.")[0];
+ final Configuration config = new Configuration(TotalFreedomMod.plugin, "backup/backup.yml",
+ false);
+ config.load();
+
+ // Weekly
+ if (!config.isInt(save + ".weekly")) {
+ performBackup(file, "weekly");
+ config.set(save + ".weekly", Utilities.getUnixTime());
+ } else {
+ int lastBackupWeekly = config.getInt(save + ".weekly");
+
+ if (lastBackupWeekly + 3600 * 24 * 7 < Utilities.getUnixTime()) {
+ performBackup(file, "weekly");
+ config.set(save + ".weekly", Utilities.getUnixTime());
+ }
+ }
+
+ if (onlyWeekly) {
+ config.save();
+ return;
+ }
+
+ // Daily
+ if (!config.isInt(save + ".daily")) {
+ performBackup(file, "daily");
+ config.set(save + ".daily", Utilities.getUnixTime());
+ } else {
+ int lastBackupDaily = config.getInt(save + ".daily");
+
+ if (lastBackupDaily + 3600 * 24 < Utilities.getUnixTime()) {
+ performBackup(file, "daily");
+ config.set(save + ".daily", Utilities.getUnixTime());
+ }
+ }
+
+ config.save();
+ }
+
+ private static void performBackup(String file, String type) {
+ Log.info("Backing up " + file + " to " + file + "." + type + ".bak");
+ final File backupFolder = new File(TotalFreedomMod.plugin.getDataFolder(), "backup");
+
+ if (!backupFolder.exists()) {
+ backupFolder.mkdirs();
+ }
+
+ final File oldYaml = new File(TotalFreedomMod.plugin.getDataFolder(), file);
+ final File newYaml = new File(backupFolder, file + "." + type + ".bak");
+ FileUtil.copy(oldYaml, newYaml);
+ }
+
+ public static String dateToString(Date date) {
+ return new SimpleDateFormat(DATE_STORAGE_FORMAT, Locale.ENGLISH).format(date);
+ }
+
+ public static Date stringToDate(String dateString) {
+ try {
+ return new SimpleDateFormat(DATE_STORAGE_FORMAT, Locale.ENGLISH).parse(dateString);
+ } catch (ParseException pex) {
+ return new Date(0L);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public static boolean isFromHostConsole(String senderName) {
+ return ConfigurationEntry.HOST_SENDER_NAMES.getList().contains(senderName.toLowerCase());
+ }
+
+ public static List removeDuplicates(List oldList) {
+ List newList = new ArrayList();
+ for (String entry : oldList) {
+ if (!newList.contains(entry)) {
+ newList.add(entry);
+ }
+ }
+ return newList;
+ }
+
+ public static boolean fuzzyIpMatch(String a, String b, int octets) {
+ boolean match = true;
+
+ String[] aParts = a.split("\\.");
+ String[] bParts = b.split("\\.");
+
+ if (aParts.length != 4 || bParts.length != 4) {
+ return false;
+ }
+
+ if (octets > 4) {
+ octets = 4;
+ } else if (octets < 1) {
+ octets = 1;
+ }
+
+ for (int i = 0; i < octets && i < 4; i++) {
+ if (aParts[i].equals("*") || bParts[i].equals("*")) {
+ continue;
+ }
+
+ if (!aParts[i].equals(bParts[i])) {
+ match = false;
+ break;
+ }
+ }
+
+ 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 int replaceBlocks(Location center, Material fromMaterial, Material toMaterial,
+ int radius) {
+ int affected = 0;
+
+ Block centerBlock = center.getBlock();
+ for (int xOffset = -radius; xOffset <= radius; xOffset++) {
+ for (int yOffset = -radius; yOffset <= radius; yOffset++) {
+ for (int zOffset = -radius; zOffset <= radius; zOffset++) {
+ Block block = centerBlock.getRelative(xOffset, yOffset, zOffset);
+
+ if (block.getType().equals(fromMaterial)) {
+ if (block.getLocation().distanceSquared(center) < (radius * radius)) {
+ block.setType(toMaterial);
+ affected++;
+ }
+ }
+ }
+ }
+ }
+
+ return affected;
+ }
+
+ public static void downloadFile(String url, File output) throws java.lang.Exception {
+ downloadFile(url, output, false);
+ }
+
+ public static void downloadFile(String url, File output, boolean verbose)
+ throws java.lang.Exception {
+ final URL website = new URL(url);
+ ReadableByteChannel rbc = Channels.newChannel(website.openStream());
+ FileOutputStream fos = new FileOutputStream(output);
+ fos.getChannel().transferFrom(rbc, 0, 1 << 24);
+ fos.close();
+
+ if (verbose) {
+ Log.info("Downloaded " + url + " to " + output + ".");
+ }
+ }
+
+ public static void adminChatMessage(CommandSender sender, String message,
+ boolean senderIsConsole) {
+ String name =
+ sender.getName() + " " + PlayerRank.fromSender(sender).getPrefix() + ChatColor.WHITE;
+ Log.info("[ADMIN] " + name + ": " + message);
+ String adminChatMessage =
+ "[" + ChatColor.AQUA + "ADMIN" + ChatColor.WHITE + "] " + ChatColor.DARK_RED + name
+ + ": " + ChatColor.AQUA + message;
+
+ for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
+ if (AdminList.isSuperAdmin(player)) {
+ player.sendMessage(adminChatMessage);
+ }
+ }
+
+ DiscordBridge.transmitAdminMessage(adminChatMessage.replaceAll("([`_~*])", "\\\\$1"));
+ }
+
+ //getField: Borrowed from WorldEdit
+ @SuppressWarnings("unchecked")
+ public static T getField(Object from, String name) {
+ Class> checkClass = from.getClass();
+ do {
+ try {
+ Field field = checkClass.getDeclaredField(name);
+ field.setAccessible(true);
+ return (T) field.get(from);
+
+ } catch (NoSuchFieldException ex) {
+ } catch (IllegalAccessException ex) {
+ }
+ }
+ while (checkClass.getSuperclass() != Object.class
+ && ((checkClass = checkClass.getSuperclass()) != null));
+
+ return null;
+ }
+
+ public static ChatColor randomChatColor() {
+ return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size()));
+ }
+
+ public static TextComponent fromBaseComponents(BaseComponent[] components) {
+ TextComponent newComponent = new TextComponent("");
+
+ for (BaseComponent component : components) {
+ newComponent.addExtra(component);
+ }
+
+ return newComponent;
+ }
+
+ public static String colorize(String string) {
+ return ChatColor.translateAlternateColorCodes('&', string);
+ }
+
+ public static long getUnixTime() {
+ return System.currentTimeMillis() / 1000L;
+ }
+
+ public static Date getUnixDate(long unix) {
+ return new Date(unix * 1000);
+ }
+
+ public static long getUnixTime(Date date) {
+ if (date == null) {
+ return 0;
+ }
+
+ return date.getTime() / 1000L;
+ }
+
+ public static String getNmsVersion() {
+ String packageName = Bukkit.getServer().getClass().getPackage().getName();
+ return packageName.substring(packageName.lastIndexOf('.') + 1);
+
+ }
+
+ public static void reportAction(org.bukkit.entity.Player reporter,
+ org.bukkit.entity.Player reported, String report) {
+ for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
+ if (AdminList.isSuperAdmin(player)) {
+ playerMsg(player, ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter.getName()
+ + " has reported " + reported.getName() + " for " + report);
+ }
+ }
+ }
+
+ public static class TFM_EntityWiper {
+
+ private static final List> WIPEABLES = new ArrayList>();
+
+ static {
+ WIPEABLES.add(EnderCrystal.class);
+ WIPEABLES.add(EnderSignal.class);
+ WIPEABLES.add(ExperienceOrb.class);
+ WIPEABLES.add(Projectile.class);
+ WIPEABLES.add(FallingBlock.class);
+ WIPEABLES.add(Firework.class);
+ WIPEABLES.add(Item.class);
+ }
+
+ private TFM_EntityWiper() {
+ throw new AssertionError();
+ }
+
+ private static boolean canWipe(Entity entity, boolean wipeExplosives,
+ boolean wipeVehicles) {
+ if (wipeExplosives) {
+ if (Explosive.class.isAssignableFrom(entity.getClass())) {
+ return true;
+ }
+ }
+
+ if (wipeVehicles) {
+ if (Boat.class.isAssignableFrom(entity.getClass())) {
+ return true;
+ } else if (Minecart.class.isAssignableFrom(entity.getClass())) {
+ return true;
+ }
+ }
+
+ Iterator> it = WIPEABLES.iterator();
+ while (it.hasNext()) {
+ if (it.next().isAssignableFrom(entity.getClass())) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static int wipeEntities(boolean wipeExplosives, boolean wipeVehicles) {
+ int removed = 0;
+
+ Iterator worlds = Bukkit.getWorlds().iterator();
+ while (worlds.hasNext()) {
+ Iterator entities = worlds.next().getEntities().iterator();
+ while (entities.hasNext()) {
+ Entity entity = entities.next();
+ if (canWipe(entity, wipeExplosives, wipeVehicles)) {
+ entity.remove();
+ removed++;
+ }
+ }
+ }
+
+ return removed;
+ }
+ }
+
+ public enum EjectMethod {
+ STRIKE_ONE, STRIKE_TWO, STRIKE_THREE
+ }
+
+ public static class MethodTimer {
+
+ private long lastStart;
+ private long total = 0;
+
+ public MethodTimer() {
+ }
+
+ public void start() {
+ this.lastStart = System.currentTimeMillis();
+ }
+
+ public void update() {
+ this.total += (System.currentTimeMillis() - this.lastStart);
+ }
+
+ public long getTotal() {
+ return this.total;
+ }
+
+ public void printTotalToLog(String timerName) {
+ Log.info("DEBUG: " + timerName + " used " + this.getTotal() + " ms.");
+ }
+ }
}