From 83c99df895c8e94a732b05be5e156c22bafbff90 Mon Sep 17 00:00:00 2001 From: NorbiPeti Date: Thu, 11 Oct 2018 13:15:03 +0200 Subject: [PATCH] Adding support for nation color (WIP) Also various fixes Got rid of a bunch of warnings --- pom.xml | 2 +- .../java/buttondevteam/chat/PluginMain.java | 44 ++++++++++++------- .../chat/commands/ucmds/TownColorCommand.java | 13 +++--- .../ucmds/admin/TownColorCommand.java | 29 +++++++++--- .../listener/PlayerJoinLeaveListener.java | 43 +++++------------- .../chat/listener/TownyListener.java | 20 ++++++++- 6 files changed, 85 insertions(+), 66 deletions(-) diff --git a/pom.xml b/pom.xml index 024cb81..8056f5b 100644 --- a/pom.xml +++ b/pom.xml @@ -163,7 +163,7 @@ com.github.TBMCPlugins.ButtonCore Towny - master-SNAPSHOT + 8d3b6b6 com.vexsoftware diff --git a/src/main/java/buttondevteam/chat/PluginMain.java b/src/main/java/buttondevteam/chat/PluginMain.java index b082706..d7b7ad1 100644 --- a/src/main/java/buttondevteam/chat/PluginMain.java +++ b/src/main/java/buttondevteam/chat/PluginMain.java @@ -40,7 +40,6 @@ import org.htmlcleaner.TagNode; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; @@ -54,16 +53,16 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. // https://www.reddit.com/r/thebutton/comments/31c32v/i_pressed_the_button_without_really_thinking/ public static PluginMain Instance; public static ConsoleCommandSender Console; - public final static String FlairThreadURL = "https://www.reddit.com/r/Chromagamers/comments/51ys94/flair_thread_for_the_mc_server/"; + private final static String FlairThreadURL = "https://www.reddit.com/r/Chromagamers/comments/51ys94/flair_thread_for_the_mc_server/"; public static Scoreboard SB; public static TownyUniverse TU; - public static ArrayList Towns; - public static ArrayList Nations; + private static ArrayList Towns; + private static ArrayList Nations; public static Channel TownChat; public static Channel NationChat; - public static Channel RPChannel; + private static Channel RPChannel; //TODO: Move to ButtonCore - or use the ch filter in the Discord plugin /** *

