More Audit Things + Code Cleanup + SaberException Added for Debugging

This commit is contained in:
Driftay 2019-12-28 04:58:33 -05:00
parent acf06c78ed
commit 8e855bc9bb
18 changed files with 178 additions and 190 deletions

View File

@ -101,6 +101,9 @@ public class Conf {
public static boolean worldGuardBuildPriority = false; public static boolean worldGuardBuildPriority = false;
public static boolean factionsDrainEnabled = false; public static boolean factionsDrainEnabled = false;
//AUDIT
public static boolean useAuditSystem = true;
//DISCORD //DISCORD
public static boolean useDiscordSystem = false; public static boolean useDiscordSystem = false;
public static String discordBotToken = "<token here>"; public static String discordBotToken = "<token here>";

View File

@ -3,6 +3,7 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.alts.CmdAlts; import com.massivecraft.factions.cmd.alts.CmdAlts;
import com.massivecraft.factions.cmd.audit.CmdAudit;
import com.massivecraft.factions.cmd.check.CmdCheck; import com.massivecraft.factions.cmd.check.CmdCheck;
import com.massivecraft.factions.cmd.check.CmdWeeWoo; import com.massivecraft.factions.cmd.check.CmdWeeWoo;
import com.massivecraft.factions.cmd.chest.CmdChest; import com.massivecraft.factions.cmd.chest.CmdChest;
@ -164,6 +165,7 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
public CmdDebug cmdDebug = new CmdDebug(); public CmdDebug cmdDebug = new CmdDebug();
public CmdDrain cmdDrain = new CmdDrain(); public CmdDrain cmdDrain = new CmdDrain();
public CmdLookup cmdLookup = new CmdLookup(); public CmdLookup cmdLookup = new CmdLookup();
public CmdAudit cmdAudit = new CmdAudit();
//Variables to know if we already setup certain sub commands //Variables to know if we already setup certain sub commands
public Boolean discordEnabled = false; public Boolean discordEnabled = false;
public Boolean checkEnabled = false; public Boolean checkEnabled = false;
@ -179,6 +181,7 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
public Boolean coreProtectEnabled = false; public Boolean coreProtectEnabled = false;
public Boolean internalFTOPEnabled = false; public Boolean internalFTOPEnabled = false;
public Boolean fWildEnabled = false; public Boolean fWildEnabled = false;
public Boolean fAuditEnabled = false;
public FCmdRoot() { public FCmdRoot() {
super(); super();
@ -340,6 +343,12 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
this.addSubCommand(this.cmdTop); this.addSubCommand(this.cmdTop);
internalFTOPEnabled = true; internalFTOPEnabled = true;
} }
if(Conf.useAuditSystem){
this.addSubCommand(cmdAudit);
fAuditEnabled = true;
}
//Other //Other
if (FactionsPlugin.getInstance().getConfig().getBoolean("Wild.Enabled", false) && !fWildEnabled) { if (FactionsPlugin.getInstance().getConfig().getBoolean("Wild.Enabled", false) && !fWildEnabled) {
this.addSubCommand(this.cmdWild); this.addSubCommand(this.cmdWild);

View File

@ -1,7 +1,7 @@
package com.massivecraft.factions.cmd.audit; package com.massivecraft.factions.cmd.audit;
/** /*
* @author Saser @author Saser
*/ */
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
@ -20,7 +20,6 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
public class FAuditMenu extends GUIMenu { public class FAuditMenu extends GUIMenu {
private static int logsPerPage = 20;
private Player player; private Player player;
private boolean showTimestamps = true; private boolean showTimestamps = true;
private Faction faction; private Faction faction;
@ -33,62 +32,42 @@ public class FAuditMenu extends GUIMenu {
public void drawItems() { public void drawItems() {
int index = 0; int index = 0;
FLogType[] logTypes = FLogType.values(); for (FLogType type : FLogType.values()) {
int length1 = logTypes.length; if (type.getSlot() == -1) continue;
for (FLogType type : logTypes) {
if (type != FLogType.F_TNT || FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled")) { if (type != FLogType.F_TNT || FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled")) {
if (index == 9) { if (index == 9) index = FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled") ? 11 : 12;
index = FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled") ? 11 : 12; FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(faction.getId());
} if (logs == null) logs = new FactionLogs();
FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(this.faction.getId());
if (logs == null) {
logs = new FactionLogs();
}
LinkedList<FactionLogs.FactionLog> recentLogs = logs.getMostRecentLogs().get(type); LinkedList<FactionLogs.FactionLog> recentLogs = logs.getMostRecentLogs().get(type);
if (recentLogs == null) { if (recentLogs == null) recentLogs = Lists.newLinkedList();
recentLogs = Lists.newLinkedList();
}
List<String> lore = Lists.newArrayList("", CC.GreenB + "Recent Logs " + CC.Green + "(" + CC.GreenB + recentLogs.size() + CC.Green + ")"); List<String> lore = Lists.newArrayList("", CC.GreenB + "Recent Logs " + CC.Green + "(" + CC.GreenB + recentLogs.size() + CC.Green + ")");
int added = 0; int added = 0;
Iterator backwars = recentLogs.descendingIterator(); Iterator backwars = recentLogs.descendingIterator();
int logsPerPage = 20;
while (backwars.hasNext()) { while (backwars.hasNext()) {
FactionLogs.FactionLog log = (FactionLogs.FactionLog) backwars.next(); FactionLogs.FactionLog log = (FactionLogs.FactionLog) backwars.next();
if (added >= logsPerPage) { if (added >= logsPerPage) break;
break; String length = log.getLogLine(type, showTimestamps);
}
String length = log.getLogLine(type, this.showTimestamps);
lore.add(" " + CC.Yellow + length); lore.add(" " + CC.Yellow + length);
++added; ++added;
} }
int logSize = recentLogs.size(); int logSize = recentLogs.size();
int logsLeft = logSize - logsPerPage; int logsLeft = logSize - logsPerPage;
if (logsLeft > 0) { if (logsLeft > 0) lore.add(CC.YellowB + logsLeft + CC.Yellow + " more logs...");
lore.add(CC.YellowB + logsLeft + CC.Yellow + " more logs...");
}
lore.add(""); lore.add("");
if (logsLeft > 0) { if (logsLeft > 0) lore.add(CC.Yellow + "Left-Click " + CC.Gray + "to view more logs");
lore.add(CC.Yellow + "Left-Click " + CC.Gray + "to view more logs");
}
lore.add(CC.Yellow + "Right-Click " + CC.Gray + "to toggle timestamps"); lore.add(CC.Yellow + "Right-Click " + CC.Gray + "to toggle timestamps");
this.setItem(index++, (new ClickableItemStack((new ItemBuilder(type.getDisplayMaterial())).name(CC.GreenB + type.getDisplayName()).lore(lore).build())).setClickCallback((click) -> { setItem(index++, (new ClickableItemStack((new ItemBuilder(type.getDisplayMaterial())).name(CC.GreenB + type.getDisplayName()).lore(lore).build())).setClickCallback((click) -> {
click.setCancelled(true); click.setCancelled(true);
if (click.getClick() == ClickType.RIGHT) { if (click.getClick() == ClickType.RIGHT) {
this.showTimestamps = !this.showTimestamps; showTimestamps = !showTimestamps;
this.drawItems(); drawItems();
} else { } else {
if (logsLeft <= 0) { if (logsLeft <= 0) {
this.player.sendMessage(CC.Red + "No extra logs to load."); player.sendMessage(CC.Red + "No extra logs to load.");
return; return;
} }
Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditLogMenu(this.player, this.faction, type)).open(this.player)); Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditLogMenu(player, faction, type)).open(player));
} }
})); }));
} }
@ -96,7 +75,7 @@ public class FAuditMenu extends GUIMenu {
} }
class FAuditLogMenu extends GUIMenu { static class FAuditLogMenu extends GUIMenu {
private Player player; private Player player;
private Faction faction; private Faction faction;
private FLogType logType; private FLogType logType;
@ -111,11 +90,11 @@ public class FAuditMenu extends GUIMenu {
public void drawItems() { public void drawItems() {
FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(faction.getId()); FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(faction.getId());
int perPage = this.logType == FLogType.F_TNT ? 25 : 20; int perPage = logType == FLogType.F_TNT ? 25 : 20;
if (logs != null) { if (logs != null) {
LinkedList<FactionLogs.FactionLog> log = logs.getMostRecentLogs().get(this.logType); LinkedList<FactionLogs.FactionLog> log = logs.getMostRecentLogs().get(logType);
if (log != null) { if (log != null) {
int slot = this.logType == FLogType.F_TNT ? 0 : 3; int slot = logType == FLogType.F_TNT ? 0 : 3;
int pagesToShow = (int)Math.max(1.0D, Math.ceil((double)log.size() / (double)perPage)); int pagesToShow = (int)Math.max(1.0D, Math.ceil((double)log.size() / (double)perPage));
for(int page = 1; page <= pagesToShow; ++page) { for(int page = 1; page <= pagesToShow; ++page) {
@ -131,26 +110,23 @@ public class FAuditMenu extends GUIMenu {
if (i < 0) { if (i < 0) {
break; break;
} }
FactionLogs.FactionLog l = log.get(i); FactionLogs.FactionLog l = log.get(i);
lore.add(" " + CC.Yellow + l.getLogLine(this.logType, this.timeStamp)); lore.add(" " + CC.Yellow + l.getLogLine(logType, timeStamp));
} }
} }
lore.add(""); lore.add("");
lore.add(CC.Gray + "Click to toggle timestamp"); lore.add(CC.Gray + "Click to toggle timestamp");
this.setItem(slot++, (new ClickableItemStack((new ItemBuilder(Material.PAPER)).name(CC.GreenB + "Log #" + page).lore(lore).build())).setClickCallback((e) -> { setItem(slot++, (new ClickableItemStack((new ItemBuilder(Material.PAPER)).name(CC.GreenB + "Log #" + page).lore(lore).build())).setClickCallback((e) -> {
e.setCancelled(true); e.setCancelled(true);
this.timeStamp = !this.timeStamp; timeStamp = !timeStamp;
this.drawItems(); drawItems();
})); }));
} }
} }
} }
setItem(getSize() - 1, (new ClickableItemStack((new ItemBuilder(Material.ARROW)).name(CC.Green + "Previous Page").lore("", CC.Gray + "Click to view previous page!").build())).setClickCallback((event) -> {
this.setItem(this.getSize() - 1, (new ClickableItemStack((new ItemBuilder(Material.ARROW)).name(CC.Green + "Previous Page").lore("", CC.Gray + "Click to view previous page!").build())).setClickCallback((event) -> {
event.setCancelled(true); event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditMenu(this.player, this.faction)).open(this.player)); Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditMenu(player, faction)).open(player));
})); }));
} }
} }

