From bce31de137bdb41403d5ed393f06930d8a063d4f Mon Sep 17 00:00:00 2001 From: NorbiPeti Date: Thu, 23 Jun 2016 00:08:39 +0200 Subject: [PATCH] Command refactoring is in progress... --- plugin.yml | 71 +- .../norbipeti/thebuttonmc/ChatProcessing.java | 1010 +++++++------- .../norbipeti/thebuttonmc/Commands.java | 1185 ++++++----------- .../norbipeti/thebuttonmc/PluginMain.java | 837 ++++++------ 4 files changed, 1353 insertions(+), 1750 deletions(-) diff --git a/plugin.yml b/plugin.yml index c30ca85..d14a0b7 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,37 +1,34 @@ -name: TheButtonMCPlugin -main: io.github.norbipeti.thebuttonmc.PluginMain -version: 4.0 -commands: - u: - description: Auto-flair system. Accept or ignore flair. - usage: "&cUsage: /u accept|ignore|opme&r" - nrp: - description: Send message in Out-of-Character. - usage: "&cUsage: /nrp &r" - ooc: - description: Send message in Out-of-Character. - usage: "&cUsage: /ooc &r" - unlol: - description: Unlaugh the last laugh. - unlaugh: - description: Unlaugh the last laugh. - mwiki: - description: Search the wiki. - usage: "&cUsage: /mwiki [query]&r" - dontrunthiscmd: - tableflip: - description: Flip a table. - usage: "&cUsage: /tableflip [message]&r" - unflip: - description: Unflip a flip. - usage: "&cUsage: /unflip [message]&r" - chatonly: - description: Enable chat only mode. Useful for chat clients. - usage: "&cUsage: /chatonly&r" -author: NorbiPeti -depend: [Essentials, Towny, Minigames, Votifier, Factions, WorldGuard, WorldEdit, ProtocolLib, FastLogin, Vault, AuthMe] -permissions: - tbmc.admin: - description: Gives access to /un- commands and /u admin commands - tbmc.rainbow: - description: Gives access to rainbow colors (/u c). +name: TheButtonMCPlugin +main: io.github.norbipeti.thebuttonmc.PluginMain +version: 4.0 +commands: + u: + description: Auto-flair system. Accept or ignore flair. + usage: "&cUsage: /u accept|ignore|opme&r" + ooc: + description: Send message in Out-of-Character. + usage: "&cUsage: /ooc &r" + alias: nrp + unlol: + description: Unlaugh the last laugh. + alias: unlaugh + mwiki: + description: Search the wiki. + usage: "&cUsage: /mwiki [query]&r" + dontrunthiscmd: + tableflip: + description: Flip a table. + usage: "&cUsage: /tableflip [message]&r" + unflip: + description: Unflip a flip. + usage: "&cUsage: /unflip [message]&r" + chatonly: + description: Enable chat only mode. Useful for chat clients. + usage: "&cUsage: /chatonly&r" +author: NorbiPeti +depend: [Essentials, Towny, Minigames, Votifier, Factions, WorldGuard, WorldEdit, ProtocolLib, FastLogin, Vault, AuthMe] +permissions: + tbmc.admin: + description: Gives access to /un- commands and /u admin commands + tbmc.rainbow: + description: Gives access to rainbow colors (/u c). diff --git a/src/io/github/norbipeti/thebuttonmc/ChatProcessing.java b/src/io/github/norbipeti/thebuttonmc/ChatProcessing.java index d74721a..5a6e47a 100644 --- a/src/io/github/norbipeti/thebuttonmc/ChatProcessing.java +++ b/src/io/github/norbipeti/thebuttonmc/ChatProcessing.java @@ -1,511 +1,499 @@ -package io.github.norbipeti.thebuttonmc; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.Sound; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Objective; - -import ru.tehkode.permissions.bukkit.PermissionsEx; - -import com.earth2me.essentials.Essentials; -import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; -import com.palmergames.bukkit.towny.object.Nation; -import com.palmergames.bukkit.towny.object.Resident; -import com.palmergames.bukkit.towny.object.Town; - -public class ChatProcessing { - // Returns e.setCancelled - public static boolean ProcessChat(CommandSender sender, String message) { - if (PlayerListener.essentials == null) - PlayerListener.essentials = (Essentials) (Bukkit.getPluginManager() - .getPlugin("Essentials")); - Player player = (sender instanceof Player ? (Player) sender : null); - - if (player != null - && PlayerListener.essentials.getUser(player).isMuted()) - return true; - - MaybeOfflinePlayer mp = null; - if (player != null) { - mp = MaybeOfflinePlayer.AllPlayers.get(player.getUniqueId()); - if (message.equalsIgnoreCase("F")) { - if (!mp.PressedF && PlayerListener.ActiveF) { - PlayerListener.FCount++; - mp.PressedF = true; - if (PlayerListener.FPlayer != null - && PlayerListener.FPlayer.FCount < Integer.MAX_VALUE - 1) - PlayerListener.FPlayer.FCount++; - } - } - } - - String msg = message.toLowerCase(); - if (msg.contains("lol")) { - if (player != null) { - Commands.Lastlol = player; - Commands.Lastlolornot = true; - Commands.Lastlolconsole = false; - } else { - Commands.Lastlolornot = true; - Commands.Lastlolconsole = true; - Commands.Lastlol = null; - } - } else { - for (int i = 0; i < PlayerListener.LaughStrings.length; i++) { - if (msg.contains(PlayerListener.LaughStrings[i])) { - if (player != null) { - Commands.Lastlol = player; - Commands.Lastlolornot = false; - Commands.Lastlolconsole = false; - } else { - Commands.Lastlolornot = false; - Commands.Lastlolconsole = true; - Commands.Lastlol = null; - } - break; - } - } - } - Channel currentchannel = (mp == null ? PlayerListener.ConsoleChannel - : mp.CurrentChannel); - - String colormode = currentchannel.Color; - if (mp != null && mp.OtherColorMode.length() > 0) - colormode = mp.OtherColorMode; - if (message.startsWith(">")) - colormode = "green"; // If greentext, ignore channel or player - // colors - - String formattedmessage = message; - formattedmessage = formattedmessage.replace("\\", "\\\\"); // It's - // really - // important - // to escape - // the - // slashes - // first - formattedmessage = formattedmessage.replace("\"", "\\\""); - if (PluginMain.permission.has(sender, "tbmc.admin")) - formattedmessage = formattedmessage.replace("&", "§"); - formattedmessage = formattedmessage.replace("§r", "§" - + currentchannel.DisplayName.charAt(1)); - String suggestmsg = formattedmessage; - boolean cont = true; - while (cont) { - - int first_under = formattedmessage.indexOf("_"); - if (first_under != -1 - && formattedmessage.indexOf("_", first_under + 1) != -1) // underline - { - formattedmessage = formattedmessage.replaceFirst("_", "§n") - .replaceFirst("_", "§r"); - continue; - } - - int first_bold = formattedmessage.indexOf("**"); - if (first_bold != -1 - && formattedmessage.indexOf("**", first_bold + 1) != -1) // bold - { - formattedmessage = formattedmessage - .replaceFirst("\\*\\*", "§l").replaceFirst("\\*\\*", - "§r"); - continue; - } - int first = formattedmessage.indexOf('*'); - if (first != -1 && formattedmessage.indexOf('*', first + 1) != -1) { - formattedmessage = formattedmessage.replaceFirst("\\*", "§o") - .replaceFirst("\\*", "§r"); - continue; - } - cont = false; - } - - // URLs + Rainbow text - String[] parts = formattedmessage.split("\\s+"); - boolean hadurls = false; - final String[] RainbowPresserColors = new String[] { "c", "6", "e", - "a", "9", "5" }; - int rpc = 0; - int currentindex = 0; - for (String item : parts) { - try { - URL url = new URL(item); - formattedmessage = formattedmessage - .replace( - item, - String.format( - "\",\"color\":\"%s\"},{\"text\":\"%s\",\"color\":\"%s\",\"underlined\":\"true\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"%s\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Open URL\",\"color\":\"blue\"}]}}},{\"text\":\"", - colormode, url, colormode, url)); - hadurls = true; - } catch (MalformedURLException e) { - } - if (mp != null && mp.RainbowPresserColorMode) { - if (item.startsWith(RainbowPresserColors[rpc])) { // Prevent - // words - // being - // equal/starting - // with a - // color - // code - // letter to - // be messed - // up - if (rpc + 1 < RainbowPresserColors.length) - rpc++; - else - rpc = 0; - } - StringBuffer buf = new StringBuffer(formattedmessage); - buf.replace(currentindex, currentindex + item.length(), - String.format("§%s%s", RainbowPresserColors[rpc], item)); - formattedmessage = buf.toString(); - if (rpc + 1 < RainbowPresserColors.length) - rpc++; - else - rpc = 0; - } - currentindex += item.length() + 3; - } - - if (!hadurls) { - for (Player p : PluginMain.GetPlayers()) { - String color = ""; - if (formattedmessage.matches("(?i).*" - + Pattern.quote(p.getName()) + ".*")) { - if (PlayerListener.NotificationSound == null) - p.playSound(p.getLocation(), - Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: - // Airhorn - else - p.playSound(p.getLocation(), - PlayerListener.NotificationSound, 1.0f, - (float) PlayerListener.NotificationPitch); - MaybeOfflinePlayer mpp = MaybeOfflinePlayer - .AddPlayerIfNeeded(p.getUniqueId()); - color = String.format( - "§%x", - (mpp.GetFlairColor() == 0x00 ? 0xb : mpp - .GetFlairColor())); - } - - formattedmessage = formattedmessage - .replaceAll( - "(?i)" + Pattern.quote(p.getName()), - String.format( - "\",\"color\":\"%s\"},{\"text\":\"%s%s%s\",\"color\":\"blue\"},{\"text\":\"", - colormode, color, p.getName(), "§r")); - } - for (String n : PlayerListener.nicknames.keySet()) { - Player p = null; - String nwithoutformatting = new String(n); - int index; - while ((index = nwithoutformatting.indexOf("§k")) != -1) - nwithoutformatting = nwithoutformatting.replace("§k" - + nwithoutformatting.charAt(index + 2), ""); // Support - // for - // one - // random - // char - while ((index = nwithoutformatting.indexOf('§')) != -1) - nwithoutformatting = nwithoutformatting.replace("§" - + nwithoutformatting.charAt(index + 1), ""); - if (formattedmessage.matches("(?i).*" - + Pattern.quote(nwithoutformatting) + ".*")) { - p = Bukkit.getPlayer(PlayerListener.nicknames.get(n)); - if (PlayerListener.NotificationSound == null) - p.playSound(p.getLocation(), - Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // 2015.08.12. - else - p.playSound(p.getLocation(), - PlayerListener.NotificationSound, 1.0f, - (float) PlayerListener.NotificationPitch); - MaybeOfflinePlayer.AddPlayerIfNeeded(p.getUniqueId()); - } - if (p != null) { - - formattedmessage = formattedmessage - .replaceAll( - "(?i)" + Pattern.quote(nwithoutformatting), - String.format( - "\",\"color\":\"%s\"},{\"text\":\"%s%s\",\"color\":\"blue\"},{\"text\":\"", - colormode, n, "§r")); - } - } - - if (formattedmessage.matches("(?i).*" + Pattern.quote("@console") - + ".*")) { - formattedmessage = formattedmessage.replaceAll( - "(?i)" + Pattern.quote("@console"), "§b@console§r"); - formattedmessage = formattedmessage - .replaceAll( - "(?i)" + Pattern.quote("@console"), - String.format( - "\",\"color\":\"%s\"},{\"text\":\"§b@console§r\",\"color\":\"blue\"},{\"text\":\"", - colormode)); - System.out.println("\007"); - } - } - - StringBuilder json = new StringBuilder(); - json.append("[\"\","); - json.append(String - .format("%s{\"text\":\"[%s]%s\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"Copy message\",\"color\":\"blue\"}},\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"%s\"}},", - (mp != null && mp.ChatOnly ? "{\"text\":\"[C]\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Chat only\",\"color\":\"blue\"}]}}}," - // (mp != null && mp.ChatOnly ? - // "{\"text:\":\"\"}," - I have been staring at - // this one line for hours... Hours... - : ""), currentchannel.DisplayName, (mp != null - && !mp.RPMode ? "[OOC]" : ""), suggestmsg)); - json.append("{\"text\":\" <\"},"); - json.append(String.format("{\"text\":\"%s%s\",", - (player != null ? player.getDisplayName() : sender.getName()), - (mp != null ? mp.GetFormattedFlair() : ""))); - json.append("\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":["); - json.append(String.format("{\"text\":\"%s\n\",", - (player != null ? player.getName() : sender.getName()))); - json.append(String - .format("\"color\":\"aqua\"},{\"text\":\"World: %s\n\",\"color\":\"white\"},", - (player != null ? player.getWorld().getName() : "-"))); - json.append(String - .format("{\"text\":\"Respect: %s%s%s\",\"color\":\"white\"}]}}},", - (mp != null ? (mp.FCount / (double) mp.FDeaths) - : "Infinite"), - (mp != null && mp.UserName != null - && !mp.UserName.isEmpty() ? "\nUserName: " - + mp.UserName : ""), - (mp != null && mp.PlayerName.equals("\nAlpha_Bacca44") ? "\nDeaths: " - + PlayerListener.AlphaDeaths - : ""))); - json.append("{\"text\":\"> \",\"color\":\"white\"},"); - - int index = -1; - ArrayList list = new ArrayList(); - while ((index = message.indexOf("#", index + 1)) != -1) { - int index2 = message.indexOf(" ", index + 1); - if (index2 == -1) - index2 = message.length(); - int index3 = message.indexOf("#", index + 1); - if (index3 != -1 && index3 < index2) // A # occurs before a - // space - index2 = index3; - String original = message.substring(index + 1, index2); - list.add(original); - } - - if (!hadurls) { - for (String original : list) - // Hashtags - formattedmessage = formattedmessage - .replace( - "#" + original, - String.format( - "\",\"color\":\"%s\"},{\"text\":\"#%s\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://twitter.com/hashtag/%s\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Open on Twitter\",\"color\":\"blue\"}]}}},{\"text\":\"", - colormode, original, original)); - } - - json.append(String.format("{\"text\":\"%s\",\"color\":\"%s\"}]", - formattedmessage, colormode)); - String jsonstr = json.toString(); - if (jsonstr.length() >= 32767) { - sender.sendMessage("§cError: Message too large. Try shortening it, or remove hashtags and other formatting."); - return true; - } - if (currentchannel.equals(Channel.TownChat) - || currentchannel.equals(Channel.NationChat)) { - if (player == null) { - sender.sendMessage("§cYou are not a player!"); - return true; - } - for (Player p : PluginMain.GetPlayers()) { - try { - Resident resident = PluginMain.Instance.TU.getResidentMap() - .get(p.getName().toLowerCase()); - if (!resident.getName().equals(player.getName()) - && resident.getModes().contains("spy")) - Bukkit.getPlayer(resident.getName()).sendMessage( - String.format("[SPY-%s] - %s: %s", - currentchannel.DisplayName, - player.getDisplayName(), message)); - } catch (Exception e) { - } - } - } - if (currentchannel.equals(Channel.TownChat)) { - try { - Town town = null; - try { - town = PluginMain.Instance.TU.getResidentMap() - .get(player.getName().toLowerCase()).getTown(); - } catch (NotRegisteredException e) { - } - if (town == null) { - player.sendMessage("§cYou aren't in a town or an error occured."); - return true; - } - index = PluginMain.Instance.Towns.indexOf(town); - if (index < 0) { - PluginMain.Instance.Towns.add(town); - index = PluginMain.Instance.Towns.size() - 1; - } - Objective obj = PluginMain.SB.getObjective("town"); - for (Player p : PluginMain.GetPlayers()) { - try { - if (PluginMain.Instance.TU.getResidentMap() - .get(p.getName().toLowerCase()).getTown() - .getName().equals(town.getName())) - obj.getScore(p.getName()).setScore(index); - else - obj.getScore(p.getName()).setScore(-1); - } catch (Exception e) { - obj.getScore(p.getName()).setScore(-1); - } - } - PluginMain.Instance - .getServer() - .dispatchCommand( - PluginMain.Console, - String.format( - "tellraw @a[score_town=%d,score_town_min=%d] %s", - index, index, json.toString())); - } catch (IllegalStateException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); - return true; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); - return true; - } - } else if (currentchannel.equals(Channel.NationChat)) { - try { - Town town = null; - try { - town = PluginMain.Instance.TU.getResidentMap() - .get(player.getName().toLowerCase()).getTown(); - } catch (NotRegisteredException e) { - } - if (town == null) { - player.sendMessage("§cYou aren't in a town or an error occured."); - return true; - } - Nation nation = null; - try { - nation = town.getNation(); - } catch (NotRegisteredException e) { - } - if (nation == null) { - player.sendMessage("§cYour town isn't in a nation or an error occured."); - return true; - } - index = PluginMain.Instance.Nations.indexOf(nation); - if (index < 0) { - PluginMain.Instance.Nations.add(nation); - index = PluginMain.Instance.Nations.size() - 1; - } - Objective obj = PluginMain.SB.getObjective("nation"); - for (Player p : PluginMain.GetPlayers()) { - try { - if (PluginMain.Instance.TU.getResidentMap() - .get(p.getName().toLowerCase()).getTown() - .getNation().getName().equals(nation.getName())) - obj.getScore(p.getName()).setScore(index); - else - obj.getScore(p.getName()).setScore(-1); - } catch (Exception e) { - } - } - PluginMain.Instance - .getServer() - .dispatchCommand( - PluginMain.Console, - String.format( - "tellraw @a[score_nation=%d,score_nation_min=%d] %s", - index, index, json.toString())); - } catch (IllegalStateException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); - return true; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); - return true; - } - } else if (currentchannel.equals(Channel.AdminChat)) { - try { // TODO: Put message JSON into it's structure - if (player != null && !player.isOp()) { - player.sendMessage("§cYou need to be an OP to use this channel."); - return true; - } - Objective obj = PluginMain.SB.getObjective("admin"); - for (Player p : PluginMain.GetPlayers()) { - if (p.isOp()) - obj.getScore(p.getName()).setScore(1); - else - obj.getScore(p.getName()).setScore(0); - } - PluginMain.Instance - .getServer() - .dispatchCommand( - PluginMain.Console, - String.format( - "tellraw @a[score_admin=%d,score_admin_min=%d] %s", - 1, 1, json.toString())); - } catch (IllegalStateException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); - return true; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); - return true; - } - } else if (currentchannel.equals(Channel.ModChat)) { - try { - if (player != null - && !PermissionsEx.getUser(player).inGroup("mod")) { - player.sendMessage("§cYou need to be a mod to use this channel."); - return true; - } - Objective obj = PluginMain.SB.getObjective("mod"); - for (Player p : PluginMain.GetPlayers()) { - if (PermissionsEx.getUser(p).inGroup("mod")) - obj.getScore(p.getName()).setScore(1); - else - obj.getScore(p.getName()).setScore(0); - } - PluginMain.Instance.getServer().dispatchCommand( - PluginMain.Console, - String.format( - "tellraw @a[score_mod=%d,score_mod_min=%d] %s", - 1, 1, json.toString())); - } catch (IllegalStateException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); - return true; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); - return true; - } - } else - PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, - String.format("tellraw @a %s", json.toString())); - PluginMain.Instance - .getServer() - .getConsoleSender() - .sendMessage( - String.format("[%s] <%s%s> %s", - currentchannel.DisplayName, - (player != null ? player.getDisplayName() - : sender.getName()), - (mp != null ? mp.GetFormattedFlair() : ""), - message)); - return true; - } -} +package io.github.norbipeti.thebuttonmc; + +import io.github.norbipeti.thebuttonmc.commands.UnlolCommand; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.regex.Pattern; + +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Objective; + +import ru.tehkode.permissions.bukkit.PermissionsEx; + +import com.earth2me.essentials.Essentials; +import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; +import com.palmergames.bukkit.towny.object.Nation; +import com.palmergames.bukkit.towny.object.Resident; +import com.palmergames.bukkit.towny.object.Town; + +public class ChatProcessing { + // Returns e.setCancelled + public static boolean ProcessChat(CommandSender sender, String message) { + if (PlayerListener.essentials == null) + PlayerListener.essentials = (Essentials) (Bukkit.getPluginManager() + .getPlugin("Essentials")); + Player player = (sender instanceof Player ? (Player) sender : null); + + if (player != null + && PlayerListener.essentials.getUser(player).isMuted()) + return true; + + MaybeOfflinePlayer mp = null; + if (player != null) { + mp = MaybeOfflinePlayer.AllPlayers.get(player.getUniqueId()); + if (message.equalsIgnoreCase("F")) { + if (!mp.PressedF && PlayerListener.ActiveF) { + PlayerListener.FCount++; + mp.PressedF = true; + if (PlayerListener.FPlayer != null + && PlayerListener.FPlayer.FCount < Integer.MAX_VALUE - 1) + PlayerListener.FPlayer.FCount++; + } + } + } + + String msg = message.toLowerCase(); + if (msg.contains("lol")) { + UnlolCommand.Lastlolornot = true; + UnlolCommand.Lastlol = sender; + } else { + for (int i = 0; i < PlayerListener.LaughStrings.length; i++) { + if (msg.contains(PlayerListener.LaughStrings[i])) { + UnlolCommand.Lastlol = sender; + UnlolCommand.Lastlolornot = false; + } + break; + } + } + Channel currentchannel = (mp == null ? PlayerListener.ConsoleChannel + : mp.CurrentChannel); + + String colormode = currentchannel.Color; + if (mp != null && mp.OtherColorMode.length() > 0) + colormode = mp.OtherColorMode; + if (message.startsWith(">")) + colormode = "green"; // If greentext, ignore channel or player + // colors + + String formattedmessage = message; + formattedmessage = formattedmessage.replace("\\", "\\\\"); // It's + // really + // important + // to escape + // the + // slashes + // first + formattedmessage = formattedmessage.replace("\"", "\\\""); + if (PluginMain.permission.has(sender, "tbmc.admin")) + formattedmessage = formattedmessage.replace("&", "§"); + formattedmessage = formattedmessage.replace("§r", "§" + + currentchannel.DisplayName.charAt(1)); + String suggestmsg = formattedmessage; + boolean cont = true; + while (cont) { + + int first_under = formattedmessage.indexOf("_"); + if (first_under != -1 + && formattedmessage.indexOf("_", first_under + 1) != -1) // underline + { + formattedmessage = formattedmessage.replaceFirst("_", "§n") + .replaceFirst("_", "§r"); + continue; + } + + int first_bold = formattedmessage.indexOf("**"); + if (first_bold != -1 + && formattedmessage.indexOf("**", first_bold + 1) != -1) // bold + { + formattedmessage = formattedmessage + .replaceFirst("\\*\\*", "§l").replaceFirst("\\*\\*", + "§r"); + continue; + } + int first = formattedmessage.indexOf('*'); + if (first != -1 && formattedmessage.indexOf('*', first + 1) != -1) { + formattedmessage = formattedmessage.replaceFirst("\\*", "§o") + .replaceFirst("\\*", "§r"); + continue; + } + cont = false; + } + + // URLs + Rainbow text + String[] parts = formattedmessage.split("\\s+"); + boolean hadurls = false; + final String[] RainbowPresserColors = new String[] { "c", "6", "e", + "a", "9", "5" }; + int rpc = 0; + int currentindex = 0; + for (String item : parts) { + try { + URL url = new URL(item); + formattedmessage = formattedmessage + .replace( + item, + String.format( + "\",\"color\":\"%s\"},{\"text\":\"%s\",\"color\":\"%s\",\"underlined\":\"true\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"%s\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Open URL\",\"color\":\"blue\"}]}}},{\"text\":\"", + colormode, url, colormode, url)); + hadurls = true; + } catch (MalformedURLException e) { + } + if (mp != null && mp.RainbowPresserColorMode) { + if (item.startsWith(RainbowPresserColors[rpc])) { // Prevent + // words + // being + // equal/starting + // with a + // color + // code + // letter to + // be messed + // up + if (rpc + 1 < RainbowPresserColors.length) + rpc++; + else + rpc = 0; + } + StringBuffer buf = new StringBuffer(formattedmessage); + buf.replace(currentindex, currentindex + item.length(), + String.format("§%s%s", RainbowPresserColors[rpc], item)); + formattedmessage = buf.toString(); + if (rpc + 1 < RainbowPresserColors.length) + rpc++; + else + rpc = 0; + } + currentindex += item.length() + 3; + } + + if (!hadurls) { + for (Player p : PluginMain.GetPlayers()) { + String color = ""; + if (formattedmessage.matches("(?i).*" + + Pattern.quote(p.getName()) + ".*")) { + if (PlayerListener.NotificationSound == null) + p.playSound(p.getLocation(), + Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: + // Airhorn + else + p.playSound(p.getLocation(), + PlayerListener.NotificationSound, 1.0f, + (float) PlayerListener.NotificationPitch); + MaybeOfflinePlayer mpp = MaybeOfflinePlayer + .AddPlayerIfNeeded(p.getUniqueId()); + color = String.format( + "§%x", + (mpp.GetFlairColor() == 0x00 ? 0xb : mpp + .GetFlairColor())); + } + + formattedmessage = formattedmessage + .replaceAll( + "(?i)" + Pattern.quote(p.getName()), + String.format( + "\",\"color\":\"%s\"},{\"text\":\"%s%s%s\",\"color\":\"blue\"},{\"text\":\"", + colormode, color, p.getName(), "§r")); + } + for (String n : PlayerListener.nicknames.keySet()) { + Player p = null; + String nwithoutformatting = new String(n); + int index; + while ((index = nwithoutformatting.indexOf("§k")) != -1) + nwithoutformatting = nwithoutformatting.replace("§k" + + nwithoutformatting.charAt(index + 2), ""); // Support + // for + // one + // random + // char + while ((index = nwithoutformatting.indexOf('§')) != -1) + nwithoutformatting = nwithoutformatting.replace("§" + + nwithoutformatting.charAt(index + 1), ""); + if (formattedmessage.matches("(?i).*" + + Pattern.quote(nwithoutformatting) + ".*")) { + p = Bukkit.getPlayer(PlayerListener.nicknames.get(n)); + if (PlayerListener.NotificationSound == null) + p.playSound(p.getLocation(), + Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // 2015.08.12. + else + p.playSound(p.getLocation(), + PlayerListener.NotificationSound, 1.0f, + (float) PlayerListener.NotificationPitch); + MaybeOfflinePlayer.AddPlayerIfNeeded(p.getUniqueId()); + } + if (p != null) { + + formattedmessage = formattedmessage + .replaceAll( + "(?i)" + Pattern.quote(nwithoutformatting), + String.format( + "\",\"color\":\"%s\"},{\"text\":\"%s%s\",\"color\":\"blue\"},{\"text\":\"", + colormode, n, "§r")); + } + } + + if (formattedmessage.matches("(?i).*" + Pattern.quote("@console") + + ".*")) { + formattedmessage = formattedmessage.replaceAll( + "(?i)" + Pattern.quote("@console"), "§b@console§r"); + formattedmessage = formattedmessage + .replaceAll( + "(?i)" + Pattern.quote("@console"), + String.format( + "\",\"color\":\"%s\"},{\"text\":\"§b@console§r\",\"color\":\"blue\"},{\"text\":\"", + colormode)); + System.out.println("\007"); + } + } + + StringBuilder json = new StringBuilder(); + json.append("[\"\","); + json.append(String + .format("%s{\"text\":\"[%s]%s\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"Copy message\",\"color\":\"blue\"}},\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"%s\"}},", + (mp != null && mp.ChatOnly ? "{\"text\":\"[C]\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Chat only\",\"color\":\"blue\"}]}}}," + // (mp != null && mp.ChatOnly ? + // "{\"text:\":\"\"}," - I have been staring at + // this one line for hours... Hours... + : ""), currentchannel.DisplayName, (mp != null + && !mp.RPMode ? "[OOC]" : ""), suggestmsg)); + json.append("{\"text\":\" <\"},"); + json.append(String.format("{\"text\":\"%s%s\",", + (player != null ? player.getDisplayName() : sender.getName()), + (mp != null ? mp.GetFormattedFlair() : ""))); + json.append("\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":["); + json.append(String.format("{\"text\":\"%s\n\",", + (player != null ? player.getName() : sender.getName()))); + json.append(String + .format("\"color\":\"aqua\"},{\"text\":\"World: %s\n\",\"color\":\"white\"},", + (player != null ? player.getWorld().getName() : "-"))); + json.append(String + .format("{\"text\":\"Respect: %s%s%s\",\"color\":\"white\"}]}}},", + (mp != null ? (mp.FCount / (double) mp.FDeaths) + : "Infinite"), + (mp != null && mp.UserName != null + && !mp.UserName.isEmpty() ? "\nUserName: " + + mp.UserName : ""), + (mp != null && mp.PlayerName.equals("\nAlpha_Bacca44") ? "\nDeaths: " + + PlayerListener.AlphaDeaths + : ""))); + json.append("{\"text\":\"> \",\"color\":\"white\"},"); + + int index = -1; + ArrayList list = new ArrayList(); + while ((index = message.indexOf("#", index + 1)) != -1) { + int index2 = message.indexOf(" ", index + 1); + if (index2 == -1) + index2 = message.length(); + int index3 = message.indexOf("#", index + 1); + if (index3 != -1 && index3 < index2) // A # occurs before a + // space + index2 = index3; + String original = message.substring(index + 1, index2); + list.add(original); + } + + if (!hadurls) { + for (String original : list) + // Hashtags + formattedmessage = formattedmessage + .replace( + "#" + original, + String.format( + "\",\"color\":\"%s\"},{\"text\":\"#%s\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://twitter.com/hashtag/%s\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Open on Twitter\",\"color\":\"blue\"}]}}},{\"text\":\"", + colormode, original, original)); + } + + json.append(String.format("{\"text\":\"%s\",\"color\":\"%s\"}]", + formattedmessage, colormode)); + String jsonstr = json.toString(); + if (jsonstr.length() >= 32767) { + sender.sendMessage("§cError: Message too large. Try shortening it, or remove hashtags and other formatting."); + return true; + } + if (currentchannel.equals(Channel.TownChat) + || currentchannel.equals(Channel.NationChat)) { + if (player == null) { + sender.sendMessage("§cYou are not a player!"); + return true; + } + for (Player p : PluginMain.GetPlayers()) { + try { + Resident resident = PluginMain.Instance.TU.getResidentMap() + .get(p.getName().toLowerCase()); + if (!resident.getName().equals(player.getName()) + && resident.getModes().contains("spy")) + Bukkit.getPlayer(resident.getName()).sendMessage( + String.format("[SPY-%s] - %s: %s", + currentchannel.DisplayName, + player.getDisplayName(), message)); + } catch (Exception e) { + } + } + } + if (currentchannel.equals(Channel.TownChat)) { + try { + Town town = null; + try { + town = PluginMain.Instance.TU.getResidentMap() + .get(player.getName().toLowerCase()).getTown(); + } catch (NotRegisteredException e) { + } + if (town == null) { + player.sendMessage("§cYou aren't in a town or an error occured."); + return true; + } + index = PluginMain.Instance.Towns.indexOf(town); + if (index < 0) { + PluginMain.Instance.Towns.add(town); + index = PluginMain.Instance.Towns.size() - 1; + } + Objective obj = PluginMain.SB.getObjective("town"); + for (Player p : PluginMain.GetPlayers()) { + try { + if (PluginMain.Instance.TU.getResidentMap() + .get(p.getName().toLowerCase()).getTown() + .getName().equals(town.getName())) + obj.getScore(p.getName()).setScore(index); + else + obj.getScore(p.getName()).setScore(-1); + } catch (Exception e) { + obj.getScore(p.getName()).setScore(-1); + } + } + PluginMain.Instance + .getServer() + .dispatchCommand( + PluginMain.Console, + String.format( + "tellraw @a[score_town=%d,score_town_min=%d] %s", + index, index, json.toString())); + } catch (IllegalStateException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); + return true; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); + return true; + } + } else if (currentchannel.equals(Channel.NationChat)) { + try { + Town town = null; + try { + town = PluginMain.Instance.TU.getResidentMap() + .get(player.getName().toLowerCase()).getTown(); + } catch (NotRegisteredException e) { + } + if (town == null) { + player.sendMessage("§cYou aren't in a town or an error occured."); + return true; + } + Nation nation = null; + try { + nation = town.getNation(); + } catch (NotRegisteredException e) { + } + if (nation == null) { + player.sendMessage("§cYour town isn't in a nation or an error occured."); + return true; + } + index = PluginMain.Instance.Nations.indexOf(nation); + if (index < 0) { + PluginMain.Instance.Nations.add(nation); + index = PluginMain.Instance.Nations.size() - 1; + } + Objective obj = PluginMain.SB.getObjective("nation"); + for (Player p : PluginMain.GetPlayers()) { + try { + if (PluginMain.Instance.TU.getResidentMap() + .get(p.getName().toLowerCase()).getTown() + .getNation().getName().equals(nation.getName())) + obj.getScore(p.getName()).setScore(index); + else + obj.getScore(p.getName()).setScore(-1); + } catch (Exception e) { + } + } + PluginMain.Instance + .getServer() + .dispatchCommand( + PluginMain.Console, + String.format( + "tellraw @a[score_nation=%d,score_nation_min=%d] %s", + index, index, json.toString())); + } catch (IllegalStateException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); + return true; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); + return true; + } + } else if (currentchannel.equals(Channel.AdminChat)) { + try { // TODO: Put message JSON into it's structure + if (player != null && !player.isOp()) { + player.sendMessage("§cYou need to be an OP to use this channel."); + return true; + } + Objective obj = PluginMain.SB.getObjective("admin"); + for (Player p : PluginMain.GetPlayers()) { + if (p.isOp()) + obj.getScore(p.getName()).setScore(1); + else + obj.getScore(p.getName()).setScore(0); + } + PluginMain.Instance + .getServer() + .dispatchCommand( + PluginMain.Console, + String.format( + "tellraw @a[score_admin=%d,score_admin_min=%d] %s", + 1, 1, json.toString())); + } catch (IllegalStateException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); + return true; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); + return true; + } + } else if (currentchannel.equals(Channel.ModChat)) { + try { + if (player != null + && !PermissionsEx.getUser(player).inGroup("mod")) { + player.sendMessage("§cYou need to be a mod to use this channel."); + return true; + } + Objective obj = PluginMain.SB.getObjective("mod"); + for (Player p : PluginMain.GetPlayers()) { + if (PermissionsEx.getUser(p).inGroup("mod")) + obj.getScore(p.getName()).setScore(1); + else + obj.getScore(p.getName()).setScore(0); + } + PluginMain.Instance.getServer().dispatchCommand( + PluginMain.Console, + String.format( + "tellraw @a[score_mod=%d,score_mod_min=%d] %s", + 1, 1, json.toString())); + } catch (IllegalStateException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalStateException)"); + return true; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + player.sendMessage("§cAn error occured while sending the message. (IllegalArgumentException)"); + return true; + } + } else + PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, + String.format("tellraw @a %s", json.toString())); + PluginMain.Instance + .getServer() + .getConsoleSender() + .sendMessage( + String.format("[%s] <%s%s> %s", + currentchannel.DisplayName, + (player != null ? player.getDisplayName() + : sender.getName()), + (mp != null ? mp.GetFormattedFlair() : ""), + message)); + return true; + } +} diff --git a/src/io/github/norbipeti/thebuttonmc/Commands.java b/src/io/github/norbipeti/thebuttonmc/Commands.java index db7f7f0..3c6d857 100644 --- a/src/io/github/norbipeti/thebuttonmc/Commands.java +++ b/src/io/github/norbipeti/thebuttonmc/Commands.java @@ -1,773 +1,412 @@ -package io.github.norbipeti.thebuttonmc; - -import org.apache.commons.io.FileUtils; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.command.BlockCommandSender; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Ocelot; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import com.earth2me.essentials.Mob; -import com.earth2me.essentials.Mob.MobException; - -import au.com.mineauz.minigames.MinigamePlayer; -import au.com.mineauz.minigames.Minigames; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Random; -import java.util.Timer; - -public class Commands implements CommandExecutor { - - public static Player Lastlol = null; - public static boolean Lastlolornot; - public static boolean Lastlolconsole; - - // This method is called, when somebody uses our command - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, - String[] args) { - if (sender instanceof Player) { - final Player player = (Player) sender; - switch (cmd.getName()) { - case "u": { - if (args.length < 1) - return false; - MaybeOfflinePlayer p = MaybeOfflinePlayer.AllPlayers.get(player - .getUniqueId()); - switch (args[0].toLowerCase()) { - case "accept": { - if (args.length < 2 && p.UserNames.size() > 1) { - player.sendMessage("§9Multiple users commented your name. §bPlease pick one using /u accept "); - StringBuilder sb = new StringBuilder(); - sb.append("§6Usernames:"); - for (String username : p.UserNames) - sb.append(" ").append(username); - player.sendMessage(sb.toString()); - return true; - } - if (p.FlairState.equals(FlairStates.NoComment) - || p.UserNames.size() == 0) { - player.sendMessage("§cError: You need to write your username to the reddit thread at /r/TheButtonMinecraft§r"); - return true; - } - if (args.length > 1 && !p.UserNames.contains(args[1])) { - player.sendMessage("§cError: Unknown name: " + args[1] - + "§r"); - return true; - } - if (p.Working) { - player.sendMessage("§cError: Something is already in progress.§r"); - return true; - } - - if ((args.length > 1 ? args[1] : p.UserNames.get(0)) - .equals(p.UserName)) { - player.sendMessage("§cYou already have this user's flair.§r"); - return true; - } - if (args.length > 1) - p.UserName = args[1]; - else - p.UserName = p.UserNames.get(0); - - player.sendMessage("§bObtaining flair..."); - p.Working = true; - Timer timer = new Timer(); - PlayerJoinTimerTask tt = new PlayerJoinTimerTask() { - @Override - public void run() { - try { - PluginMain.Instance.DownloadFlair(mp); - } catch (Exception e) { - e.printStackTrace(); - player.sendMessage("Sorry, but an error occured while trying to get your flair. Please contact a mod."); - mp.Working = false; - return; - } - - if (mp.FlairState.equals(FlairStates.Commented)) { - player.sendMessage("Sorry, but your flair isn't recorded. Please ask an admin to set it for you. Also, prepare a comment on /r/thebutton, if possible."); - mp.Working = false; - return; - } - String flair = mp.GetFormattedFlair(); - mp.FlairState = FlairStates.Accepted; - PluginMain.ConfirmUserMessage(mp); - player.sendMessage("§bYour flair has been set:§r " - + flair); - mp.Working = false; - } - }; - tt.mp = p; - timer.schedule(tt, 20); - break; - } - case "ignore": { - if (p.FlairState.equals(FlairStates.Accepted)) { - player.sendMessage("§cSorry, but ignoring the flair is no longer possible. As with the original Button, you can't undo what already happened."); - return true; - } - if (p.FlairState.equals(FlairStates.Commented)) { - player.sendMessage("Sorry, but your flair isn't recorded. Please ask a mod to set it for you."); - return true; - } - if (!p.FlairState.equals(FlairStates.Ignored)) { - p.FlairState = FlairStates.Ignored; - p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); - p.UserName = ""; - player.sendMessage("§bYou have removed your flair. You can still use /u accept to get one.§r"); - } else - player.sendMessage("§cYou already removed your flair.§r"); - break; - } - case "admin": // 2015.08.09. - DoAdmin(player, args); - break; - case "opme": // 2015.08.10. - player.sendMessage("It would be nice, wouldn't it?"); // Sometimes - // I'm - // bored - // too - break; - case "announce": - DoAnnounce(player, args, null); - break; - case "name": { - if (args.length == 1) { - player.sendMessage("§cUsage: /u name §r"); - break; - } - MaybeOfflinePlayer mp = MaybeOfflinePlayer - .GetFromName(args[1]); - if (mp == null) { - player.sendMessage("§cUnknown user (player has to be online): " - + args[1]); - break; - } - player.sendMessage("§bUsername of " + args[1] + ": " - + mp.UserName); - break; - } - case "enable": - if (player.getName().equals("NorbiPeti")) { - PlayerListener.Enable = true; - player.sendMessage("Enabled."); - } else - player.sendMessage("Unknown command: " + cmd.getName()); - break; - case "disable": - if (player.getName().equals("NorbiPeti")) { - PlayerListener.Enable = false; - player.sendMessage("Disabled."); - } else - player.sendMessage("Unknown command: " + cmd.getName()); - break; - case "kittycannon": - DoKittyCannon(player, args); - break; - case "c": - if (args.length < 2) { - if (PluginMain.permission.has(player, "tbmc.rainbow")) { - p.RainbowPresserColorMode = !p.RainbowPresserColorMode; - p.OtherColorMode = ""; - if (p.RainbowPresserColorMode) - player.sendMessage("§eRainbow colors §aenabled."); - else - player.sendMessage("§eRainbow colors §cdisabled."); - } else { - player.sendMessage("§cYou don't have permission for this command. Donate to get it!"); - return true; - } - } else { - if (PluginMain.permission.has(player, "tbmc.admin")) { - p.RainbowPresserColorMode = false; - p.OtherColorMode = args[1]; - if (p.OtherColorMode.length() > 0) - player.sendMessage(String.format( - "§eMessage color set to %s", - p.OtherColorMode)); - else - player.sendMessage("§eMessage color reset."); - } else { - player.sendMessage("§cYou don't have permission for this command."); - return true; - } - } - break; - default: - return false; - } - return true; - } - case "nrp": - case "ooc": { - if (args.length == 0) { - return false; - } else { - MaybeOfflinePlayer.AddPlayerIfNeeded(player.getUniqueId()).RPMode = false; - String message = ""; - for (String arg : args) - message += arg + " "; - player.chat(message.substring(0, message.length() - 1)); - MaybeOfflinePlayer.AddPlayerIfNeeded(player.getUniqueId()).RPMode = true; - } - return true; - } - case "unlaugh": - case "unlol": { - if (Lastlol != null) { - Lastlol.addPotionEffect(new PotionEffect( - PotionEffectType.BLINDNESS, 10 * 20, 5, false, - false)); - for (Player pl : PluginMain.GetPlayers()) - pl.sendMessage(player.getDisplayName() - + (Lastlolornot ? " unlolled " : " unlaughed ") - + Lastlol.getDisplayName()); - Bukkit.getServer() - .getConsoleSender() - .sendMessage( - player.getDisplayName() - + (Lastlolornot ? " unlolled " - : " unlaughed ") - + Lastlol.getDisplayName()); - Lastlol = null; - } else if (Lastlolconsole) { - for (Player pl : PluginMain.GetPlayers()) - pl.sendMessage(player.getDisplayName() - + (Lastlolornot ? " unlolled " : " unlaughed ") - + Bukkit.getServer().getConsoleSender() - .getName()); - Bukkit.getServer() - .getConsoleSender() - .sendMessage( - player.getDisplayName() - + (Lastlolornot ? " unlolled " - : " unlaughed ") - + Bukkit.getServer() - .getConsoleSender() - .getName()); - } - return true; - } - case "yeehaw": { - for (Player p : PluginMain.GetPlayers()) { - p.playSound(p.getLocation(), "tbmc.yeehaw", 1f, 1f); - p.sendMessage("§b* " + p.getDisplayName() + " YEEHAWs."); - } - return true; - } - case "mwiki": { - DoMWiki(player, args); - return true; - } - case "tableflip": { - String msg = " (╯°□°)╯︵ ┻━┻"; - if (args.length > 0) { - msg = args[0] + " " + msg; - } - player.chat(msg); - return true; - } - case "unflip": { - String msg = " ┬─┬ ノ( ゜-゜ノ)"; - if (args.length > 0) { - msg = args[0] + "" + msg; - } - player.chat(msg); - return true; - } - case "shrug": { - String msg = " ¯\\_(ツ)_/¯"; - if (args.length > 0) { - msg = args[0] + "" + msg; - } - player.chat(msg); - return true; - } - case "chatonly": { - MaybeOfflinePlayer p = MaybeOfflinePlayer.AllPlayers.get(player - .getUniqueId()); - p.ChatOnly = true; - player.setGameMode(GameMode.SPECTATOR); - player.sendMessage("§bChat-only mode enabled. You are now invincible."); - return true; - } - default: - player.sendMessage("Unknown command: " + cmd.getName()); - break; - } - } else if (args.length > 0 && args[0].toLowerCase().equals("admin")) // 2015.08.09. - { - DoAdmin(null, args); // 2015.08.09. - return true; // 2015.08.09. - } else if (args.length > 0 && args[0].toLowerCase().equals("announce")) { - if (sender instanceof BlockCommandSender) - DoAnnounce(null, args, (BlockCommandSender) sender); - else - DoAnnounce(null, args, null); - return true; - } else { - switch (cmd.getName()) { - case "unlaugh": - case "unlol": { - if (Lastlol != null) { - Lastlol.addPotionEffect(new PotionEffect( - PotionEffectType.BLINDNESS, 10 * 20, 5, false, - false)); - for (Player pl : PluginMain.GetPlayers()) - pl.sendMessage(Bukkit.getServer().getConsoleSender() - .getName() - + (Lastlolornot ? " unlolled " : " unlaughed ") - + Lastlol.getDisplayName()); - Bukkit.getServer() - .getConsoleSender() - .sendMessage( - Bukkit.getServer().getConsoleSender() - .getName() - + (Lastlolornot ? " unlolled " - : " unlaughed ") - + Lastlol.getDisplayName()); - Lastlol = null; - } - return true; - } - } - } - return false; - } - - private static void DoReload(Player player) { - try { - PluginMain.Console - .sendMessage("§6-- Reloading The Button Minecraft plugin...§r"); - PluginMain.LoadFiles(true); // 2015.08.09. - for (Player p : PluginMain.GetPlayers()) { - MaybeOfflinePlayer mp = MaybeOfflinePlayer.AddPlayerIfNeeded(p - .getUniqueId()); - if (mp.FlairState.equals(FlairStates.Recognised) - || mp.FlairState.equals(FlairStates.Commented)) { - PluginMain.ConfirmUserMessage(mp); - } - String msg = "§bNote: The auto-flair plugin has been reloaded. You might need to wait 10s to have your flair.§r"; // 2015.08.09. - p.sendMessage(msg); // 2015.08.09. - } - PluginMain.Console.sendMessage("§6-- Reloading done!§r"); - } catch (Exception e) { - System.out.println("Error!\n" + e); - if (player != null) - player.sendMessage("§cAn error occured. See console for details.§r"); - PluginMain.LastException = e; // 2015.08.09. - } - } - - private static Player ReloadPlayer; // 2015.08.09. - - private static String DoAdminUsage = "§cUsage: /u admin reload|playerinfo|getlasterror|save|setflair|updateplugin|togglerpshow|toggledebug|savepos|loadpos§r"; - - private static void DoAdmin(Player player, String[] args) { - if (player == null || PluginMain.permission.has(player, "tbmc.admin")) { - if (args.length == 1) { - String message = DoAdminUsage; - SendMessage(player, message); - return; - } - // args[0] is "admin" - switch (args[1].toLowerCase()) { - case "reload": - ReloadPlayer = player; // 2015.08.09. - SendMessage( - player, - "§bMake sure to save the current settings before you modify and reload them! Type /u admin confirm when done.§r"); - break; - case "playerinfo": - DoPlayerInfo(player, args); - break; - case "getlasterror": - DoGetLastError(player, args); - break; // <-- 2015.08.10. - case "confirm": - if (ReloadPlayer == player) - DoReload(player); // 2015.08.09. - else - SendMessage(player, - "§cYou need to do /u admin reload first.§r"); - break; - case "save": - PluginMain.SaveFiles(); // 2015.08.09. - SendMessage(player, - "§bSaved files. Now you can edit them and reload if you want.§r"); - break; - case "setflair": - DoSetFlair(player, args); - break; - case "updateplugin": // 2015.08.10. - DoUpdatePlugin(player); - break; - case "togglerpshow": - PlayerListener.ShowRPTag = !PlayerListener.ShowRPTag; - SendMessage(player, "RP tag showing " - + (PlayerListener.ShowRPTag ? "enabled" : "disabled")); - break; - case "toggledebug": - PlayerListener.DebugMode = !PlayerListener.DebugMode; - SendMessage(player, "DebugMode: " + PlayerListener.DebugMode); - break; - case "savepos": - DoSaveLoadPos(player, args); - break; - case "loadpos": - DoSaveLoadPos(player, args); - break; - case "updatedynmap": - DoUpdateDynmap(player, args); - default: - String message = DoAdminUsage; - SendMessage(player, message); - return; - } - } else - player.sendMessage("§cYou don't have permission to use this command.§r"); - } - - private static void DoPlayerInfo(Player player, String[] args) { // 2015.08.09. - // args[0] is "admin" - args[1] is "playerinfo" - if (args.length == 2) { - String message = "§cUsage: /u admin playerinfo §r"; - SendMessage(player, message); - return; - } - MaybeOfflinePlayer p = MaybeOfflinePlayer.GetFromName(args[2]); - if (p == null) { - String message = "§cPlayer not found: " + args[2] - + " - Currently only online players can be viewed§r"; - SendMessage(player, message); - return; - } - SendMessage(player, "Player name: " + p.PlayerName); - SendMessage(player, "User flair: " + p.GetFormattedFlair()); - SendMessage(player, "Username: " + p.UserName); - SendMessage(player, "Flair state: " + p.FlairState); - StringBuilder sb = new StringBuilder(); - sb.append("§6Usernames:"); - for (String username : p.UserNames) - sb.append(" ").append(username); - SendMessage(player, sb.toString()); - } - - private static void SendMessage(Player player, String message) { // 2015.08.09. - if (player == null) - PluginMain.Console.sendMessage(message); // 2015.08.12. - else - player.sendMessage(message); - } - - private static void DoGetLastError(Player player, String[] args) { // 2015.08.09. - // args[0] is "admin" - args[1] is "getlasterror" - if (PluginMain.LastException != null) { - SendMessage(player, "Last error:"); - SendMessage(player, PluginMain.LastException.toString()); - PluginMain.LastException = null; - } else - SendMessage(player, "There were no exceptions."); - } - - private static void SetPlayerFlair(Player player, - MaybeOfflinePlayer targetplayer, short flairtime, boolean cheater, - String username) { - targetplayer.SetFlair(flairtime, cheater); - targetplayer.FlairState = FlairStates.Accepted; - if (username == null) - targetplayer.UserName = ""; - else { - targetplayer.UserName = username; - if (!targetplayer.UserNames.contains(username)) - targetplayer.UserNames.add(username); - } - SendMessage(player, - "§bThe flair has been set. Player: " + targetplayer.PlayerName - + " Flair: " + targetplayer.GetFormattedFlair() + "§r"); - } - - // TODO: Put commands into separate classes - private static void DoSetFlair(Player player, String[] args) { - // args[0] is "admin" - args[1] is "setflair" - if (args.length < 5) { - SendMessage( - player, - "§cUsage: /u admin setflair [username]"); - return; - } - Player p = Bukkit.getPlayer(args[2]); - if (p == null) { - SendMessage(player, "§cPlayer not found.&r"); - return; - } - short flairtime = 0x00; - if (args[3].equalsIgnoreCase("non-presser")) - flairtime = MaybeOfflinePlayer.FlairTimeNonPresser; - else if (args[3].equalsIgnoreCase("cant-press")) - flairtime = MaybeOfflinePlayer.FlairTimeCantPress; - else if (args[3].equalsIgnoreCase("none")) - flairtime = MaybeOfflinePlayer.FlairTimeNone; - else { - try { - flairtime = Short.parseShort(args[3]); - } catch (Exception e) { - SendMessage(player, - "§cFlairtime must be a number, \"non-presser\", \"cant-press\" or \"none\"."); - return; - } - } // TODO: Split config to per-player - boolean cheater = false; - if (args[4].equalsIgnoreCase("true")) - cheater = true; - else if (args[4].equalsIgnoreCase("false")) - cheater = false; - else { - SendMessage(player, "§cUnknown value for cheater parameter."); - return; - } - SetPlayerFlair(player, - MaybeOfflinePlayer.AddPlayerIfNeeded(p.getUniqueId()), - flairtime, cheater, (args.length > 5 ? args[5] : null)); - } - - private static void DoUpdatePlugin(Player player) { // 2015.08.10. - SendMessage(player, "Updating Auto-Flair plugin..."); - System.out.println("Forced updating of Auto-Flair plugin."); - URL url; - try { - url = new URL( - "https://github.com/NorbiPeti/thebuttonautoflairmc/raw/master/TheButtonAutoFlair.jar"); - FileUtils.copyURLToFile(url, new File( - "plugins/TheButtonAutoFlair.jar")); - SendMessage(player, "Updating done!"); - } catch (MalformedURLException e) { - System.out.println("Error!\n" + e); - PluginMain.LastException = e; // 2015.08.09. - } catch (IOException e) { - System.out.println("Error!\n" + e); - PluginMain.LastException = e; // 2015.08.09. - } - } - - private static void DoAnnounce(Player player, String[] args, - BlockCommandSender commandblock) { - if (player == null || player.isOp() - || player.getName().equals("NorbiPeti")) { - if (args.length == 1) { - String message = "§cUsage: /u announce add|remove|settime|list|edit§r"; - SendMessage(player, message); - return; - } - switch (args[1].toLowerCase()) { - case "add": - if (args.length < 3) { - SendMessage(player, "§cUsage: /u announce add "); - return; - } - StringBuilder sb = new StringBuilder(); - for (int i = 2; i < args.length; i++) { - sb.append(args[i]); - if (i != args.length - 1) - sb.append(" "); - } - String finalmessage = sb.toString().replace('&', '§'); - PluginMain.AnnounceMessages.add(finalmessage); - SendMessage(player, "§bAnnouncement added.§r"); - break; - case "remove": - if (args.length < 3) { - SendMessage(player, "§cUsage: /u announce remove "); - return; - } - PluginMain.AnnounceMessages.remove(Integer.parseInt(args[2])); - break; - case "settime": - if (args.length < 3) { - SendMessage(player, - "§cUsage: /u announce settime "); - return; - } - PluginMain.AnnounceTime = Integer.parseInt(args[2]) * 60 * 1000; - SendMessage(player, "Time set between announce messages"); - break; - case "list": - SendMessage(player, "§bList of announce messages:§r"); - SendMessage(player, "§bFormat: [index] message§r"); - int i = 0; - for (String message : PluginMain.AnnounceMessages) - SendMessage(player, "[" + i++ + "] " + message); - SendMessage(player, - "§bCurrent wait time between announcements: " - + PluginMain.AnnounceTime / 60 / 1000 - + " minute(s)§r"); - break; - case "edit": - if (commandblock == null) { - SendMessage( - player, - "§cError: This command can only be used from a command block. Use /u announce remove."); - break; - } - if (args.length < 4) { - commandblock - .sendMessage("§cUsage: /u announce edit "); - return; - } - StringBuilder sb1 = new StringBuilder(); - for (int i1 = 3; i1 < args.length; i1++) { - sb1.append(args[i1]); - if (i1 != args.length - 1) - sb1.append(" "); - } - String finalmessage1 = sb1.toString().replace('&', '§'); - int index = Integer.parseInt(args[2]); - if (index > 100) - break; - while (PluginMain.AnnounceMessages.size() <= index) - PluginMain.AnnounceMessages.add(""); - PluginMain.AnnounceMessages.set(Integer.parseInt(args[2]), - finalmessage1); - commandblock.sendMessage("Announcement edited."); - break; - default: - String message = "§cUsage: /u announce add|remove|settime|list|edit§r"; - SendMessage(player, message); - return; - } - } - } - - @SuppressWarnings("unused") - private static void DoSaveLoadPos(Player player, String[] args) { // 2015.08.09. - // args[0] is "admin" - args[1] is "savepos|loadpos" - if (args.length == 2) { - String message = "§cUsage: /u admin savepos|loadpos §r"; - SendMessage(player, message); - return; - } - Player p = null; - try { - p = Bukkit.getPlayer(args[2]); - } catch (Exception e) { - } - if (!MaybeOfflinePlayer.AllPlayers.containsKey(p.getUniqueId())) { - String message = "§cPlayer not found: " + args[2] + "§r"; - SendMessage(player, message); - return; - } - MaybeOfflinePlayer mp = MaybeOfflinePlayer.AllPlayers.get(p - .getUniqueId()); - if (p == null) { - String message = "§cPlayer is not online: " + args[2] + "§r"; - SendMessage(player, message); - return; - } - if (args[1].equalsIgnoreCase("savepos")) { - mp.SavedLocation = p.getLocation(); - } else if (args[1].equalsIgnoreCase("loadpos")) { - if (mp.SavedLocation != null) - p.teleport(mp.SavedLocation); - } else { - String message = "§cUsage: /u admin savepos|loadpos §r"; - SendMessage(player, message); - return; - } - // SendMessage(player, "Player " + p.getName() + - // " position saved/loaded.");s - } - - private static void DoUpdateDynmap(Player player, String[] args) { - // args[0] is "admin" - args[1] is "updatedynmap" - if (args.length == 2) { - String message = "§cUsage: /u admin updatedynmap §r"; - SendMessage(player, message); - return; - } - } - - private static Random random = new Random(); - - public static String KittyCannonMinigame = "KittyCannon"; - - private static void DoKittyCannon(Player player, String[] args) { - if (player == null) { - SendMessage(player, - "§cThis command can only be used by a player.§r"); - return; - } - MinigamePlayer mp = Minigames.plugin.pdata.getMinigamePlayer(player); - if (!(mp.isInMinigame() && mp.getMinigame().getName(false) - .equalsIgnoreCase(Commands.KittyCannonMinigame))) { - SendMessage(player, - "§cYou can only use KittyCannon in it's minigame!"); - return; - } - try { - final Mob cat = Mob.OCELOT; - final Ocelot ocelot = (Ocelot) cat.spawn(player.getWorld(), - player.getServer(), player.getEyeLocation()); - if (ocelot == null) { - return; - } - final ArrayList lore = new ArrayList<>(); - lore.add(player.getName()); - final int i = random.nextInt(Ocelot.Type.values().length); - ocelot.setCatType(Ocelot.Type.values()[i]); - ocelot.setTamed(true); - ocelot.setBaby(); - ocelot.addPotionEffect(new PotionEffect( - PotionEffectType.DAMAGE_RESISTANCE, 5, 5)); - ocelot.setVelocity(player.getEyeLocation().getDirection() - .multiply(2)); - Bukkit.getScheduler().scheduleSyncDelayedTask(PluginMain.Instance, - new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { - final Location loc = ocelot.getLocation(); - ocelot.remove(); - loc.getWorld().createExplosion(loc, 0F); - final ItemStack head = new ItemStack( - Material.SKULL_ITEM, 1, (short) 3, (byte) 3); - SkullMeta im = (SkullMeta) head.getItemMeta(); - im.setDisplayName("§rOcelot Head"); - im.setOwner("MHF_Ocelot"); - im.setLore(lore); - head.setItemMeta(im); - loc.getWorld().dropItem(loc, head); - } - }, 20); - } catch (MobException e) { - } - } - - private static void DoMWiki(Player player, String[] args) { - String query = ""; - for (int i = 0; i < args.length; i++) - query += args[i]; - query = query.trim(); - if (args.length == 0) - SendMessage(player, - "§bMinecraft Wiki link: http://minecraft.gamepedia.com/"); - else - SendMessage(player, - "§bMinecraft Wiki link: http://minecraft.gamepedia.com/index.php?search=" - + query + "&title=Special%3ASearch&go=Go"); - } -} +package io.github.norbipeti.thebuttonmc; + +import org.apache.commons.io.FileUtils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Ocelot; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import com.earth2me.essentials.Mob; +import com.earth2me.essentials.Mob.MobException; + +import au.com.mineauz.minigames.MinigamePlayer; +import au.com.mineauz.minigames.Minigames; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Random; +import java.util.Timer; + +public class Commands implements CommandExecutor { + + // This method is called, when somebody uses our command + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, + String[] args) { + if (sender instanceof Player) { + final Player player = (Player) sender; + switch (cmd.getName()) { + case "u": { + if (args.length < 1) + return false; + MaybeOfflinePlayer p = MaybeOfflinePlayer.AllPlayers.get(player + .getUniqueId()); + switch (args[0].toLowerCase()) { + case "admin": // 2015.08.09. + DoAdmin(player, args); + break; + case "opme": // 2015.08.10. + player.sendMessage("It would be nice, wouldn't it?"); // Sometimes + // I'm + // bored + // too + break; + case "announce": + DoAnnounce(player, args, null); + break; + case "name": { + if (args.length == 1) { + player.sendMessage("§cUsage: /u name §r"); + break; + } + MaybeOfflinePlayer mp = MaybeOfflinePlayer + .GetFromName(args[1]); + if (mp == null) { + player.sendMessage("§cUnknown user (player has to be online): " + + args[1]); + break; + } + player.sendMessage("§bUsername of " + args[1] + ": " + + mp.UserName); + break; + } + case "enable": + if (player.getName().equals("NorbiPeti")) { + PlayerListener.Enable = true; + player.sendMessage("Enabled."); + } else + player.sendMessage("Unknown command: " + cmd.getName()); + break; + case "disable": + if (player.getName().equals("NorbiPeti")) { + PlayerListener.Enable = false; + player.sendMessage("Disabled."); + } else + player.sendMessage("Unknown command: " + cmd.getName()); + break; + case "kittycannon": + DoKittyCannon(player, args); + break; + case "c": + if (args.length < 2) { + if (PluginMain.permission.has(player, "tbmc.rainbow")) { + p.RainbowPresserColorMode = !p.RainbowPresserColorMode; + p.OtherColorMode = ""; + if (p.RainbowPresserColorMode) + player.sendMessage("§eRainbow colors §aenabled."); + else + player.sendMessage("§eRainbow colors §cdisabled."); + } else { + player.sendMessage("§cYou don't have permission for this command. Donate to get it!"); + return true; + } + } else { + if (PluginMain.permission.has(player, "tbmc.admin")) { + p.RainbowPresserColorMode = false; + p.OtherColorMode = args[1]; + if (p.OtherColorMode.length() > 0) + player.sendMessage(String.format( + "§eMessage color set to %s", + p.OtherColorMode)); + else + player.sendMessage("§eMessage color reset."); + } else { + player.sendMessage("§cYou don't have permission for this command."); + return true; + } + } + break; + default: + return false; + } + return true; + } + case "nrp": + case "ooc": { + if (args.length == 0) { + return false; + } else { + MaybeOfflinePlayer.AddPlayerIfNeeded(player.getUniqueId()).RPMode = false; + String message = ""; + for (String arg : args) + message += arg + " "; + player.chat(message.substring(0, message.length() - 1)); + MaybeOfflinePlayer.AddPlayerIfNeeded(player.getUniqueId()).RPMode = true; + } + return true; + } + case "unlaugh": + case "unlol": { //TODO + return true; + } + case "yeehaw": { + for (Player p : PluginMain.GetPlayers()) { + p.playSound(p.getLocation(), "tbmc.yeehaw", 1f, 1f); + p.sendMessage("§b* " + p.getDisplayName() + " YEEHAWs."); + } + return true; + } + case "mwiki": { + DoMWiki(player, args); + return true; + } + case "tableflip": { + String msg = " (╯°□°)╯︵ ┻━┻"; + if (args.length > 0) { + msg = args[0] + " " + msg; + } + player.chat(msg); + return true; + } + case "unflip": { + String msg = " ┬─┬ ノ( ゜-゜ノ)"; + if (args.length > 0) { + msg = args[0] + "" + msg; + } + player.chat(msg); + return true; + } + case "shrug": { + String msg = " ¯\\_(ツ)_/¯"; + if (args.length > 0) { + msg = args[0] + "" + msg; + } + player.chat(msg); + return true; + } + case "chatonly": { + MaybeOfflinePlayer p = MaybeOfflinePlayer.AllPlayers.get(player + .getUniqueId()); + p.ChatOnly = true; + player.setGameMode(GameMode.SPECTATOR); + player.sendMessage("§bChat-only mode enabled. You are now invincible."); + return true; + } + default: + player.sendMessage("Unknown command: " + cmd.getName()); + break; + } + } else if (args.length > 0 && args[0].toLowerCase().equals("admin")) // 2015.08.09. + { + DoAdmin(null, args); // 2015.08.09. + return true; // 2015.08.09. + } else if (args.length > 0 && args[0].toLowerCase().equals("announce")) { + if (sender instanceof BlockCommandSender) + DoAnnounce(null, args, (BlockCommandSender) sender); + else + DoAnnounce(null, args, null); + return true; + } else { + switch (cmd.getName()) { + return true; + } + } + return false; + } + + private static String DoAdminUsage = "§cUsage: /u admin reload|playerinfo|getlasterror|save|setflair|updateplugin|togglerpshow|toggledebug|savepos|loadpos§r"; + + private static void DoAnnounce(Player player, String[] args, + BlockCommandSender commandblock) { + if (player == null || player.isOp() + || player.getName().equals("NorbiPeti")) { + switch (args[1].toLowerCase()) { + case "add": + if (args.length < 3) { + SendMessage(player, "§cUsage: /u announce add "); + return; + } + StringBuilder sb = new StringBuilder(); + for (int i = 2; i < args.length; i++) { + sb.append(args[i]); + if (i != args.length - 1) + sb.append(" "); + } + String finalmessage = sb.toString().replace('&', '§'); + PluginMain.AnnounceMessages.add(finalmessage); + SendMessage(player, "§bAnnouncement added.§r"); + break; + case "remove": + if (args.length < 3) { + SendMessage(player, "§cUsage: /u announce remove "); + return; + } + PluginMain.AnnounceMessages.remove(Integer.parseInt(args[2])); + break; + case "settime": + if (args.length < 3) { + SendMessage(player, + "§cUsage: /u announce settime "); + return; + } + PluginMain.AnnounceTime = Integer.parseInt(args[2]) * 60 * 1000; + SendMessage(player, "Time set between announce messages"); + break; + case "list": + SendMessage(player, "§bList of announce messages:§r"); + SendMessage(player, "§bFormat: [index] message§r"); + int i = 0; + for (String message : PluginMain.AnnounceMessages) + SendMessage(player, "[" + i++ + "] " + message); + SendMessage(player, + "§bCurrent wait time between announcements: " + + PluginMain.AnnounceTime / 60 / 1000 + + " minute(s)§r"); + break; + case "edit": + if (commandblock == null) { + SendMessage( + player, + "§cError: This command can only be used from a command block. Use /u announce remove."); + break; + } + if (args.length < 4) { + commandblock + .sendMessage("§cUsage: /u announce edit "); + return; + } + StringBuilder sb1 = new StringBuilder(); + for (int i1 = 3; i1 < args.length; i1++) { + sb1.append(args[i1]); + if (i1 != args.length - 1) + sb1.append(" "); + } + String finalmessage1 = sb1.toString().replace('&', '§'); + int index = Integer.parseInt(args[2]); + if (index > 100) + break; + while (PluginMain.AnnounceMessages.size() <= index) + PluginMain.AnnounceMessages.add(""); + PluginMain.AnnounceMessages.set(Integer.parseInt(args[2]), + finalmessage1); + commandblock.sendMessage("Announcement edited."); + break; + default: + String message = "§cUsage: /u announce add|remove|settime|list|edit§r"; + SendMessage(player, message); + return; + } + } + } + + @SuppressWarnings("unused") + private static void DoSaveLoadPos(Player player, String[] args) { // 2015.08.09. + // args[0] is "admin" - args[1] is "savepos|loadpos" + if (args.length == 2) { + String message = "§cUsage: /u admin savepos|loadpos §r"; + SendMessage(player, message); + return; + } + Player p = null; + try { + p = Bukkit.getPlayer(args[2]); + } catch (Exception e) { + } + if (!MaybeOfflinePlayer.AllPlayers.containsKey(p.getUniqueId())) { + String message = "§cPlayer not found: " + args[2] + "§r"; + SendMessage(player, message); + return; + } + MaybeOfflinePlayer mp = MaybeOfflinePlayer.AllPlayers.get(p + .getUniqueId()); + if (p == null) { + String message = "§cPlayer is not online: " + args[2] + "§r"; + SendMessage(player, message); + return; + } + if (args[1].equalsIgnoreCase("savepos")) { + mp.SavedLocation = p.getLocation(); + } else if (args[1].equalsIgnoreCase("loadpos")) { + if (mp.SavedLocation != null) + p.teleport(mp.SavedLocation); + } else { + String message = "§cUsage: /u admin savepos|loadpos §r"; + SendMessage(player, message); + return; + } + // SendMessage(player, "Player " + p.getName() + + // " position saved/loaded.");s + } + + private static void DoUpdateDynmap(Player player, String[] args) { + // args[0] is "admin" - args[1] is "updatedynmap" + if (args.length == 2) { + String message = "§cUsage: /u admin updatedynmap §r"; + SendMessage(player, message); + return; + } + } + + private static Random random = new Random(); + + public static String KittyCannonMinigame = "KittyCannon"; + + private static void DoKittyCannon(Player player, String[] args) { + if (player == null) { + SendMessage(player, + "§cThis command can only be used by a player.§r"); + return; + } + MinigamePlayer mp = Minigames.plugin.pdata.getMinigamePlayer(player); + if (!(mp.isInMinigame() && mp.getMinigame().getName(false) + .equalsIgnoreCase(Commands.KittyCannonMinigame))) { + SendMessage(player, + "§cYou can only use KittyCannon in it's minigame!"); + return; + } + try { + final Mob cat = Mob.OCELOT; + final Ocelot ocelot = (Ocelot) cat.spawn(player.getWorld(), + player.getServer(), player.getEyeLocation()); + if (ocelot == null) { + return; + } + final ArrayList lore = new ArrayList<>(); + lore.add(player.getName()); + final int i = random.nextInt(Ocelot.Type.values().length); + ocelot.setCatType(Ocelot.Type.values()[i]); + ocelot.setTamed(true); + ocelot.setBaby(); + ocelot.addPotionEffect(new PotionEffect( + PotionEffectType.DAMAGE_RESISTANCE, 5, 5)); + ocelot.setVelocity(player.getEyeLocation().getDirection() + .multiply(2)); + Bukkit.getScheduler().scheduleSyncDelayedTask(PluginMain.Instance, + new Runnable() { + @SuppressWarnings("deprecation") + @Override + public void run() { + final Location loc = ocelot.getLocation(); + ocelot.remove(); + loc.getWorld().createExplosion(loc, 0F); + final ItemStack head = new ItemStack( + Material.SKULL_ITEM, 1, (short) 3, (byte) 3); + SkullMeta im = (SkullMeta) head.getItemMeta(); + im.setDisplayName("§rOcelot Head"); + im.setOwner("MHF_Ocelot"); + im.setLore(lore); + head.setItemMeta(im); + loc.getWorld().dropItem(loc, head); + } + }, 20); + } catch (MobException e) { + } + } + + private static void DoMWiki(Player player, String[] args) { + String query = ""; + for (int i = 0; i < args.length; i++) + query += args[i]; + query = query.trim(); + if (args.length == 0) + SendMessage(player, + "§bMinecraft Wiki link: http://minecraft.gamepedia.com/"); + else + SendMessage(player, + "§bMinecraft Wiki link: http://minecraft.gamepedia.com/index.php?search=" + + query + "&title=Special%3ASearch&go=Go"); + } +} diff --git a/src/io/github/norbipeti/thebuttonmc/PluginMain.java b/src/io/github/norbipeti/thebuttonmc/PluginMain.java index 94db27b..6b5e7ba 100644 --- a/src/io/github/norbipeti/thebuttonmc/PluginMain.java +++ b/src/io/github/norbipeti/thebuttonmc/PluginMain.java @@ -1,429 +1,408 @@ -package io.github.norbipeti.thebuttonmc; - -import net.milkbowl.vault.chat.Chat; -import net.milkbowl.vault.economy.Economy; -import net.milkbowl.vault.permission.Permission; - -import org.apache.commons.io.IOUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scoreboard.Scoreboard; -import org.htmlcleaner.HtmlCleaner; -import org.htmlcleaner.TagNode; -import org.json.JSONArray; -import org.json.JSONObject; - -import au.com.mineauz.minigames.mechanics.GameMechanics; - -import com.palmergames.bukkit.towny.Towny; -import com.palmergames.bukkit.towny.object.Nation; -import com.palmergames.bukkit.towny.object.Town; -import com.palmergames.bukkit.towny.object.TownyUniverse; - -import java.io.*; -import java.lang.String; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.TimeZone; - -public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. - // A user, which flair isn't obtainable: - // https://www.reddit.com/r/thebutton/comments/31c32v/i_pressed_the_button_without_really_thinking/ - public static PluginMain Instance; - public static ConsoleCommandSender Console; // 2015.08.12. - public static Scoreboard SB; - public final static String FlairThreadURL = "https://www.reddit.com/r/TheButtonMinecraft/comments/433ptk/autoflair_thread/"; - public TownyUniverse TU; - public ArrayList Towns; - public ArrayList Nations; - - // Fired when plugin is first enabled - @Override - public void onEnable() { - try { - System.out.println("Extracting necessary libraries..."); - final File[] libs = new File[] { new File(getDataFolder(), - "htmlcleaner-2.16.jar") }; - for (final File lib : libs) { - if (!lib.exists()) { - JarUtils.extractFromJar(lib.getName(), - lib.getAbsolutePath()); - } - } - for (final File lib : libs) { - if (!lib.exists()) { - getLogger().warning( - "Failed to load plugin! Could not find lib: " - + lib.getName()); - Bukkit.getServer().getPluginManager().disablePlugin(this); - return; - } - addClassPath(JarUtils.getJarUrl(lib)); - } - } catch (final Exception e) { - e.printStackTrace(); - } - - getServer().getPluginManager().registerEvents(new PlayerListener(), - this); - Commands comm = new Commands(); - this.getCommand("u").setExecutor(comm); - this.getCommand("u").setUsage( - this.getCommand("u").getUsage().replace('&', '§')); - this.getCommand("nrp").setExecutor(comm); - this.getCommand("nrp").setUsage( - this.getCommand("nrp").getUsage().replace('&', '§')); - this.getCommand("ooc").setExecutor(comm); - this.getCommand("ooc").setUsage( - this.getCommand("ooc").getUsage().replace('&', '§')); - this.getCommand("unlol").setExecutor(comm); - this.getCommand("unlaugh").setExecutor(comm); - this.getCommand("mwiki").setExecutor(comm); - this.getCommand("mwiki").setUsage( - this.getCommand("mwiki").getUsage().replace('&', '§')); - this.getCommand("tableflip").setExecutor(comm); - this.getCommand("tableflip").setUsage( - this.getCommand("tableflip").getUsage().replace('&', '§')); - this.getCommand("unflip").setExecutor(comm); - this.getCommand("unflip").setUsage( - this.getCommand("unflip").getUsage().replace('&', '§')); - this.getCommand("chatonly").setExecutor(comm); - this.getCommand("chatonly").setUsage( - this.getCommand("chatonly").getUsage().replace('&', '§')); - Instance = this; - Console = this.getServer().getConsoleSender(); - LoadFiles(false); - - SB = PluginMain.Instance.getServer().getScoreboardManager() - .getMainScoreboard(); // Main can be detected with @a[score_...] - if (SB.getObjective("town") == null) - SB.registerNewObjective("town", "dummy"); - if (SB.getObjective("nation") == null) - SB.registerNewObjective("nation", "dummy"); - if (SB.getObjective("admin") == null) - SB.registerNewObjective("admin", "dummy"); - if (SB.getObjective("mod") == null) - SB.registerNewObjective("mod", "dummy"); - TU = ((Towny) Bukkit.getPluginManager().getPlugin("Towny")) - .getTownyUniverse(); - Towns = new ArrayList(TU.getTownsMap().values()); - Nations = new ArrayList(TU.getNationsMap().values()); - - setupChat(); - setupEconomy(); - setupPermissions(); - - GameMechanics.addGameMechanic(new CreativeGlobalMechanic()); - - Runnable r = new Runnable() { - public void run() { - ThreadMethod(); - } - }; - Thread t = new Thread(r); - t.start(); - r = new Runnable() { - public void run() { - AnnouncerThread.Run(); - } - }; - t = new Thread(r); - t.start(); - } - - public Boolean stop = false; - - // Fired when plugin is disabled - @Override - public void onDisable() { - SaveFiles(); // 2015.08.09. - stop = true; - } - - private void ThreadMethod() { - while (!stop) { - try { - String body = DownloadString(FlairThreadURL - + ".json?limit=1000"); - JSONArray json = new JSONArray(body).getJSONObject(1) - .getJSONObject("data").getJSONArray("children"); - for (Object obj : json) { - JSONObject item = (JSONObject) obj; - String author = item.getJSONObject("data").getString( - "author"); - String ign = item.getJSONObject("data").getString("body"); - int start = ign.indexOf("IGN:") + "IGN:".length(); - if (start == -1 + "IGN:".length()) // +length: 2015.08.10. - continue; // 2015.08.09. - int end = ign.indexOf(' ', start); - if (end == -1 || end == start) - end = ign.indexOf('\n', start); // 2015.07.15. - if (end == -1 || end == start) - ign = ign.substring(start); - else - ign = ign.substring(start, end); - ign = ign.trim(); - MaybeOfflinePlayer mp = MaybeOfflinePlayer.GetFromName(ign); - if (mp == null) - continue; - if (!JoinedBefore(mp, 2015, 6, 5)) - continue; - if (!mp.UserNames.contains(author)) - mp.UserNames.add(author); - if (mp.FlairState.equals(FlairStates.NoComment)) { - mp.FlairState = FlairStates.Commented; - ConfirmUserMessage(mp); - } - try { - Thread.sleep(10); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - try { - Thread.sleep(10000); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } catch (Exception e) { - // System.out.println("Error!\n" + e); - LastException = e; // 2015.08.09. - } - } - } - - public void DownloadFlair(MaybeOfflinePlayer mp) - throws MalformedURLException, IOException { - String[] flairdata = DownloadString( - "http://karmadecay.com/thebutton-data.php?users=" + mp.UserName) - .replace("\"", "").split(":"); - String flair; - if (flairdata.length > 1) - flair = flairdata[1]; - else - flair = ""; - String flairclass; - if (flairdata.length > 2) - flairclass = flairdata[2]; - else - flairclass = "unknown"; - SetFlair(mp, flair, flairclass, mp.UserName); - } - - public static Exception LastException; // 2015.08.09. - - public String DownloadString(String urlstr) throws MalformedURLException, - IOException { - URL url = new URL(urlstr); - URLConnection con = url.openConnection(); - con.setRequestProperty("User-Agent", "TheButtonAutoFlair"); - InputStream in = con.getInputStream(); - String encoding = con.getContentEncoding(); - encoding = encoding == null ? "UTF-8" : encoding; - String body = IOUtils.toString(in, encoding); - in.close(); - return body; - } - - private void SetFlair(MaybeOfflinePlayer p, String text, String flairclass, - String username) { - p.UserName = username; - p.FlairState = FlairStates.Recognised; - switch (flairclass) { - case "cheater": - p.SetFlair((short) 0x5, true); - return; - case "unknown": - if (text.equals("-1")) // If true, only non-presser/can't press; if - // false, any flair (but we can still detect - // can't press) - { - try { - if (CheckForJoinDate(p)) { - p.SetFlair(MaybeOfflinePlayer.FlairTimeNonPresser); - } else { - p.SetFlair(MaybeOfflinePlayer.FlairTimeCantPress); - } - } catch (Exception e) { - p.FlairState = FlairStates.Commented; // Flair unknown - p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); - e.printStackTrace(); - } - } else { - try { - if (CheckForJoinDate(p)) { - p.FlairState = FlairStates.Commented; // Flair unknown - p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); - } else { - p.SetFlair(MaybeOfflinePlayer.FlairTimeCantPress); - } - } catch (Exception e) { - p.FlairState = FlairStates.Commented; // Flair unknown - p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); - e.printStackTrace(); - } - } - return; - default: - break; - } - p.SetFlair(Short.parseShort(text)); - } - - public static boolean CheckForJoinDate(MaybeOfflinePlayer mp) - throws Exception { - return JoinedBefore(mp, 2015, 4, 1); - } - - public static boolean JoinedBefore(MaybeOfflinePlayer mp, int year, - int month, int day) throws Exception { - URL url = new URL("https://www.reddit.com/u/" + mp.UserName); - URLConnection con = url.openConnection(); - con.setRequestProperty("User-Agent", "TheButtonAutoFlair"); - InputStream in = con.getInputStream(); - HtmlCleaner cleaner = new HtmlCleaner(); - TagNode node = cleaner.clean(in); - - node = node.getElementsByAttValue("class", "age", true, true)[0]; - node = node.getElementsByName("time", false)[0]; - String joindate = node.getAttributeByName("datetime"); - SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd"); - joindate = joindate.split("T")[0]; - Date date = parserSDF.parse(joindate); - return date.before(new Calendar.Builder() - .setTimeZone(TimeZone.getTimeZone("UTC")) - .setDate(year, month, day).build().getTime()); - } - - public static void ConfirmUserMessage(MaybeOfflinePlayer mp) { - Player p = Bukkit.getPlayer(mp.UUID); - if (mp.FlairState.equals(FlairStates.Commented) && p != null) - if (mp.UserNames.size() > 1) - p.sendMessage("§9Multiple Reddit users commented your name. You can select with /u accept.§r §6Type /u accept or /u ignore§r"); - else - p.sendMessage("§9A Reddit user commented your name. Is that you?§r §6Type /u accept or /u ignore§r"); - } - - public static Collection GetPlayers() { - return Instance.getServer().getOnlinePlayers(); - } - - public static ArrayList AnnounceMessages = new ArrayList<>(); - public static int AnnounceTime = 15 * 60 * 1000; - - public static void LoadFiles(boolean reload) { - if (reload) { - System.out - .println("The Button Minecraft plugin cleanup for reloading..."); - MaybeOfflinePlayer.AllPlayers.clear(); - AnnounceMessages.clear(); - } - System.out.println("Loading files for The Button Minecraft plugin..."); - try { - File file = new File("thebuttonmc.yml"); - if (file.exists()) { - YamlConfiguration yc = new YamlConfiguration(); - yc.load(file); - MaybeOfflinePlayer.Load(yc); - PlayerListener.NotificationSound = yc - .getString("notificationsound"); - PlayerListener.NotificationPitch = yc - .getDouble("notificationpitch"); - AnnounceTime = yc.getInt("announcetime"); - AnnounceMessages.addAll(yc.getStringList("announcements")); - PlayerListener.AlphaDeaths = yc.getInt("alphadeaths"); - } - System.out.println("The Button Minecraft plugin loaded files!"); - } catch (IOException e) { - System.out.println("Error!\n" + e); - LastException = e; - } catch (InvalidConfigurationException e) { - System.out.println("Error!\n" + e); - LastException = e; - } - } - - public static void SaveFiles() { - System.out.println("Saving files for The Button Minecraft plugin..."); - try { - File file = new File("thebuttonmc.yml"); - YamlConfiguration yc = new YamlConfiguration(); - MaybeOfflinePlayer.Save(yc); - yc.set("notificationsound", PlayerListener.NotificationSound); - yc.set("notificationpitch", PlayerListener.NotificationPitch); - yc.set("announcetime", AnnounceTime); - yc.set("announcements", AnnounceMessages); - yc.set("alphadeaths", PlayerListener.AlphaDeaths); - yc.save(file); - System.out.println("The Button Minecraft plugin saved files!"); - } catch (IOException e) { - System.out.println("Error!\n" + e); - LastException = e; - } - } - - private void addClassPath(final URL url) throws IOException { - final URLClassLoader sysloader = (URLClassLoader) ClassLoader - .getSystemClassLoader(); - final Class sysclass = URLClassLoader.class; - try { - final Method method = sysclass.getDeclaredMethod("addURL", - new Class[] { URL.class }); - method.setAccessible(true); - method.invoke(sysloader, new Object[] { url }); - } catch (final Throwable t) { - t.printStackTrace(); - throw new IOException("Error adding " + url - + " to system classloader"); - } - } - - public static Permission permission = null; - public static Economy economy = null; - public static Chat chat = null; - - private boolean setupPermissions() { - RegisteredServiceProvider permissionProvider = getServer() - .getServicesManager().getRegistration( - net.milkbowl.vault.permission.Permission.class); - if (permissionProvider != null) { - permission = permissionProvider.getProvider(); - } - return (permission != null); - } - - private boolean setupChat() { - RegisteredServiceProvider chatProvider = getServer() - .getServicesManager().getRegistration( - net.milkbowl.vault.chat.Chat.class); - if (chatProvider != null) { - chat = chatProvider.getProvider(); - } - - return (chat != null); - } - - private boolean setupEconomy() { - RegisteredServiceProvider economyProvider = getServer() - .getServicesManager().getRegistration( - net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - - return (economy != null); - } -} +package io.github.norbipeti.thebuttonmc; + +import net.milkbowl.vault.chat.Chat; +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.permission.Permission; + +import org.apache.commons.io.IOUtils; +import org.bukkit.Bukkit; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scoreboard.Scoreboard; +import org.htmlcleaner.HtmlCleaner; +import org.htmlcleaner.TagNode; +import org.json.JSONArray; +import org.json.JSONObject; + +import au.com.mineauz.minigames.mechanics.GameMechanics; + +import com.palmergames.bukkit.towny.Towny; +import com.palmergames.bukkit.towny.object.Nation; +import com.palmergames.bukkit.towny.object.Town; +import com.palmergames.bukkit.towny.object.TownyUniverse; + +import io.github.norbipeti.thebuttonmc.commands.TBMCCommandBase; + +import java.io.*; +import java.lang.String; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLConnection; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.TimeZone; + +public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. + // A user, which flair isn't obtainable: + // https://www.reddit.com/r/thebutton/comments/31c32v/i_pressed_the_button_without_really_thinking/ + public static PluginMain Instance; + public static ConsoleCommandSender Console; // 2015.08.12. + public static Scoreboard SB; + public final static String FlairThreadURL = "https://www.reddit.com/r/TheButtonMinecraft/comments/433ptk/autoflair_thread/"; + public TownyUniverse TU; + public ArrayList Towns; + public ArrayList Nations; + + // Fired when plugin is first enabled + @Override + public void onEnable() { + try { + System.out.println("Extracting necessary libraries..."); + final File[] libs = new File[] { new File(getDataFolder(), + "htmlcleaner-2.16.jar") }; + for (final File lib : libs) { + if (!lib.exists()) { + JarUtils.extractFromJar(lib.getName(), + lib.getAbsolutePath()); + } + } + for (final File lib : libs) { + if (!lib.exists()) { + getLogger().warning( + "Failed to load plugin! Could not find lib: " + + lib.getName()); + Bukkit.getServer().getPluginManager().disablePlugin(this); + return; + } + addClassPath(JarUtils.getJarUrl(lib)); + } + } catch (final Exception e) { + e.printStackTrace(); + } + + getServer().getPluginManager().registerEvents(new PlayerListener(), + this); + TBMCCommandBase.RegisterCommands(this); + Instance = this; + Console = this.getServer().getConsoleSender(); + LoadFiles(false); + + SB = PluginMain.Instance.getServer().getScoreboardManager() + .getMainScoreboard(); // Main can be detected with @a[score_...] + if (SB.getObjective("town") == null) + SB.registerNewObjective("town", "dummy"); + if (SB.getObjective("nation") == null) + SB.registerNewObjective("nation", "dummy"); + if (SB.getObjective("admin") == null) + SB.registerNewObjective("admin", "dummy"); + if (SB.getObjective("mod") == null) + SB.registerNewObjective("mod", "dummy"); + TU = ((Towny) Bukkit.getPluginManager().getPlugin("Towny")) + .getTownyUniverse(); + Towns = new ArrayList(TU.getTownsMap().values()); + Nations = new ArrayList(TU.getNationsMap().values()); + + setupChat(); + setupEconomy(); + setupPermissions(); + + GameMechanics.addGameMechanic(new CreativeGlobalMechanic()); + + Runnable r = new Runnable() { + public void run() { + ThreadMethod(); + } + }; + Thread t = new Thread(r); + t.start(); + r = new Runnable() { + public void run() { + AnnouncerThread.Run(); + } + }; + t = new Thread(r); + t.start(); + } + + public Boolean stop = false; + + // Fired when plugin is disabled + @Override + public void onDisable() { + SaveFiles(); // 2015.08.09. + stop = true; + } + + private void ThreadMethod() { + while (!stop) { + try { + String body = DownloadString(FlairThreadURL + + ".json?limit=1000"); + JSONArray json = new JSONArray(body).getJSONObject(1) + .getJSONObject("data").getJSONArray("children"); + for (Object obj : json) { + JSONObject item = (JSONObject) obj; + String author = item.getJSONObject("data").getString( + "author"); + String ign = item.getJSONObject("data").getString("body"); + int start = ign.indexOf("IGN:") + "IGN:".length(); + if (start == -1 + "IGN:".length()) // +length: 2015.08.10. + continue; // 2015.08.09. + int end = ign.indexOf(' ', start); + if (end == -1 || end == start) + end = ign.indexOf('\n', start); // 2015.07.15. + if (end == -1 || end == start) + ign = ign.substring(start); + else + ign = ign.substring(start, end); + ign = ign.trim(); + MaybeOfflinePlayer mp = MaybeOfflinePlayer.GetFromName(ign); + if (mp == null) + continue; + if (!JoinedBefore(mp, 2015, 6, 5)) + continue; + if (!mp.UserNames.contains(author)) + mp.UserNames.add(author); + if (mp.FlairState.equals(FlairStates.NoComment)) { + mp.FlairState = FlairStates.Commented; + ConfirmUserMessage(mp); + } + try { + Thread.sleep(10); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + try { + Thread.sleep(10000); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } catch (Exception e) { + // System.out.println("Error!\n" + e); + LastException = e; // 2015.08.09. + } + } + } + + public void DownloadFlair(MaybeOfflinePlayer mp) + throws MalformedURLException, IOException { + String[] flairdata = DownloadString( + "http://karmadecay.com/thebutton-data.php?users=" + mp.UserName) + .replace("\"", "").split(":"); + String flair; + if (flairdata.length > 1) + flair = flairdata[1]; + else + flair = ""; + String flairclass; + if (flairdata.length > 2) + flairclass = flairdata[2]; + else + flairclass = "unknown"; + SetFlair(mp, flair, flairclass, mp.UserName); + } + + public static Exception LastException; // 2015.08.09. + + public String DownloadString(String urlstr) throws MalformedURLException, + IOException { + URL url = new URL(urlstr); + URLConnection con = url.openConnection(); + con.setRequestProperty("User-Agent", "TheButtonAutoFlair"); + InputStream in = con.getInputStream(); + String encoding = con.getContentEncoding(); + encoding = encoding == null ? "UTF-8" : encoding; + String body = IOUtils.toString(in, encoding); + in.close(); + return body; + } + + private void SetFlair(MaybeOfflinePlayer p, String text, String flairclass, + String username) { + p.UserName = username; + p.FlairState = FlairStates.Recognised; + switch (flairclass) { + case "cheater": + p.SetFlair((short) 0x5, true); + return; + case "unknown": + if (text.equals("-1")) // If true, only non-presser/can't press; if + // false, any flair (but we can still detect + // can't press) + { + try { + if (CheckForJoinDate(p)) { + p.SetFlair(MaybeOfflinePlayer.FlairTimeNonPresser); + } else { + p.SetFlair(MaybeOfflinePlayer.FlairTimeCantPress); + } + } catch (Exception e) { + p.FlairState = FlairStates.Commented; // Flair unknown + p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); + e.printStackTrace(); + } + } else { + try { + if (CheckForJoinDate(p)) { + p.FlairState = FlairStates.Commented; // Flair unknown + p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); + } else { + p.SetFlair(MaybeOfflinePlayer.FlairTimeCantPress); + } + } catch (Exception e) { + p.FlairState = FlairStates.Commented; // Flair unknown + p.SetFlair(MaybeOfflinePlayer.FlairTimeNone); + e.printStackTrace(); + } + } + return; + default: + break; + } + p.SetFlair(Short.parseShort(text)); + } + + public static boolean CheckForJoinDate(MaybeOfflinePlayer mp) + throws Exception { + return JoinedBefore(mp, 2015, 4, 1); + } + + public static boolean JoinedBefore(MaybeOfflinePlayer mp, int year, + int month, int day) throws Exception { + URL url = new URL("https://www.reddit.com/u/" + mp.UserName); + URLConnection con = url.openConnection(); + con.setRequestProperty("User-Agent", "TheButtonAutoFlair"); + InputStream in = con.getInputStream(); + HtmlCleaner cleaner = new HtmlCleaner(); + TagNode node = cleaner.clean(in); + + node = node.getElementsByAttValue("class", "age", true, true)[0]; + node = node.getElementsByName("time", false)[0]; + String joindate = node.getAttributeByName("datetime"); + SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd"); + joindate = joindate.split("T")[0]; + Date date = parserSDF.parse(joindate); + return date.before(new Calendar.Builder() + .setTimeZone(TimeZone.getTimeZone("UTC")) + .setDate(year, month, day).build().getTime()); + } + + public static void ConfirmUserMessage(MaybeOfflinePlayer mp) { + Player p = Bukkit.getPlayer(mp.UUID); + if (mp.FlairState.equals(FlairStates.Commented) && p != null) + if (mp.UserNames.size() > 1) + p.sendMessage("§9Multiple Reddit users commented your name. You can select with /u accept.§r §6Type /u accept or /u ignore§r"); + else + p.sendMessage("§9A Reddit user commented your name. Is that you?§r §6Type /u accept or /u ignore§r"); + } + + public static Collection GetPlayers() { + return Instance.getServer().getOnlinePlayers(); + } + + public static ArrayList AnnounceMessages = new ArrayList<>(); + public static int AnnounceTime = 15 * 60 * 1000; + + public static void LoadFiles(boolean reload) { + if (reload) { + System.out + .println("The Button Minecraft plugin cleanup for reloading..."); + MaybeOfflinePlayer.AllPlayers.clear(); + AnnounceMessages.clear(); + } + System.out.println("Loading files for The Button Minecraft plugin..."); + try { + File file = new File("thebuttonmc.yml"); + if (file.exists()) { + YamlConfiguration yc = new YamlConfiguration(); + yc.load(file); + MaybeOfflinePlayer.Load(yc); + PlayerListener.NotificationSound = yc + .getString("notificationsound"); + PlayerListener.NotificationPitch = yc + .getDouble("notificationpitch"); + AnnounceTime = yc.getInt("announcetime"); + AnnounceMessages.addAll(yc.getStringList("announcements")); + PlayerListener.AlphaDeaths = yc.getInt("alphadeaths"); + } + System.out.println("The Button Minecraft plugin loaded files!"); + } catch (IOException e) { + System.out.println("Error!\n" + e); + LastException = e; + } catch (InvalidConfigurationException e) { + System.out.println("Error!\n" + e); + LastException = e; + } + } + + public static void SaveFiles() { + System.out.println("Saving files for The Button Minecraft plugin..."); + try { + File file = new File("thebuttonmc.yml"); + YamlConfiguration yc = new YamlConfiguration(); + MaybeOfflinePlayer.Save(yc); + yc.set("notificationsound", PlayerListener.NotificationSound); + yc.set("notificationpitch", PlayerListener.NotificationPitch); + yc.set("announcetime", AnnounceTime); + yc.set("announcements", AnnounceMessages); + yc.set("alphadeaths", PlayerListener.AlphaDeaths); + yc.save(file); + System.out.println("The Button Minecraft plugin saved files!"); + } catch (IOException e) { + System.out.println("Error!\n" + e); + LastException = e; + } + } + + private void addClassPath(final URL url) throws IOException { + final URLClassLoader sysloader = (URLClassLoader) ClassLoader + .getSystemClassLoader(); + final Class sysclass = URLClassLoader.class; + try { + final Method method = sysclass.getDeclaredMethod("addURL", + new Class[] { URL.class }); + method.setAccessible(true); + method.invoke(sysloader, new Object[] { url }); + } catch (final Throwable t) { + t.printStackTrace(); + throw new IOException("Error adding " + url + + " to system classloader"); + } + } + + public static Permission permission = null; + public static Economy economy = null; + public static Chat chat = null; + + private boolean setupPermissions() { + RegisteredServiceProvider permissionProvider = getServer() + .getServicesManager().getRegistration( + net.milkbowl.vault.permission.Permission.class); + if (permissionProvider != null) { + permission = permissionProvider.getProvider(); + } + return (permission != null); + } + + private boolean setupChat() { + RegisteredServiceProvider chatProvider = getServer() + .getServicesManager().getRegistration( + net.milkbowl.vault.chat.Chat.class); + if (chatProvider != null) { + chat = chatProvider.getProvider(); + } + + return (chat != null); + } + + private boolean setupEconomy() { + RegisteredServiceProvider economyProvider = getServer() + .getServicesManager().getRegistration( + net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + } + + return (economy != null); + } +}