@@ -88,10 +87,11 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. SB = getServer().getScoreboardManager().getMainScoreboard(); // Main can be detected with @a[score_...] TU = ((Towny) Bukkit.getPluginManager().getPlugin("Towny")).getTownyUniverse(); - Towns = new ArrayList(TU.getTownsMap().values()); // Creates a snapshot of towns, new towns will be added when needed - Nations = new ArrayList(TU.getNationsMap().values()); // Same here but with nations + Towns = new ArrayList<>(TU.getTownsMap().values()); // Creates a snapshot of towns, new towns will be added when needed + Nations = new ArrayList<>(TU.getNationsMap().values()); // Same here but with nations - TownColors.keySet().removeIf(t -> !TU.getTownsMap().containsKey(t.toLowerCase())); // Removes town colors for deleted/renamed towns + TownColors.keySet().removeIf(t -> !TU.getTownsMap().containsKey(t)); // Removes town colors for deleted/renamed towns + NationColor.keySet().removeIf(n -> !TU.getNationsMap().containsKey(n)); // Removes nation colors for deleted/renamed nations TBMCChatAPI.RegisterChatChannel( TownChat = new Channel("§3TC§f", Color.DarkAqua, "tc", s -> checkTownNationChat(s, false))); @@ -201,7 +201,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. } } - public void DownloadFlair(ChatPlayer mp) throws MalformedURLException, IOException { + public void DownloadFlair(ChatPlayer mp) throws IOException { String[] flairdata = TBMCCoreAPI .DownloadString("http://karmadecay.com/thebutton-data.php?users=" + mp.UserName().get()) .replace("\"", "").split(":"); @@ -247,11 +247,11 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. p.SetFlair(Short.parseShort(text)); } - public static boolean CheckForJoinDate(ChatPlayer mp) throws Exception { + private static boolean CheckForJoinDate(ChatPlayer mp) throws Exception { return JoinedBefore(mp, 2015, 4, 1); } - public static boolean JoinedBefore(ChatPlayer mp, int year, int month, int day) throws Exception { + private static boolean JoinedBefore(ChatPlayer 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"); @@ -281,13 +281,17 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. public static ArrayList AnnounceMessages = new ArrayList<>(); public static int AnnounceTime = 15 * 60 * 1000; - /** - * Names lowercased - */ - public static Map TownColors = new HashMap<>(); + /** + * Names lowercased + */ + public static Map TownColors = new HashMap<>(); + /** + * Names lowercased - nation color gets added to town colors when needed + */ + public static Map NationColor = new HashMap<>(); @SuppressWarnings("unchecked") - public static void LoadFiles() { + private static void LoadFiles() { PluginMain.Instance.getLogger().info("Loading files..."); try { File file = new File("TBMC/chatsettings.yml"); @@ -305,6 +309,10 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. .collect(Collectors.toMap(Map.Entry::getKey, v -> ((List) v.getValue()).stream() .map(Color::valueOf).toArray(Color[]::new)))); TownColorCommand.ColorCount = (byte) yc.getInt("towncolorcount", 1); + val ncs = yc.getConfigurationSection("nationcolors"); + if (ncs != null) + NationColor.putAll(ncs.getValues(true).entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, v -> Color.valueOf((String) v.getValue())))); PluginMain.Instance.getLogger().info("Loaded files!"); } else PluginMain.Instance.getLogger().info("No files to load, first run probably."); @@ -323,9 +331,11 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15. yc.set("announcetime", AnnounceTime); yc.set("announcements", AnnounceMessages); yc.set("alphadeaths", PlayerListener.AlphaDeaths); - yc.createSection("towncolors", TownColors.entrySet().stream().collect(Collectors.toMap(k -> k.getKey(), + yc.createSection("towncolors", TownColors.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, v -> Arrays.stream(v.getValue()).map(Enum::toString).toArray(String[]::new)))); yc.set("towncolorcount", TownColorCommand.ColorCount); + yc.createSection("nationcolors", NationColor.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + v -> v.getValue().toString()))); yc.save(file); PluginMain.Instance.getLogger().info("Saved files!"); } catch (Exception e) { diff --git a/src/main/java/buttondevteam/chat/commands/ucmds/TownColorCommand.java b/src/main/java/buttondevteam/chat/commands/ucmds/TownColorCommand.java index 7d0d9d8..197a574 100644 --- a/src/main/java/buttondevteam/chat/commands/ucmds/TownColorCommand.java +++ b/src/main/java/buttondevteam/chat/commands/ucmds/TownColorCommand.java @@ -1,22 +1,21 @@ package buttondevteam.chat.commands.ucmds; -import org.bukkit.entity.Player; -import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; -import com.palmergames.bukkit.towny.object.Resident; - import buttondevteam.chat.PluginMain; import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.OptionallyPlayerCommandClass; +import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; +import com.palmergames.bukkit.towny.object.Resident; +import org.bukkit.entity.Player; @CommandClass // TODO: /u u when annotation not present @OptionallyPlayerCommandClass(playerOnly = true) public class TownColorCommand extends UCommandBase { @Override public String GetHelpText(String alias)[] { - String cns = " "; + StringBuilder cns = new StringBuilder(" "); for (int i = 2; i <= ColorCount; i++) - cns += " [colorname" + i + "]"; + cns.append(" [colorname").append(i).append("]"); return new String[] { // "§6---- Town Color ----", // "This command allows setting a color for a town.", // @@ -47,7 +46,7 @@ public class TownColorCommand extends UCommandBase { String[] a = new String[args.length + 1]; System.arraycopy(args, 0, a, 1, args.length); try { - a[0] = res.getTown().getName().toLowerCase(); + a[0] = res.getTown().getName(); } catch (NotRegisteredException e) { TBMCCoreAPI.SendException("Failed to set town color for player " + player + "!", e); player.sendMessage("§cCouldn't find your town... Error reported."); diff --git a/src/main/java/buttondevteam/chat/commands/ucmds/admin/TownColorCommand.java b/src/main/java/buttondevteam/chat/commands/ucmds/admin/TownColorCommand.java index 72f92dc..38c56d8 100644 --- a/src/main/java/buttondevteam/chat/commands/ucmds/admin/TownColorCommand.java +++ b/src/main/java/buttondevteam/chat/commands/ucmds/admin/TownColorCommand.java @@ -11,6 +11,7 @@ import org.bukkit.command.CommandSender; import org.dynmap.towny.DynmapTownyPlugin; import java.util.Arrays; +import java.util.Optional; import java.util.stream.Collectors; public class TownColorCommand extends AdminCommandBase { @@ -38,10 +39,21 @@ public class TownColorCommand extends AdminCommandBase { sender.sendMessage("§cThe town '" + args[0] + "' cannot be found."); return true; } - val clrs = new Color[args.length - 1]; - for (int i = 1; i < args.length; i++) { - val ii = i; - val c = Arrays.stream(Color.values()).skip(1).filter(cc -> cc.getName().equalsIgnoreCase(args[ii])).findAny(); + Color[] clrs = null; //Add nation color as well + Town targetTown = PluginMain.TU.getTownsMap().get(args[0].toLowerCase()); + try { + Color c; //TODO: Add command for nation color + if (targetTown.getNation() != null + && (c = PluginMain.NationColor.get(targetTown.getNation().getName().toLowerCase())) != null) { + clrs = new Color[args.length]; + clrs[0] = c; + } + } catch (NotRegisteredException ignored) { + } + if (clrs == null) + clrs = new Color[args.length - 1]; + for (int i = 1; i < args.length; i++) { + val c = getColor(args[i]); if (!c.isPresent()) { //^^ Skip black sender.sendMessage("§cThe color '" + args[i] + "' cannot be found."); //ˇˇ Skip black sender.sendMessage("§cAvailable colors: " + Arrays.stream(Color.values()).skip(1).map(col -> String.format("§%x%s§r", col.ordinal(), col.getName())).collect(Collectors.joining(", "))); @@ -51,13 +63,12 @@ public class TownColorCommand extends AdminCommandBase { clrs[i - 1] = c.get(); } PluginMain.TownColors.put(args[0].toLowerCase(), clrs); - //PluginMain.TU.getTownsMap().get(args[0].toLowerCase()).getResidents().forEach(r->{ Bukkit.getOnlinePlayers().forEach(p -> { try { Town t = PluginMain.TU.getResidentMap().get(p.getName().toLowerCase()).getTown(); if (t != null && t.getName().equalsIgnoreCase(args[0])) PlayerJoinLeaveListener.updatePlayerColors(p); - } catch (NotRegisteredException e) { + } catch (NotRegisteredException ignored) { } }); @@ -72,7 +83,11 @@ public class TownColorCommand extends AdminCommandBase { return true; } - public static String getTownNameCased(String name) { + private static Optional getColor(String name) { + return Arrays.stream(Color.values()).skip(1).filter(cc -> cc.getName().equalsIgnoreCase(name)).findAny(); + } + + public static String getTownNameCased(String name) { return PluginMain.TU.getTownsMap().get(name.toLowerCase()).getName(); } } diff --git a/src/main/java/buttondevteam/chat/listener/PlayerJoinLeaveListener.java b/src/main/java/buttondevteam/chat/listener/PlayerJoinLeaveListener.java index 4d5d940..91f5fa2 100644 --- a/src/main/java/buttondevteam/chat/listener/PlayerJoinLeaveListener.java +++ b/src/main/java/buttondevteam/chat/listener/PlayerJoinLeaveListener.java @@ -51,31 +51,7 @@ public class PlayerJoinLeaveListener implements Listener { }; tt.mp = cp; timer.schedule(tt, 1000); - } else { - /*Timer timer = new Timer(); - PlayerJoinTimerTask tt = new PlayerJoinTimerTask() { - - @Override - public void run() { - Player player = Bukkit.getPlayer(mp.PlayerName().get()); - if (player == null) - return; - - if (mp.FlairState().get().equals(FlairStates.NoComment)) { - String json = String.format( - "[\"\",{\"text\":\"If you're from Reddit and you'd like your /r/TheButton flair displayed ingame, write your Minecraft name to \",\"color\":\"aqua\"},{\"text\":\"[this thread].\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"%s\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Click here to go to the Reddit thread\",\"color\":\"aqua\"}]}}}]", - PluginMain.FlairThreadURL); - PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, - "tellraw " + mp.PlayerName() + " " + json); - json = "[\"\",{\"text\":\"If you aren't from Reddit or don't want the flair, type /u ignore to prevent this message after next login.\",\"color\":\"aqua\"}]"; - PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, - "tellraw " + mp.PlayerName() + " " + json); - } - } - }; - tt.mp = cp; - timer.schedule(tt, 15 * 1000);*/ //TODO: Better Reddit integration (OAuth) - } + } //TODO: Better Reddit integration (OAuth) String nwithoutformatting = PluginMain.essentials.getUser(p).getNickname(); @@ -109,7 +85,7 @@ public class PlayerJoinLeaveListener implements Listener { UnlolCommand.Lastlol.values().removeIf(lld -> lld.getLolowner().equals(event.getPlayer())); } - private static String getPlayerNickname(Player player, User user) { + private static String getPlayerNickname(Player player, User user, ChatPlayer cp) { String nickname = user.getNick(true); if (nickname.contains("~")) //StartsWith doesn't work because of color codes nickname = nickname.replace("~", ""); //It gets stacked otherwise @@ -128,7 +104,7 @@ public class PlayerJoinLeaveListener implements Listener { + (i + 1 == clrs.length ? name.substring(prevlen.get()) : name.substring(prevlen.get(), prevlen.addAndGet(len))); int len = name.length() / clrs.length; - val nclar = ChatPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class).NameColorLocations().get(); + val nclar = cp.NameColorLocations().get(); int[] ncl = nclar == null ? null : nclar.stream().mapToInt(Integer::intValue).toArray(); if (ncl != null && (Arrays.stream(ncl).sum() != name.length() || ncl.length != clrs.length)) ncl = null; // Reset if name length changed @@ -145,10 +121,11 @@ public class PlayerJoinLeaveListener implements Listener { updatePlayerColors(player, ChatPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class)); } - public static void updatePlayerColors(Player player, ChatPlayer cp) { //Probably at join - nop, nicknames - User user = PluginMain.essentials.getUser(player); - user.setNickname(getPlayerNickname(player, user)); - user.setDisplayNick(); //These won't fire the nick change event - cp.FlairUpdate(); //Update in list - } + @SuppressWarnings("WeakerAccess") + public static void updatePlayerColors(Player player, ChatPlayer cp) { //Probably at join - nop, nicknames + User user = PluginMain.essentials.getUser(player); + user.setNickname(getPlayerNickname(player, user, cp)); + user.setDisplayNick(); //These won't fire the nick change event + cp.FlairUpdate(); //Update in list + } } diff --git a/src/main/java/buttondevteam/chat/listener/TownyListener.java b/src/main/java/buttondevteam/chat/listener/TownyListener.java index 56309f4..54a3dbf 100644 --- a/src/main/java/buttondevteam/chat/listener/TownyListener.java +++ b/src/main/java/buttondevteam/chat/listener/TownyListener.java @@ -3,6 +3,7 @@ package buttondevteam.chat.listener; import buttondevteam.chat.PluginMain; import com.earth2me.essentials.User; import com.palmergames.bukkit.towny.event.*; +import com.palmergames.bukkit.towny.object.Town; import lombok.val; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -10,6 +11,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; +import java.util.Objects; + public class TownyListener implements Listener { @EventHandler public void onTownRename(RenameTownEvent event) { @@ -25,6 +28,21 @@ public class TownyListener implements Listener { PlayerJoinLeaveListener.updatePlayerColors(p); } + @EventHandler //Gets called on town load as well + public void onNationJoin(NationAddTownEvent event) { + updateTownMembers(event.getTown()); + } + + @EventHandler //Gets called on town load as well + public void onNationLeave(NationRemoveTownEvent event) { + updateTownMembers(event.getTown()); + } + + private void updateTownMembers(Town town) { //TODO: Update (or remove) nation color from town color + town.getResidents().stream().map(r -> Bukkit.getPlayer(r.getName())) + .filter(Objects::nonNull).forEach(PlayerJoinLeaveListener::updatePlayerColors); + } + @EventHandler public void onTownLeave(TownRemoveResidentEvent event) { Player p = Bukkit.getPlayer(event.getResident().getName()); @@ -43,6 +61,6 @@ public class TownyListener implements Listener { public void onTownCreate(NewTownEvent event) { Player p = Bukkit.getPlayer(event.getTown().getMayor().getName()); if (p != null) - p.sendMessage("§6Use /u towncolor [color2] to set a color for the town."); + p.sendMessage("§6Use /u towncolor to set a color for the town."); } }