View File

@ -88,12 +88,12 @@ public class FChestListener implements Listener {
return; return;
} }
this.logRemoveItem(currentItem, fplayer, player); logRemoveItem(currentItem, fplayer, player);
} else if (cursorItemType != Material.AIR && !event.isShiftClick()) { } else if (cursorItemType != Material.AIR && !event.isShiftClick()) {
this.logAddItem(cursorItem, fplayer, player); logAddItem(cursorItem, fplayer, player);
} }
} else if (event.isShiftClick() && currentItemType != Material.AIR) { } else if (event.isShiftClick() && currentItemType != Material.AIR) {
this.logAddItem(currentItem, fplayer, player); logAddItem(currentItem, fplayer, player);
} }
} }

View File

@ -13,10 +13,8 @@ import org.bukkit.Bukkit;
import java.io.File; import java.io.File;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import java.util.Timer;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class FLogManager { public class FLogManager {
private Map<String, FactionLogs> factionLogMap = new ConcurrentHashMap<>(); private Map<String, FactionLogs> factionLogMap = new ConcurrentHashMap<>();
@ -41,7 +39,7 @@ public class FLogManager {
logFile.createNewFile(); logFile.createNewFile();
} }
factionLogMap = (Map) JSONUtils.fromJson(logFile, logToken); factionLogMap = (Map<String, FactionLogs>) JSONUtils.fromJson(logFile, logToken);
if (factionLogMap == null) { if (factionLogMap == null) {
factionLogMap = new ConcurrentHashMap<>(); factionLogMap = new ConcurrentHashMap<>();
} }
@ -64,8 +62,6 @@ public class FLogManager {
e.printStackTrace(); e.printStackTrace();
} }
long delay = TimeUnit.SECONDS.toMillis(15L);
long sellDelay = TimeUnit.SECONDS.toMillis(30L);
Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.instance, () -> { Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.instance, () -> {
if (saving) { if (saving) {
Bukkit.getLogger().info("Ignoring saveLogs scheduler due to saving == true!"); Bukkit.getLogger().info("Ignoring saveLogs scheduler due to saving == true!");
@ -100,7 +96,7 @@ public class FLogManager {
} }
if (type != null) { if (type != null) {
Map<LogTimer.TimerSubType, Timer> timers = (Map) logTimer.get(type); Map<LogTimer.TimerSubType, LogTimer.Timer> timers = logTimer.get(type);
if (timers != null && faction != null) { if (timers != null && faction != null) {
logTimer.pushLogs(faction, type); logTimer.pushLogs(faction, type);
} }
@ -133,7 +129,7 @@ public class FLogManager {
try { try {
JSONUtils.saveJSONToFile(logFile, factionLogMap,logToken); JSONUtils.saveJSONToFile(logFile, factionLogMap,logToken);
} catch (Exception e1) { } catch (Exception e1) {
Bukkit.getLogger().info("ERRRO SAVING JSON LOGS: " + e1.getMessage()); Bukkit.getLogger().info("ERROR SAVING JSON LOGS: " + e1.getMessage());
e1.printStackTrace(); e1.printStackTrace();
} }

View File

@ -1,6 +1,8 @@
package com.massivecraft.factions.cmd.audit; package com.massivecraft.factions.cmd.audit;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.XMaterial; import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import org.bukkit.Material; import org.bukkit.Material;
/** /**
@ -31,6 +33,25 @@ public enum FLogType {
return this.displayName; return this.displayName;
} }
/**
* Case insensitive check for action.
*
* @param check
* @return - action
*/
public static FLogType fromString(String check) {
for (FLogType fLogType : values()) {
if (fLogType.displayName.equalsIgnoreCase(check)) {
return fLogType;
}
}
return null;
}
public int getSlot() {
return FactionsPlugin.getInstance().getConfig().getInt("faudit-gui.slots." + this.displayName.toLowerCase());
}
public Material getDisplayMaterial() { public Material getDisplayMaterial() {
return this.displayMaterial; return this.displayMaterial;
} }

View File

@ -18,7 +18,6 @@ import java.util.concurrent.TimeUnit;
public class FactionLogs { public class FactionLogs {
private Map<FLogType, LinkedList<FactionLog>> mostRecentLogs = new ConcurrentHashMap<>(); private Map<FLogType, LinkedList<FactionLog>> mostRecentLogs = new ConcurrentHashMap<>();
public static transient SimpleDateFormat format = new SimpleDateFormat("MM/dd hh:mmaa"); public static transient SimpleDateFormat format = new SimpleDateFormat("MM/dd hh:mmaa");
private static transient int MAX_LOG_SIZE = 60;
public FactionLogs() { public FactionLogs() {
} }
@ -28,7 +27,7 @@ public class FactionLogs {
Bukkit.getLogger().info("INVALID ARGUMENT COUNT MET: " + type.getRequiredArgs() + " REQUIRED: "); Bukkit.getLogger().info("INVALID ARGUMENT COUNT MET: " + type.getRequiredArgs() + " REQUIRED: ");
Thread.dumpStack(); Thread.dumpStack();
} else { } else {
LinkedList<FactionLog> logs = this.mostRecentLogs.computeIfAbsent(type, (lists) -> new LinkedList<>()); LinkedList<FactionLog> logs = mostRecentLogs.computeIfAbsent(type, (lists) -> new LinkedList<>());
logs.add(new FactionLog(System.currentTimeMillis(), Lists.newArrayList(arguments))); logs.add(new FactionLog(System.currentTimeMillis(), Lists.newArrayList(arguments)));
int maxLog = type == FLogType.F_TNT ? 200 : 60; int maxLog = type == FLogType.F_TNT ? 200 : 60;
if (logs.size() > maxLog) { if (logs.size() > maxLog) {
@ -69,16 +68,14 @@ public class FactionLogs {
toRemove.add(logType); toRemove.add(logType);
} }
}); });
toRemove.forEach((rem) -> { toRemove.forEach((rem) -> mostRecentLogs.remove(rem));
LinkedList linkedList = this.mostRecentLogs.remove(rem);
});
} }
public Map<FLogType, LinkedList<FactionLog>> getMostRecentLogs() { public Map<FLogType, LinkedList<FactionLog>> getMostRecentLogs() {
return this.mostRecentLogs; return mostRecentLogs;
} }
public class FactionLog { public static class FactionLog {
private long t; private long t;
private List<String> a; private List<String> a;
@ -88,19 +85,19 @@ public class FactionLogs {
} }
public boolean isExpired(long duration) { public boolean isExpired(long duration) {
return System.currentTimeMillis() - this.t >= duration; return System.currentTimeMillis() - t >= duration;
} }
public String getLogLine(FLogType type, boolean timestamp) { public String getLogLine(FLogType type, boolean timestamp) {
String[] args = this.a.toArray(new String[0]); String[] args = a.toArray(new String[0]);
String timeFormat = ""; String timeFormat = "";
if (timestamp) { if (timestamp) {
timeFormat = FactionLogs.format.format(this.t); timeFormat = FactionLogs.format.format(t);
if (timeFormat.startsWith("0")) { if (timeFormat.startsWith("0")) {
timeFormat = timeFormat.substring(1); timeFormat = timeFormat.substring(1);
} }
} }
return String.format(ChatColor.translateAlternateColorCodes('&', type.getMsg()), (String[])args) + (timestamp ? ChatColor.GRAY + " - " + timeFormat : ""); return String.format(ChatColor.translateAlternateColorCodes('&', type.getMsg()), args) + (timestamp ? ChatColor.GRAY + " - " + timeFormat : "");
} }
} }
} }

View File

@ -33,7 +33,6 @@ public class LogTimer extends ConcurrentHashMap<LogTimer.TimerType, Map<LogTimer
} }
public void pushLogs(Faction faction, LogTimer.TimerType type) { public void pushLogs(Faction faction, LogTimer.TimerType type) {
StringBuilder soldString = new StringBuilder();
forEach((timerType, map) -> { forEach((timerType, map) -> {
if (timerType == type) { if (timerType == type) {
if (timerType == LogTimer.TimerType.SPAWNER_EDIT) { if (timerType == LogTimer.TimerType.SPAWNER_EDIT) {
@ -44,18 +43,18 @@ public class LogTimer extends ConcurrentHashMap<LogTimer.TimerType, Map<LogTimer
currentCounts.forEach((data, ints) -> { currentCounts.forEach((data, ints) -> {
EntityType types = EntityType.fromId(data.getData()); EntityType types = EntityType.fromId(data.getData());
if (types == null) { if (types == null) {
Bukkit.getLogger().info("Unable to find EntityType for " + data.getData() + " for " + subTimer + " for fac " + this.factionId + "!"); Bukkit.getLogger().info("Unable to find EntityType for " + data.getData() + " for " + subTimer + " for fac " + factionId + "!");
} else { } else {
entityCounts.computeIfAbsent(types, (e) -> new AtomicInteger(0)).addAndGet(ints.get()); entityCounts.computeIfAbsent(types, (e) -> new AtomicInteger(0)).addAndGet(ints.get());
} }
}); });
entityCounts.forEach((entityType, count) -> FactionsPlugin.instance.getFlogManager().log(faction, FLogType.SPAWNER_EDIT, this.username, subTimer == TimerSubType.SPAWNER_BREAK ? "broke" : "placed", count.get() + "x", StringUtils.capitaliseAllWords(entityType.name().toLowerCase().replace("_", " ")))); entityCounts.forEach((entityType, count) -> FactionsPlugin.instance.getFlogManager().log(faction, FLogType.SPAWNER_EDIT, username, subTimer == TimerSubType.SPAWNER_BREAK ? "broke" : "placed", count.get() + "x", StringUtils.capitaliseAllWords(entityType.name().toLowerCase().replace("_", " "))));
} }
}); });
} }
} }
}); });
this.remove(type); remove(type);
} }
public String getFactionId() { public String getFactionId() {

View File

@ -53,10 +53,9 @@ public class CmdSetGuild extends FCommand {
if (guildId != null && !guildId.equalsIgnoreCase("null")) { if (guildId != null && !guildId.equalsIgnoreCase("null")) {
Guild guild = null; Guild guild = null;
try { try {
guild = jda.getGuildById(guildId); guild = jda.getGuildById(guildId);
} catch (NumberFormatException var7) { } catch (NumberFormatException e) {
} }
if (guild == null) { if (guild == null) {

View File

@ -189,9 +189,7 @@ public class Discord {
* @return Boolean * @return Boolean
*/ */
public static Boolean isInMainGuild(User u) { public static Boolean isInMainGuild(User u) {
if (mainGuild == null) { if (mainGuild == null) return false;
return false;
}
return mainGuild.getMember(u) == null ? Boolean.FALSE : Boolean.TRUE; return mainGuild.getMember(u) == null ? Boolean.FALSE : Boolean.TRUE;
} }

View File

@ -66,9 +66,7 @@ public class DiscordListener extends ListenerAdapter {
public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) { public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) {
Integer i; Integer i;
if (e.getAuthor().isBot()) { if (e.getAuthor().isBot()) return;
return;
}
try { try {
i = Integer.valueOf(e.getMessage().getContentDisplay()); i = Integer.valueOf(e.getMessage().getContentDisplay());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
@ -89,17 +87,13 @@ public class DiscordListener extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) { public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
try { try {
if (event.getMessage().isWebhookMessage() || event.getAuthor().isBot()) { if (event.getMessage().isWebhookMessage() || event.getAuthor().isBot()) return;
return;
}
String prefix = DiscordListener.guilds.getGuildById(event.getGuild().getId()).getPrefix(); String prefix = DiscordListener.guilds.getGuildById(event.getGuild().getId()).getPrefix();
if (prefix == null || prefix.isEmpty()) { if (prefix == null || prefix.isEmpty()) {
prefix = "."; prefix = ".";
} }
String content = event.getMessage().getContentRaw(); String content = event.getMessage().getContentRaw();
if (!content.startsWith(prefix) && !content.startsWith(event.getGuild().getSelfMember().getAsMention())) { if (!content.startsWith(prefix) && !content.startsWith(event.getGuild().getSelfMember().getAsMention())) return;
return;
}
if (content.startsWith(prefix + "help") || content.startsWith(event.getGuild().getSelfMember().getAsMention() + " help")) { if (content.startsWith(prefix + "help") || content.startsWith(event.getGuild().getSelfMember().getAsMention() + " help")) {
this.help(event, content, prefix); this.help(event, content, prefix);
} else if (content.startsWith(prefix + "stats")) { } else if (content.startsWith(prefix + "stats")) {
@ -130,9 +124,7 @@ public class DiscordListener extends ListenerAdapter {
this.settings(event); this.settings(event);
} }
} catch (PermissionException exception) { } catch (PermissionException exception) {
if (!event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_READ, Permission.MESSAGE_WRITE)) { if (!event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_READ, Permission.MESSAGE_WRITE)) return;
return;
}
event.getChannel().sendMessage((":x: Missing permission, `" + exception.getPermission().toString() + "`")).queue(); event.getChannel().sendMessage((":x: Missing permission, `" + exception.getPermission().toString() + "`")).queue();
} }
} }
@ -143,33 +135,25 @@ public class DiscordListener extends ListenerAdapter {
private Faction getFactionWithWarning(TextChannel textChannel) { private Faction getFactionWithWarning(TextChannel textChannel) {
Faction faction = this.getFaction(textChannel.getGuild()); Faction faction = this.getFaction(textChannel.getGuild());
if (faction == null) { if (faction == null) textChannel.sendMessage((":x: This guild isn't linked to a faction, use `/f setguild " + textChannel.getGuild().getId() + "` in game")).queue();
textChannel.sendMessage((":x: This guild isn't linked to a faction, use `/f setguild " + textChannel.getGuild().getId() + "` in game")).queue();
}
return faction; return faction;
} }
private boolean cantAccessPermissionWithWarning(TextChannel textChannel, Member member) { private boolean cantAccessPermissionWithWarning(TextChannel textChannel, Member member) {
boolean can = member.hasPermission(Permission.MANAGE_SERVER); boolean can = member.hasPermission(Permission.MANAGE_SERVER);
if (!can) { if (!can) textChannel.sendMessage(":x: You need to have the Manage Server permission to do that").queue();
textChannel.sendMessage(":x: You need to have the Manage Server permission to do that").queue();
}
return !can; return !can;
} }
private boolean canAccessRole(Faction faction, Member member) { private boolean canAccessRole(Faction faction, Member member) {
if (member.hasPermission(Permission.MANAGE_SERVER)) { if (member.hasPermission(Permission.MANAGE_SERVER)) return true;
return true;
}
Role role = member.getGuild().getRoleById(faction.getMemberRoleId()); Role role = member.getGuild().getRoleById(faction.getMemberRoleId());
return role != null && member.getRoles().stream().anyMatch(r -> r.getPosition() >= role.getPosition()); return role != null && member.getRoles().stream().anyMatch(r -> r.getPosition() >= role.getPosition());
} }
private boolean cantAccessRoleWithWarning(TextChannel textChannel, Faction faction, Member member) { private boolean cantAccessRoleWithWarning(TextChannel textChannel, Faction faction, Member member) {
boolean can = this.canAccessRole(faction, member); boolean can = this.canAccessRole(faction, member);
if (!can) { if (!can) textChannel.sendMessage(":x: You don't have a faction member role").queue();
textChannel.sendMessage(":x: You don't have a faction member role").queue();
}
return !can; return !can;
} }
@ -261,9 +245,7 @@ public class DiscordListener extends ListenerAdapter {
} }
private void setPrefix(GuildMessageReceivedEvent event, String content) { private void setPrefix(GuildMessageReceivedEvent event, String content) {
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) { if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
return;
}
String[] split = content.split(" "); String[] split = content.split(" ");
if (split.length != 3) { if (split.length != 3) {
event.getChannel().sendMessage((":x: Usage, `@" + event.getGuild().getSelfMember().getEffectiveName() + " setprefix <prefix>`")).queue(); event.getChannel().sendMessage((":x: Usage, `@" + event.getGuild().getSelfMember().getEffectiveName() + " setprefix <prefix>`")).queue();
@ -281,12 +263,8 @@ public class DiscordListener extends ListenerAdapter {
private void setFChatChannel(GuildMessageReceivedEvent event) { private void setFChatChannel(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels(); List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels();
if (mentionedChannels.isEmpty()) { if (mentionedChannels.isEmpty()) {
faction.setFactionChatChannelId(null); faction.setFactionChatChannelId(null);
@ -304,12 +282,8 @@ public class DiscordListener extends ListenerAdapter {
private void setWallNotifyChannel(GuildMessageReceivedEvent event) { private void setWallNotifyChannel(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels(); List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels();
if (mentionedChannels.isEmpty()) { if (mentionedChannels.isEmpty()) {
faction.setWallNotifyChannelId(null); faction.setWallNotifyChannelId(null);
@ -327,12 +301,8 @@ public class DiscordListener extends ListenerAdapter {
private void setBufferNotifyChannel(GuildMessageReceivedEvent event) { private void setBufferNotifyChannel(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels(); List<TextChannel> mentionedChannels = event.getMessage().getMentionedChannels();
if (mentionedChannels.isEmpty()) { if (mentionedChannels.isEmpty()) {
faction.setBufferNotifyChannelId(null); faction.setBufferNotifyChannelId(null);
@ -350,9 +320,7 @@ public class DiscordListener extends ListenerAdapter {
private void setWeewooChannel(GuildMessageReceivedEvent event) { private void setWeewooChannel(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return;
}
if (!event.getMember().hasPermission(Permission.MANAGE_SERVER)) { if (!event.getMember().hasPermission(Permission.MANAGE_SERVER)) {
event.getChannel().sendMessage(":x: You need to have the Manage Server permission to do that").queue(); event.getChannel().sendMessage(":x: You need to have the Manage Server permission to do that").queue();
return; return;
@ -374,12 +342,8 @@ public class DiscordListener extends ListenerAdapter {
private void setNotifyFormat(GuildMessageReceivedEvent event, String content, String prefix) { private void setNotifyFormat(GuildMessageReceivedEvent event, String content, String prefix) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null)return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
if (!content.contains(" ")) { if (!content.contains(" ")) {
event.getChannel().sendMessage((":x: Usage, `" + prefix + "setnotifyformat <format>` (%type%)")).queue(); event.getChannel().sendMessage((":x: Usage, `" + prefix + "setnotifyformat <format>` (%type%)")).queue();
return; return;
@ -397,12 +361,8 @@ public class DiscordListener extends ListenerAdapter {
private void setWeewooFormat(GuildMessageReceivedEvent event, String content, String prefix) { private void setWeewooFormat(GuildMessageReceivedEvent event, String content, String prefix) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
if (!content.contains(" ")) { if (!content.contains(" ")) {
event.getChannel().sendMessage((":x: Usage, `" + prefix + "setweewooformat <format>`")).queue(); event.getChannel().sendMessage((":x: Usage, `" + prefix + "setweewooformat <format>`")).queue();
return; return;
@ -420,12 +380,8 @@ public class DiscordListener extends ListenerAdapter {
private void setMemberRole(GuildMessageReceivedEvent event, String content, String prefix) { private void setMemberRole(GuildMessageReceivedEvent event, String content, String prefix) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) return;
}
if (this.cantAccessPermissionWithWarning(event.getChannel(), event.getMember())) {
return;
}
List<String> split = new ArrayList<>(Arrays.asList(content.split(" "))); List<String> split = new ArrayList<>(Arrays.asList(content.split(" ")));
if (split.size() < 2) { if (split.size() < 2) {
event.getChannel().sendMessage((":x: Usage, `" + prefix + "setmemberrole <@role/role name/role id>`")).queue(); event.getChannel().sendMessage((":x: Usage, `" + prefix + "setmemberrole <@role/role name/role id>`")).queue();
@ -452,12 +408,9 @@ public class DiscordListener extends ListenerAdapter {
private void checkLeaderboard(GuildMessageReceivedEvent event) { private void checkLeaderboard(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) return;
}
if (this.cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) {
return;
}
Map<UUID, Integer> players = new HashMap<>(); Map<UUID, Integer> players = new HashMap<>();
for (Map.Entry<UUID, Integer> entry : faction.getPlayerWallCheckCount().entrySet()) { for (Map.Entry<UUID, Integer> entry : faction.getPlayerWallCheckCount().entrySet()) {
players.put(entry.getKey(), entry.getValue()); players.put(entry.getKey(), entry.getValue());
@ -485,12 +438,8 @@ public class DiscordListener extends ListenerAdapter {
private void weewoo(GuildMessageReceivedEvent event, String content, String prefix) { private void weewoo(GuildMessageReceivedEvent event, String content, String prefix) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) return;
}
if (this.cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) {
return;
}
if (!content.contains(" ")) { if (!content.contains(" ")) {
event.getChannel().sendMessage((":x: Usage, `" + prefix + "weewoo <start/stop>`")).queue(); event.getChannel().sendMessage((":x: Usage, `" + prefix + "weewoo <start/stop>`")).queue();
return; return;
@ -508,9 +457,7 @@ public class DiscordListener extends ListenerAdapter {
String discordChannelId = faction.getWeeWooChannelId(); String discordChannelId = faction.getWeeWooChannelId();
if (discordChannelId != null && !discordChannelId.isEmpty()) { if (discordChannelId != null && !discordChannelId.isEmpty()) {
TextChannel textChannel = event.getJDA().getTextChannelById(discordChannelId); TextChannel textChannel = event.getJDA().getTextChannelById(discordChannelId);
if (textChannel == null) { if (textChannel == null) return;
return;
}
textChannel.sendMessage(TL.WEEWOO_STARTED_DISCORD.format(event.getAuthor().getAsTag())).queue(); textChannel.sendMessage(TL.WEEWOO_STARTED_DISCORD.format(event.getAuthor().getAsTag())).queue();
} }
} else if (arguments.get(1).equalsIgnoreCase("stop")) { } else if (arguments.get(1).equalsIgnoreCase("stop")) {
@ -524,9 +471,7 @@ public class DiscordListener extends ListenerAdapter {
String discordChannelId = faction.getWeeWooChannelId(); String discordChannelId = faction.getWeeWooChannelId();
if (discordChannelId != null && !discordChannelId.isEmpty()) { if (discordChannelId != null && !discordChannelId.isEmpty()) {
TextChannel textChannel = event.getJDA().getTextChannelById(discordChannelId); TextChannel textChannel = event.getJDA().getTextChannelById(discordChannelId);
if (textChannel == null) { if (textChannel == null) return;
return;
}
textChannel.sendMessage(TL.WEEWOO_STOPPED_DISCORD.format(event.getAuthor().getAsTag())).queue(); textChannel.sendMessage(TL.WEEWOO_STOPPED_DISCORD.format(event.getAuthor().getAsTag())).queue();
} }
} else { } else {
@ -536,12 +481,8 @@ public class DiscordListener extends ListenerAdapter {
private void settings(GuildMessageReceivedEvent event) { private void settings(GuildMessageReceivedEvent event) {
Faction faction = this.getFactionWithWarning(event.getChannel()); Faction faction = this.getFactionWithWarning(event.getChannel());
if (faction == null) { if (faction == null) return;
return; if (cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) return;
}
if (this.cantAccessRoleWithWarning(event.getChannel(), faction, event.getMember())) {
return;
}
int wallCheck = faction.getWallCheckMinutes(); int wallCheck = faction.getWallCheckMinutes();
int bufferCheck = faction.getBufferCheckMinutes(); int bufferCheck = faction.getBufferCheckMinutes();
String wallChannel = faction.getWallNotifyChannelId(); String wallChannel = faction.getWallNotifyChannelId();

View File

@ -55,7 +55,7 @@ public class DiscordSetupAttempt {
* @return String with formatted time difference * @return String with formatted time difference
*/ */
public String getDifferentialFormatted() { public String getDifferentialFormatted() {
Integer timeIndex = 0; int timeIndex = 0;
//Milliseconds //Milliseconds
Long inProcessTime = getDifferentialTime(); Long inProcessTime = getDifferentialTime();
if (inProcessTime >= 1000) { if (inProcessTime >= 1000) {

View File

@ -37,16 +37,10 @@ public class FactionChatHandler extends ListenerAdapter {
public static void sendMessage(FactionsPlugin plugin, Faction faction, UUID uuid, String username, String message) { public static void sendMessage(FactionsPlugin plugin, Faction faction, UUID uuid, String username, String message) {
String factionsChatChannelId = faction.getFactionChatChannelId(); String factionsChatChannelId = faction.getFactionChatChannelId();
String messageWithMentions = null; String messageWithMentions = null;
if (factionsChatChannelId == null || factionsChatChannelId.isEmpty()) { if (factionsChatChannelId == null || factionsChatChannelId.isEmpty()) return;
return; if (Discord.jda == null) return;
}
if (Discord.jda == null) {
return;
}
TextChannel textChannel = Discord.jda.getTextChannelById(factionsChatChannelId); TextChannel textChannel = Discord.jda.getTextChannelById(factionsChatChannelId);
if (textChannel == null) { if (textChannel == null) return;
return;
}
if (!textChannel.getGuild().getSelfMember().hasPermission(textChannel, Permission.MANAGE_WEBHOOKS)) { if (!textChannel.getGuild().getSelfMember().hasPermission(textChannel, Permission.MANAGE_WEBHOOKS)) {
textChannel.sendMessage("Missing `Manage Webhooks` permission in this channel").queue(); textChannel.sendMessage("Missing `Manage Webhooks` permission in this channel").queue();
return; return;
@ -80,7 +74,6 @@ public class FactionChatHandler extends ListenerAdapter {
} }
if (mention.toString().contains("#")) { if (mention.toString().contains("#")) {
String[] mentionA = mention.toString().replace(" @", "").split("#"); String[] mentionA = mention.toString().replace(" @", "").split("#");
for (User u : Discord.jda.getUsersByName(mentionA[0], false)) { for (User u : Discord.jda.getUsersByName(mentionA[0], false)) {
if (u.getDiscriminator().equals(mentionA[1])) { if (u.getDiscriminator().equals(mentionA[1])) {
for (Integer l : ii) { for (Integer l : ii) {
@ -112,13 +105,10 @@ public class FactionChatHandler extends ListenerAdapter {
@Override @Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) { public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
if (event.isWebhookMessage() || event.getAuthor().isBot()) { if (event.isWebhookMessage() || event.getAuthor().isBot()) return;
return;
}
Faction faction = Factions.getInstance().getAllFactions().stream().filter(f -> event.getChannel().getId().equals(f.getFactionChatChannelId())).findAny().orElse(null); Faction faction = Factions.getInstance().getAllFactions().stream().filter(f -> event.getChannel().getId().equals(f.getFactionChatChannelId())).findAny().orElse(null);
if (faction == null) { if (faction == null) return;
return;
}
String content = event.getMessage().getContentDisplay(); String content = event.getMessage().getContentDisplay();
String message = (content.length() > 500) ? content.substring(0, 500) : content; String message = (content.length() > 500) ? content.substring(0, 500) : content;
FancyMessage fancyMessage = new FancyMessage(); FancyMessage fancyMessage = new FancyMessage();

View File

@ -6,10 +6,12 @@ package com.massivecraft.factions.util;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.massivecraft.factions.cmd.audit.FactionLogs;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.io.*; import java.io.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Map;
public class JSONUtils { public class JSONUtils {
public static Gson gson = (new GsonBuilder()).enableComplexMapKeySerialization().create(); public static Gson gson = (new GsonBuilder()).enableComplexMapKeySerialization().create();

View File

@ -0,0 +1,11 @@
package com.massivecraft.factions.util.exceptions;
/**
* @author Saser
*/
public abstract class SaberException extends Exception {
public SaberException(String message) {
super(message);
}
}

View File

@ -0,0 +1,12 @@
package com.massivecraft.factions.util.exceptions.impl;
import com.massivecraft.factions.util.exceptions.SaberException;
/**
* @author Saser
*/
public class DiscordException extends SaberException {
public DiscordException(String message) {
super(message);
}
}

View File

@ -66,7 +66,6 @@ public enum PermissableAction {
return permissableAction; return permissableAction;
} }
} }
return null; return null;
} }

View File

@ -1269,6 +1269,41 @@ fupgrades:
slots: slots:
- 4 - 4
############################################################
# +------------------------------------------------------+ #
# | Faction Audit | #
# +------------------------------------------------------+ #
############################################################
faudit-gui:
slots:
invites: 0
bans: 1
chunk_claims: 2
perm_edit_defaults: 3
bank_edit: 4
fchest_edit: 5
relation_change: 6
ftag_edit: 7
fdesc_edit: 8
role_perm_edit: 9
spawner_edit: 10
rank_edit: 11
f_tnt: 12
materials:
invites: 0
bans: 1
chunk_claims: 2
perm_edit_defaults: 3
bank_edit: 4
fchest_edit: 5
relation_change: 6
ftag_edit: 7
fdesc_edit: 8
role_perm_edit: 9
spawner_edit: 10
rank_edit: 11
f_tnt: 12
############################################################ ############################################################
# +------------------------------------------------------+ # # +------------------------------------------------------+ #
# | Faction Banners | # # | Faction Banners | #