diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java index 2c7bbc05..26b50b2d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -57,7 +57,7 @@ public class CmdAdmin extends FCommand { return; } - if(fyou.isAlt()){ + if (fyou.isAlt()) { return; } @@ -90,7 +90,7 @@ public class CmdAdmin extends FCommand { FactionsPlugin.instance.getFlogManager().log(targetFaction, FLogType.RANK_EDIT, context.fPlayer.getName(), fyou.getName(), ChatColor.RED + "Admin"); // Inform all players - if(FactionsPlugin.instance.getConfig().getBoolean("faction-leader-broadcast")) { + if (FactionsPlugin.instance.getConfig().getBoolean("faction-leader-broadcast")) { for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java b/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java index 7b453a49..bd7df7b6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java @@ -8,65 +8,60 @@ import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; -public class CmdCheckpoint extends FCommand -{ +public class CmdCheckpoint extends FCommand { - /** - * @author Illyria Team - */ + /** + * @author Illyria Team + */ - public CmdCheckpoint() - { - super(); - this.aliases.addAll(Aliases.checkpoint); + public CmdCheckpoint() { + super(); + this.aliases.addAll(Aliases.checkpoint); - this.optionalArgs.put("set", ""); + this.optionalArgs.put("set", ""); - this.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT).playerOnly().memberOnly().build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT).playerOnly().memberOnly().build(); + } - @Override + @Override public void perform(CommandContext context) { if (!FactionsPlugin.getInstance().getConfig().getBoolean("checkpoints.Enabled")) { context.msg(TL.COMMAND_CHECKPOINT_DISABLED); return; } if (context.args.size() == 1 && context.args.get(0).equalsIgnoreCase("set")) { - if (context.fPlayer.getRole() == Role.LEADER) - { - FLocation myLocation = new FLocation(context.player.getLocation()); - Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); - if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { - context.faction.setCheckpoint(context.player.getLocation()); - context.msg(TL.COMMAND_CHECKPOINT_SET); - return; - } - } else { - context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); + if (context.fPlayer.getRole() == Role.LEADER) { + FLocation myLocation = new FLocation(context.player.getLocation()); + Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); + if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { + context.faction.setCheckpoint(context.player.getLocation()); + context.msg(TL.COMMAND_CHECKPOINT_SET); return; } - - PermissableAction action = PermissableAction.SETWARP; - Access access = context.faction.getAccess(context.fPlayer, action); - if (access == Access.DENY) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, action.getName()); + } else { + context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); return; } - else - { - FLocation myLocation = new FLocation(context.player.getLocation()); - Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); - if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { - context.faction.setCheckpoint(context.player.getLocation()); - context.msg(TL.COMMAND_CHECKPOINT_SET); - return; - }else { + + PermissableAction action = PermissableAction.SETWARP; + Access access = context.faction.getAccess(context.fPlayer, action); + if (access == Access.DENY) { + context.msg(TL.GENERIC_FPERM_NOPERMISSION, action.getName()); + return; + } else { + FLocation myLocation = new FLocation(context.player.getLocation()); + Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); + if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { + context.faction.setCheckpoint(context.player.getLocation()); + context.msg(TL.COMMAND_CHECKPOINT_SET); + return; + } else { context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); return; } } } - + if (context.faction.getCheckpoint() == null) { context.msg(TL.COMMAND_CHECKPOINT_NOT_SET); return; @@ -85,9 +80,8 @@ public class CmdCheckpoint extends FCommand } } - @Override - public TL getUsageTranslation() - { - return TL.COMMAND_CHECKPOINT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHECKPOINT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java index 6fbac352..1abd857e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java @@ -55,7 +55,7 @@ public class CmdColeader extends FCommand { return; } - if(you.isAlt()){ + if (you.isAlt()) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java index c160163e..0e2765f2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -54,7 +54,7 @@ public class CmdCreate extends FCommand { return; } - if(Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "createCooldown") && !context.fPlayer.isAdminBypassing()){ + if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "createCooldown") && !context.fPlayer.isAdminBypassing()) { context.msg(TL.COMMAND_COOLDOWN); return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java index f4252194..08ade94c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -3,10 +3,7 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.struct.Role; -import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; import mkremins.fanciful.FancyMessage; @@ -56,6 +53,7 @@ public class CmdDeinvite extends FCommand { context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction)); } + @Override public TL getUsageTranslation() { return TL.COMMAND_DEINVITE_DESCRIPTION; diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index 6010810d..1b3179c8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -70,7 +70,7 @@ public class CmdDisband extends FCommand { return; } - if(Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "disbandCooldown") && !context.fPlayer.isAdminBypassing()){ + if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "disbandCooldown") && !context.fPlayer.isAdminBypassing()) { context.msg(TL.COMMAND_COOLDOWN); return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java index d3d54af7..9c3d8d73 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java @@ -19,6 +19,7 @@ import java.util.concurrent.ConcurrentHashMap; public class CmdFly extends FCommand { + public static final boolean fly = FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight"); /** * @author FactionsUUID Team */ @@ -27,8 +28,6 @@ public class CmdFly extends FCommand { public static ConcurrentHashMap flyMap = new ConcurrentHashMap<>(); public static BukkitTask particleTask = null; - public static final boolean fly = FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight"); - public CmdFly() { super(); @@ -65,25 +64,25 @@ public class CmdFly extends FCommand { if (toFac != fme.getFaction()) { if (!me.hasPermission(Permission.FLY_WILDERNESS.node) && toFac.isWilderness() || !me.hasPermission(Permission.FLY_SAFEZONE.node) && toFac.isSafeZone() || !me.hasPermission(Permission.FLY_WARZONE.node) && toFac.isWarZone()) { - if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); return false; } Access access = toFac.getAccess(fme, PermissableAction.FLY); if ((!(me.hasPermission(Permission.FLY_ENEMY.node) || access == Access.ALLOW)) && toFac.getRelationTo(fme.getFaction()) == Relation.ENEMY) { - if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); return false; } if (!(me.hasPermission(Permission.FLY_ALLY.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.ALLY) { - if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); return false; } if (!(me.hasPermission(Permission.FLY_TRUCE.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.TRUCE) { - if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); return false; } if (!(me.hasPermission(Permission.FLY_NEUTRAL.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.NEUTRAL && !toFac.isSystemFaction()) { - if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); return false; } return me.hasPermission(Permission.FLY_FLY.node) && (access != Access.DENY || toFac.isSystemFaction()); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFriendlyFire.java b/src/main/java/com/massivecraft/factions/cmd/CmdFriendlyFire.java index 1e35c32c..c47e23f2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFriendlyFire.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFriendlyFire.java @@ -11,7 +11,7 @@ import com.massivecraft.factions.zcore.util.TL; */ public class CmdFriendlyFire extends FCommand { - public CmdFriendlyFire(){ + public CmdFriendlyFire() { super(); this.aliases.addAll(Aliases.friendlyFire); @@ -23,12 +23,12 @@ public class CmdFriendlyFire extends FCommand { @Override public void perform(CommandContext context) { - if(!Conf.friendlyFireFPlayersCommand){ + if (!Conf.friendlyFireFPlayersCommand) { context.msg(TL.GENERIC_DISABLED, "friendly fire"); return; } - if(context.fPlayer.hasFriendlyFire()){ + if (context.fPlayer.hasFriendlyFire()) { context.fPlayer.setFriendlyFire(false); context.msg(TL.COMMAND_FRIENDLY_FIRE_TOGGLE_OFF); } else { diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java index f6656197..df0e182b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -9,7 +9,6 @@ import com.massivecraft.factions.util.CC; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; import mkremins.fanciful.FancyMessage; -import org.bukkit.ChatColor; public class CmdInvite extends FCommand { @@ -61,9 +60,9 @@ public class CmdInvite extends FCommand { if (target.isOnline()) { // Tooltips, colors, and commands only apply to the string immediately before it. FancyMessage message = new FancyMessage(TL.COMMAND_INVITE_INVITEDYOU.toString() - .replace("%1$s", context.fPlayer.describeTo(target, true)) - .replace("%2$s", context.faction.getTag()) - .replaceAll("&", "§")) + .replace("%1$s", context.fPlayer.describeTo(target, true)) + .replace("%2$s", context.faction.getTag()) + .replaceAll("&", "§")) .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); message.send(target.getPlayer()); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java index 87731bc3..71b01bb1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -1,19 +1,12 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.*; -import com.massivecraft.factions.cmd.audit.FLogType; -import com.massivecraft.factions.discord.Discord; import com.massivecraft.factions.event.FPlayerJoinEvent; import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.util.CC; import com.massivecraft.factions.zcore.frame.fupgrades.UpgradeType; import com.massivecraft.factions.zcore.util.TL; -import net.dv8tion.jda.core.entities.Member; -import net.dv8tion.jda.core.exceptions.HierarchyException; import org.bukkit.Bukkit; -import java.util.Objects; - public class CmdJoin extends FCommand { public CmdJoin() { diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java index 4d2f36c3..2611ba6d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -1,6 +1,9 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.*; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.event.FPlayerLeaveEvent; import com.massivecraft.factions.struct.Permission; @@ -125,7 +128,7 @@ public class CmdKick extends FCommand { FactionsPlugin.instance.logFactionEvent(toKickFaction, FLogType.INVITES, context.fPlayer.getName(), CC.Red + "kicked", toKick.getName()); toKickFaction.deinvite(toKick); toKick.resetFactionData(); - if(!CmdFly.checkBypassPerms(toKick, toKick.getPlayer(), toKickFaction, false)){ + if (!CmdFly.checkBypassPerms(toKick, toKick.getPlayer(), toKickFaction, false)) { CmdFly.disableFlight(toKick); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java index e75a0fae..3302f9d0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -50,7 +50,7 @@ public class CmdMod extends FCommand { return; } - if(you.isAlt()){ + if (you.isAlt()) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java index 9ad541e1..80efa812 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -39,7 +39,7 @@ public class CmdOpen extends FCommand { String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); - if(Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "openCooldown") && !context.fPlayer.isAdminBypassing()){ + if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "openCooldown") && !context.fPlayer.isAdminBypassing()) { context.msg(TL.COMMAND_COOLDOWN); return; } @@ -51,7 +51,7 @@ public class CmdOpen extends FCommand { Cooldown.setCooldown(fplayer.getPlayer(), "openCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-open")); continue; } - if(FactionsPlugin.getInstance().getConfig().getBoolean("faction-open-broadcast")) return; + if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-open-broadcast")) return; fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.getTag(fplayer.getFaction()), open); } }); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java index af7c1be9..ed7dab6e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -54,7 +54,7 @@ public class CmdTag extends FCommand { return; } - if(Cooldown.isOnCooldown(context.player, "tagCooldown") && !context.fPlayer.isAdminBypassing()){ + if (Cooldown.isOnCooldown(context.player, "tagCooldown") && !context.fPlayer.isAdminBypassing()) { context.msg(TL.COMMAND_COOLDOWN); return; } @@ -72,7 +72,6 @@ public class CmdTag extends FCommand { } - String oldtag = context.faction.getTag(); context.faction.setTag(tag); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java index 442b74aa..eedcc5db 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java @@ -5,7 +5,6 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; -import org.bukkit.Material; public class CmdUnban extends FCommand { diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java index b08febb8..a4fee5f5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java @@ -83,10 +83,13 @@ public class CmdUnclaim extends FCommand { this.stop(); return false; } - return true; } }; + + boolean didUnClaim = unClaim(new FLocation(context.player), context); + if (didUnClaim && !context.fPlayer.canFlyAtLocation()) + context.fPlayer.setFFlying(false, false); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java index 80d4a479..d7d69376 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java @@ -57,14 +57,8 @@ public class CmdUnclaimall extends FCommand { } if (Econ.shouldBeUsed()) { double refund = Econ.calculateTotalLandRefund(target.getLandRounded()); - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { - if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { - return; - } - } else { - if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { - return; - } + if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; } } diff --git a/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java b/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java index de6f5894..059e0c7d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java +++ b/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java @@ -37,7 +37,7 @@ public class CmdGrace extends FCommand { return; } - if(context.args.size() == 1) { + if (context.args.size() == 1) { if (context.sender.hasPermission(String.valueOf(Permission.GRACETOGGLE))) { if (context.argAsString(0).equalsIgnoreCase("on") || context.argAsString(0).equalsIgnoreCase("start")) { FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false); @@ -61,7 +61,7 @@ public class CmdGrace extends FCommand { } } - if(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() <= 0L) { + if (FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() <= 0L) { context.fPlayer.msg(TL.COMMAND_GRACE_DISABLED_NO_FORMAT.toString()); } else { context.fPlayer.msg(TL.COMMAND_GRACE_TIME_REMAINING, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true))); diff --git a/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java b/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java index 37274b7a..88d1c381 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java @@ -41,7 +41,7 @@ public abstract class FRelationCommand extends FCommand { Faction them = context.argAsFaction(0); if (them == null) return; - if(!context.faction.isNormal()) return; + if (!context.faction.isNormal()) return; if (!them.isNormal()) { context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE); diff --git a/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java b/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java index 5fdac43d..55057a0d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java @@ -74,7 +74,7 @@ public class FPromoteCommand extends FCommand { } } - if(target.isAlt()){ + if (target.isAlt()) { return; } diff --git a/src/main/java/com/massivecraft/factions/integration/Econ.java b/src/main/java/com/massivecraft/factions/integration/Econ.java index 659e5643..32c3ef61 100644 --- a/src/main/java/com/massivecraft/factions/integration/Econ.java +++ b/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -48,7 +48,8 @@ public class Econ { } econ = rsp.getProvider(); FactionsPlugin.getInstance().log("Economy integration through Vault plugin successful."); - if (!Conf.econEnabled) FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); + if (!Conf.econEnabled) + FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); //FactionsPlugin.getInstance().cmdBase.cmdHelp.updateHelp(); } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java index 407f1ae2..e2d40262 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.*; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.zcore.persist.MemoryBoard; - import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; @@ -13,1083 +12,927 @@ import org.dynmap.DynmapAPI; import org.dynmap.markers.*; import org.dynmap.utils.TileFlags; -import java.awt.Point; +import java.awt.*; +import java.util.List; import java.util.*; import java.util.Map.Entry; // This source code is a heavily modified version of mikeprimms plugin Dynmap-Factions. -public class EngineDynmap -{ - - /** - * @author FactionsUUID Team - */ - - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // - - public final static int BLOCKS_PER_CHUNK = 16; - - public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; - - public final static String FACTIONS = "factions"; - public final static String FACTIONS_ = FACTIONS + "_"; - - public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; - - public final static String FACTIONS_HOME = FACTIONS_ + "home"; - public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; - - public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; - public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; - - // -------------------------------------------- // - // INSTANCE & CONSTRUCT - // -------------------------------------------- // - - private static final EngineDynmap i = new EngineDynmap(); - public DynmapAPI dynmapApi; - public MarkerAPI markerApi; - public MarkerSet markerset; - - List> polyLine = new ArrayList>(); - - private EngineDynmap() - { - } - - public static EngineDynmap getInstance() - { - return i; - } - - public static String getHtmlPlayerString(Collection playersOfficersList) - { - StringBuilder ret = new StringBuilder(); - for (FPlayer fplayer : playersOfficersList) - { - if (ret.length() > 0) - { - ret.append(", "); - } - ret.append(getHtmlPlayerName(fplayer)); - } - return ret.toString(); - } - - public static String getHtmlPlayerName(FPlayer fplayer) - { - return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; - } - - public static String escapeHtml(String string) - { - if (string == null) - { - return ""; - } - StringBuilder out = new StringBuilder(Math.max(16, string.length())); - for (int i = 0; i < string.length(); i++) - { - char c = string.charAt(i); - if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') - { - out.append("&#").append((int) c).append(';'); - } - else - { - out.append(c); - } - } - return out.toString(); - } - - // Thread Safe / Asynchronous: Yes - public static void info(String msg) - { - System.out.println(DYNMAP_INTEGRATION + msg); - } - - // -------------------------------------------- // - // UPDATE: HOMES - // -------------------------------------------- // - - // Thread Safe / Asynchronous: Yes - public static void severe(String msg) - { - System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); - } - - public void init() - { - Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - - if (dynmap == null || !dynmap.isEnabled()) - { - return; - } - - // Should we even use dynmap? - if (!Conf.dynmapUse) - { - if (this.markerset != null) - { - this.markerset.deleteMarkerSet(); - this.markerset = null; - } - return; - } - - // Shedule non thread safe sync at the end! - Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> - { - - final Map homes = createHomes(); - final Map areas = createAreas(); - final Map polys = createPolys(areas); - final Map> playerSets = createPlayersets(); - - if (!updateCore()) - { - return; - } - - // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. - if (!updateLayer(createLayer())) - { - return; - } - - updateHomes(homes); - updateAreas(areas); - updatePolys(polys); - updatePlayersets(playerSets); - }, 100L, 100L); - } - - // -------------------------------------------- // - // UPDATE: AREAS - // -------------------------------------------- // - - // Thread Safe / Asynchronous: No - public boolean updateCore() - { - // Get DynmapAPI - this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); - if (this.dynmapApi == null) - { - severe("Could not retrieve the DynmapAPI."); - return false; - } - - // Get MarkerAPI - this.markerApi = this.dynmapApi.getMarkerAPI(); - if (this.markerApi == null) - { - severe("Could not retrieve the MarkerAPI."); - return false; - } - - return true; - } - - // Thread Safe / Asynchronous: Yes - public TempMarkerSet createLayer() - { - TempMarkerSet ret = new TempMarkerSet(); - ret.label = Conf.dynmapLayerName; - ret.minimumZoom = Conf.dynmapLayerMinimumZoom; - ret.priority = Conf.dynmapLayerPriority; - ret.hideByDefault = !Conf.dynmapLayerVisible; - return ret; - } - - // Thread Safe / Asynchronous: No - public boolean updateLayer(TempMarkerSet temp) - { - this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); - if (this.markerset == null) - { - this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); - if (this.markerset == null) - { - severe("Could not create the Faction Markerset/Layer"); - return false; - } - } - else - { - temp.update(this.markerset); - } - return true; - } - - // Thread Safe / Asynchronous: Yes - public Map createHomes() - { - Map ret = new HashMap<>(); - - // Loop current factions - for (Faction faction : Factions.getInstance().getAllFactions()) - { - Location ps = faction.getHome(); - if (ps == null) - { - continue; - } - - DynmapStyle style = getStyle(faction); - - String markerId = FACTIONS_HOME_ + faction.getId(); - - TempMarker temp = new TempMarker(); - temp.label = ChatColor.stripColor(faction.getTag()); - temp.world = ps.getWorld().toString(); - temp.x = ps.getX(); - temp.y = ps.getY(); - temp.z = ps.getZ(); - temp.iconName = style.getHomeMarker(); - temp.description = getDescription(faction); - - ret.put(markerId, temp); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - // This method places out the faction home markers into the factions markerset. - public void updateHomes(Map homes) - { - // Put all current faction markers in a map - Map markers = new HashMap<>(); - for (Marker marker : this.markerset.getMarkers()) - { - markers.put(marker.getMarkerID(), marker); - } - - // Loop homes - for (Entry entry : homes.entrySet()) - { - String markerId = entry.getKey(); - TempMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - Marker marker = markers.remove(markerId); - if (marker == null) - { - marker = temp.create(this.markerApi, this.markerset, markerId); - marker = temp.create(this.markerApi, this.markerset, markerId); - if (marker == null) - { - EngineDynmap.severe("Could not get/create the home marker " + markerId); - } - } - else - { - temp.update(this.markerApi, marker); - } - } - - // Delete Deprecated Markers - // Only old markers should now be left - for (Marker marker : markers.values()) - { - marker.deleteMarker(); - } - } - - // -------------------------------------------- // - // UPDATE: PLAYERSET - // -------------------------------------------- // - - // Thread Safe: YES - - public Map createPolys(Map areas) - { - Map ret = new HashMap(); - for (Entry entry : areas.entrySet()) - { - String markerID = entry.getKey(); - TempAreaMarker area = entry.getValue(); - - int counter = 0; - for (List points : area.getPolyLine()) - { - markerID = markerID + "_poly_" + counter; - TempPolyLineMarker tempPoly = new TempPolyLineMarker(); - tempPoly.polyLine = points; - tempPoly.lineColor = area.lineColor; - tempPoly.lineOpacity = area.lineOpacity; - tempPoly.lineWeight = area.lineWeight; - tempPoly.world = area.world; - ret.put(markerID, tempPoly); - counter++; - } - } - return ret; - } - - public Map createAreas() - { - Map>> worldFactionChunks = createWorldFactionChunks(); - return createAreas(worldFactionChunks); - } - - // Thread Safe: YES - public Map>> createWorldFactionChunks() - { - // Create map "world name --> faction --> set of chunk coords" - Map>> worldFactionChunks = new HashMap<>(); - - // Note: The board is the world. The board id is the world name. - MemoryBoard board = (MemoryBoard) Board.getInstance(); - - for (Entry entry : board.flocationIds.entrySet()) - { - String world = entry.getKey().getWorldName(); - Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); - - Map> factionChunks = worldFactionChunks.get(world); - if (factionChunks == null) - { - factionChunks = new HashMap<>(); - worldFactionChunks.put(world, factionChunks); - } - - Set factionTerritory = factionChunks.get(chunkOwner); - if (factionTerritory == null) - { - factionTerritory = new HashSet<>(); - factionChunks.put(chunkOwner, factionTerritory); - } - - factionTerritory.add(entry.getKey()); - } - - return worldFactionChunks; - } - - // Thread Safe: YES - public Map createAreas(Map>> worldFactionChunks) - { - Map ret = new HashMap<>(); - - // For each world - for (Entry>> entry : worldFactionChunks.entrySet()) - { - String world = entry.getKey(); - Map> factionChunks = entry.getValue(); - - // For each faction and its chunks in that world - for (Entry> entry1 : factionChunks.entrySet()) - { - Faction faction = entry1.getKey(); - Set chunks = entry1.getValue(); - Map worldFactionMarkers = createAreas(world, faction, chunks); - ret.putAll(worldFactionMarkers); - } - } - - return ret; - } - - // Thread Safe: YES - // Handle specific faction on specific world - // "handle faction on world" - public Map createAreas(String world, Faction faction, Set chunks) - { - Map ret = new HashMap<>(); - - // If the faction is visible ... - if (!isVisible(faction, world)) - { - return ret; - } - - // ... and has any chunks ... - if (chunks.isEmpty()) - { - return ret; - } - - // Index of polygon for given faction - int markerIndex = 0; - - // Create the info window - String description = getDescription(faction); - - // Fetch Style - DynmapStyle style = this.getStyle(faction); - - // Loop through chunks: set flags on chunk map - TileFlags allChunkFlags = new TileFlags(); - LinkedList allChunks = new LinkedList<>(); - for (FLocation chunk : chunks) - { - allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk - allChunks.addLast(chunk); - } - - // Loop through until we don't find more areas - while (allChunks != null) - { - - TileFlags ourChunkFlags = null; - LinkedList ourChunks = null; - LinkedList newChunks = null; - - for (FLocation chunk : allChunks) - { - int chunkX = (int) chunk.getX(); - int chunkZ = (int) chunk.getZ(); - - // If we need to start shape, and this block is not part of one yet - if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) - { - ourChunkFlags = new TileFlags(); // Create map for shape - ourChunks = new LinkedList<>(); - floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape - ourChunks.add(chunk); // Add it to our chunk list - } - // If shape found, and we're in it, add to our node list - else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) - { - ourChunks.add(chunk); - } - // Else, keep it in the list for the next polygon - else - { - if (newChunks == null) - { - newChunks = new LinkedList<>(); - } - newChunks.add(chunk); - } - } - - // Replace list (null if no more to process) - allChunks = newChunks; - if (ourChunkFlags == null) - { - continue; - } - List outputLines = new ArrayList(); - Map lines = new HashMap(); - - if (ourChunks == null) - { - continue; - } - - for (FLocation loc : ourChunks) - { - int x = loc.getChunk().getX(); - int z = loc.getChunk().getZ(); - - TempLine line = new TempLine(new Point(x * 16, z * 16), new Point(x * 16 + 16, z * 16)); - if (lines.containsKey(line)) - { - lines.put(line, lines.get(line) + 1); - } - else - { - lines.put(line, 1); - } - - line = new TempLine(new Point(x * 16 + 16, z * 16), new Point(x * 16 + 16, z * 16 + 16)); - if (lines.containsKey(line)) - { - lines.put(line, lines.get(line) + 1); - } - else - { - lines.put(line, 1); - } - - line = new TempLine(new Point(x * 16 + 16, z * 16 + 16), new Point(x * 16, z * 16 + 16)); - if (lines.containsKey(line)) - { - lines.put(line, lines.get(line) + 1); - } - else - { - lines.put(line, 1); - } - - line = new TempLine(new Point(x * 16, z * 16 + 16), new Point(x * 16, z * 16)); - if (lines.containsKey(line)) - { - lines.put(line, lines.get(line) + 1); - } - else - { - lines.put(line, 1); - } - } - - Iterator> iterator = lines.entrySet().iterator(); - - List lineList = new ArrayList(); - lineList.addAll(lines.keySet()); - - while (iterator.hasNext()) - { - Entry entry = iterator.next(); - if (entry.getValue() > 1) - { - lineList.remove(entry.getKey()); - } - } - - // Find the leftmost MCRWPoint - - TempLine l = null; - for (Iterator it = lineList.iterator(); it.hasNext();) - { - TempLine tl = it.next(); - if (l == null || tl.getP1().x < l.getP1().x) - l = tl; - } - - for (Iterator it = lineList.iterator(); it.hasNext();) - { - TempLine tl = it.next(); - if (tl.getP2().x < l.getP2().x) - l = tl; - } - - outputLines.add(l); - lineList.remove(l); - while (lineList.size() > 0) - { - // MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1); - // MCRWPointWLines.get(targetp); - - TempLine nextLine = null; - for (Iterator it = lineList.iterator(); it.hasNext();) - { - TempLine line = it.next(); - if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) - { - - nextLine = line; - } - - } - - if (nextLine != null) - { - outputLines.add(nextLine); - lineList.remove(nextLine); - l = nextLine; - } - else - { - outputLines.get(outputLines.size() - 1).addAdditionLines(CamScan1(lineList)); - break; - } - - } - List outputPoints = new ArrayList(); - - List polyPoints = new ArrayList(); - - for (int i = 0; i < outputLines.size(); i++) - { - Point p = new Point(outputLines.get(i).getP1().x, outputLines.get(i).getP1().y); - outputPoints.add(p); - polyPoints.add(p); - if (outputLines.get(i).getConnectedLines().size() > 0) - { - - outputPoints.addAll(addRecursivePoints(new Point((int) outputLines.get(i).getP1().x, (int) outputLines.get(i).getP1().y), outputLines.get(i))); - } - p = new Point((int) outputLines.get(i).getP2().x, (int) outputLines.get(i).getP2().y); - outputPoints.add(p); - polyPoints.add(p); - } - polyLine.add(polyPoints); - - // Build information for specific area - double[] x = new double[outputPoints.size()]; - double[] z = new double[outputPoints.size()]; - - for (int i = 0; i < outputPoints.size(); i++) - { - x[i] = outputPoints.get(i).x; - z[i] = outputPoints.get(i).y; - } - - String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; - - TempAreaMarker temp = new TempAreaMarker(); - temp.label = faction.getTag(); - temp.world = world; - temp.x = x; - temp.z = z; - temp.description = description; - - temp.lineColor = style.getLineColor(); - temp.lineOpacity = style.getLineOpacity(); - temp.lineWeight = style.getLineWeight(); - - temp.fillColor = style.getFillColor(); - temp.fillOpacity = style.getFillOpacity(); - - temp.boost = style.getBoost(); - temp.setPolyLine(polyLine); - - ret.put(markerId, temp); - polyLine.clear(); - - markerIndex++; - } - - return ret; - } - - public List addRecursivePoints(Point returnPoint, TempLine line) - { - List ret = new ArrayList(); - boolean shouldReturn = false; - List connectedLines = line.getConnectedLines(); - List polyPoints = new ArrayList(); - for (TempLine line2 : connectedLines) - { - Point p = new Point((int) line2.getP1().x, (int) line2.getP1().y); - ret.add(p); - polyPoints.add(p); - shouldReturn = true; - if (line2.getConnectedLines().size() > 0) - { - ret.addAll(addRecursivePoints(new Point((int) line2.getP1().x, (int) line2.getP1().y), line2)); - } - p = new Point((int) line2.getP2().x, (int) line2.getP2().y); - ret.add(p); - polyPoints.add(p); - - } - if (shouldReturn) - { - ret.add(returnPoint); - } - polyLine.add(polyPoints); - return ret; - } - - private List CamScan1(List lineList) - { - List ret = new ArrayList(); - - // Find the leftmost MCRWPoint - - TempLine l = null; - for (Iterator it = lineList.iterator(); it.hasNext();) - { - - TempLine tl = it.next(); - if (l == null || tl.getP1().x < l.getP1().x) - l = tl; - } - - for (Iterator it = lineList.iterator(); it.hasNext();) - { - TempLine tl = it.next(); - if (tl.getP2().x < l.getP2().x) - l = tl; - } - - ret.add(l); - lineList.remove(l); - while (lineList.size() > 0) - { - // MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1); - // MCRWPointWLines.get(targetp); - - TempLine thisChunkLine = null; - for (Iterator it = lineList.iterator(); it.hasNext();) - { - TempLine line = it.next(); - if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) - { - - thisChunkLine = line; - } - - } - if (thisChunkLine != null) - { - ret.add(thisChunkLine); - lineList.remove(thisChunkLine); - l = thisChunkLine; - } - else - { - // break; - ret.get(ret.size() - 1).addAdditionLines(CamScan1(lineList)); - } - - } - return ret; - } - - // -------------------------------------------- // - // UTIL & SHARED - // -------------------------------------------- // - - public void updatePolys(Map polys) - { - // Map Current - Map markers = new HashMap<>(); - for (PolyLineMarker marker : this.markerset.getPolyLineMarkers()) - { - markers.put(marker.getMarkerID(), marker); - } - - // Loop New - for (Entry entry : polys.entrySet()) - { - String markerId = entry.getKey(); - TempPolyLineMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - PolyLineMarker marker = markers.remove(markerId); - if (marker == null) - { - marker = temp.create(this.markerset, markerId); - if (marker == null) - { - severe("Could not get/create the area marker " + markerId); - } - } - else - { - temp.update(marker); - } - } - - // Only old/outdated should now be left. Delete them. - for (PolyLineMarker marker : markers.values()) - { - marker.deleteMarker(); - } - } - - // Thread Safe: NO - public void updateAreas(Map areas) - { - // Map Current - Map markers = new HashMap<>(); - for (AreaMarker marker : this.markerset.getAreaMarkers()) - { - markers.put(marker.getMarkerID(), marker); - } - - // Loop New - for (Entry entry : areas.entrySet()) - { - String markerId = entry.getKey(); - TempAreaMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - AreaMarker marker = markers.remove(markerId); - if (marker == null) - { - marker = temp.create(this.markerset, markerId); - if (marker == null) - { - severe("Could not get/create the area marker " + markerId); - } - } - else - { - temp.update(marker); - } - } - - // Only old/outdated should now be left. Delete them. - for (AreaMarker marker : markers.values()) - { - marker.deleteMarker(); - } - } - - // Thread Safe / Asynchronous: Yes - public String createPlayersetId(Faction faction) - { - if (faction == null) - { - return null; - } - if (faction.isWilderness()) - { - return null; - } - String factionId = faction.getId(); - if (factionId == null) - { - return null; - } - return FACTIONS_PLAYERSET_ + factionId; - } - - // Thread Safe / Asynchronous: Yes - public Set createPlayerset(Faction faction) - { - if (faction == null) - { - return null; - } - if (faction.isWilderness()) - { - return null; - } - - Set ret = new HashSet<>(); - - for (FPlayer fplayer : faction.getFPlayers()) - { - // NOTE: We add both UUID and name. This might be a good idea for future proofing. - ret.add(fplayer.getId()); - ret.add(fplayer.getName()); - } - - return ret; - } - - // Thread Safe / Asynchronous: Yes - public Map> createPlayersets() - { - if (!Conf.dynmapVisibilityByFaction) - { - return null; - } - - Map> ret = new HashMap<>(); - - for (Faction faction : Factions.getInstance().getAllFactions()) - { - String playersetId = createPlayersetId(faction); - if (playersetId == null) - { - continue; - } - Set playerIds = createPlayerset(faction); - if (playerIds == null) - { - continue; - } - ret.put(playersetId, playerIds); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - public void updatePlayersets(Map> playersets) - { - if (playersets == null) - { - return; - } - - // Remove - for (PlayerSet set : this.markerApi.getPlayerSets()) - { - if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) - { - continue; - } - - // (Null means remove all) - if (playersets.containsKey(set.getSetID())) - { - continue; - } - - set.deleteSet(); - } - - // Add / Update - for (Entry> entry : playersets.entrySet()) - { - // Extract from Entry - String setId = entry.getKey(); - Set playerIds = entry.getValue(); - - // Get Creatively - PlayerSet set = this.markerApi.getPlayerSet(setId); - if (set == null) - { - set = this.markerApi.createPlayerSet(setId, // id - true, // symmetric - playerIds, // players - false // persistent - ); - } - if (set == null) - { - severe("Could not get/create the player set " + setId); - continue; - } - - // Set Content - set.setPlayers(playerIds); - } - } - - // Thread Safe / Asynchronous: Yes - private String getDescription(Faction faction) - { - String ret = "
" + Conf.dynmapDescription + "
"; - - // Name - String name = faction.getTag(); - name = escapeHtml(ChatColor.stripColor(name)); - ret = ret.replace("%name%", name); - - // Description - String description = faction.getDescription(); - description = escapeHtml(ChatColor.stripColor(description)); - ret = ret.replace("%description%", description); - - // Money - - String money = "unavailable"; - if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) - money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); - ret = ret.replace("%money%", money); - - // Players - Set playersList = faction.getFPlayers(); - String playersCount = String.valueOf(playersList.size()); - String players = getHtmlPlayerString(playersList); - - FPlayer playersLeaderObject = faction.getFPlayerAdmin(); - String playersLeader = getHtmlPlayerName(playersLeaderObject); - - ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); - String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); - String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); - - ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); - String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); - String playersModerators = getHtmlPlayerString(playersModeratorsList); - - ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); - String playersNormalsCount = String.valueOf(playersNormalsList.size()); - String playersNormals = getHtmlPlayerString(playersNormalsList); - - ret = ret.replace("%players%", players); - ret = ret.replace("%players.count%", playersCount); - ret = ret.replace("%players.leader%", playersLeader); - ret = ret.replace("%players.admins%", playersCoAdmins); - ret = ret.replace("%players.admins.count%", playersCoAdminsCount); - ret = ret.replace("%players.moderators%", playersModerators); - ret = ret.replace("%players.moderators.count%", playersModeratorsCount); - ret = ret.replace("%players.normals%", playersNormals); - ret = ret.replace("%players.normals.count%", playersNormalsCount); - - return ret; - } - - // Thread Safe / Asynchronous: Yes - private boolean isVisible(Faction faction, String world) - { - if (faction == null) - { - return false; - } - final String factionId = faction.getId(); - if (factionId == null) - { - return false; - } - final String factionName = faction.getTag(); - if (factionName == null) - { - return false; - } - - Set visible = Conf.dynmapVisibleFactions; - Set hidden = Conf.dynmapHiddenFactions; - - if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) - { - return false; - } - - return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); - } - - // Thread Safe / Asynchronous: Yes - public DynmapStyle getStyle(Faction faction) - { - DynmapStyle ret; - - ret = Conf.dynmapFactionStyles.get(faction.getId()); - if (ret != null) - { - return ret; - } - - ret = Conf.dynmapFactionStyles.get(faction.getTag()); - if (ret != null) - { - return ret; - } - - return Conf.dynmapDefaultStyle; - } - - // Find all contiguous blocks, set in target and clear in source - private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) - { - int cnt = 0; - ArrayDeque stack = new ArrayDeque<>(); - stack.push(new int[] { x, y }); - - while (!stack.isEmpty()) - { - int[] nxt = stack.pop(); - x = nxt[0]; - y = nxt[1]; - if (source.getFlag(x, y)) - { // Set in src - source.setFlag(x, y, false); // Clear source - destination.setFlag(x, y, true); // Set in destination - cnt++; - if (source.getFlag(x + 1, y)) - { - stack.push(new int[] { x + 1, y }); - } - if (source.getFlag(x - 1, y)) - { - stack.push(new int[] { x - 1, y }); - } - if (source.getFlag(x, y + 1)) - { - stack.push(new int[] { x, y + 1 }); - } - if (source.getFlag(x, y - 1)) - { - stack.push(new int[] { x, y - 1 }); - } - } - } - return cnt; - } - - enum Direction - { - XPLUS, ZPLUS, XMINUS, ZMINUS - } +public class EngineDynmap { + + /** + * @author FactionsUUID Team + */ + + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // + + public final static int BLOCKS_PER_CHUNK = 16; + + public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; + + public final static String FACTIONS = "factions"; + public final static String FACTIONS_ = FACTIONS + "_"; + + public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; + + public final static String FACTIONS_HOME = FACTIONS_ + "home"; + public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; + + public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; + public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; + + // -------------------------------------------- // + // INSTANCE & CONSTRUCT + // -------------------------------------------- // + + private static final EngineDynmap i = new EngineDynmap(); + public DynmapAPI dynmapApi; + public MarkerAPI markerApi; + public MarkerSet markerset; + + List> polyLine = new ArrayList>(); + + private EngineDynmap() { + } + + public static EngineDynmap getInstance() { + return i; + } + + public static String getHtmlPlayerString(Collection playersOfficersList) { + StringBuilder ret = new StringBuilder(); + for (FPlayer fplayer : playersOfficersList) { + if (ret.length() > 0) { + ret.append(", "); + } + ret.append(getHtmlPlayerName(fplayer)); + } + return ret.toString(); + } + + public static String getHtmlPlayerName(FPlayer fplayer) { + return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; + } + + public static String escapeHtml(String string) { + if (string == null) { + return ""; + } + StringBuilder out = new StringBuilder(Math.max(16, string.length())); + for (int i = 0; i < string.length(); i++) { + char c = string.charAt(i); + if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { + out.append("&#").append((int) c).append(';'); + } else { + out.append(c); + } + } + return out.toString(); + } + + // Thread Safe / Asynchronous: Yes + public static void info(String msg) { + System.out.println(DYNMAP_INTEGRATION + msg); + } + + // -------------------------------------------- // + // UPDATE: HOMES + // -------------------------------------------- // + + // Thread Safe / Asynchronous: Yes + public static void severe(String msg) { + System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); + } + + public void init() { + Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + + if (dynmap == null || !dynmap.isEnabled()) { + return; + } + + // Should we even use dynmap? + if (!Conf.dynmapUse) { + if (this.markerset != null) { + this.markerset.deleteMarkerSet(); + this.markerset = null; + } + return; + } + + // Shedule non thread safe sync at the end! + Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> + { + + final Map homes = createHomes(); + final Map areas = createAreas(); + final Map polys = createPolys(areas); + final Map> playerSets = createPlayersets(); + + if (!updateCore()) { + return; + } + + // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. + if (!updateLayer(createLayer())) { + return; + } + + updateHomes(homes); + updateAreas(areas); + updatePolys(polys); + updatePlayersets(playerSets); + }, 100L, 100L); + } + + // -------------------------------------------- // + // UPDATE: AREAS + // -------------------------------------------- // + + // Thread Safe / Asynchronous: No + public boolean updateCore() { + // Get DynmapAPI + this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); + if (this.dynmapApi == null) { + severe("Could not retrieve the DynmapAPI."); + return false; + } + + // Get MarkerAPI + this.markerApi = this.dynmapApi.getMarkerAPI(); + if (this.markerApi == null) { + severe("Could not retrieve the MarkerAPI."); + return false; + } + + return true; + } + + // Thread Safe / Asynchronous: Yes + public TempMarkerSet createLayer() { + TempMarkerSet ret = new TempMarkerSet(); + ret.label = Conf.dynmapLayerName; + ret.minimumZoom = Conf.dynmapLayerMinimumZoom; + ret.priority = Conf.dynmapLayerPriority; + ret.hideByDefault = !Conf.dynmapLayerVisible; + return ret; + } + + // Thread Safe / Asynchronous: No + public boolean updateLayer(TempMarkerSet temp) { + this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); + if (this.markerset == null) { + this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); + if (this.markerset == null) { + severe("Could not create the Faction Markerset/Layer"); + return false; + } + } else { + temp.update(this.markerset); + } + return true; + } + + // Thread Safe / Asynchronous: Yes + public Map createHomes() { + Map ret = new HashMap<>(); + + // Loop current factions + for (Faction faction : Factions.getInstance().getAllFactions()) { + Location ps = faction.getHome(); + if (ps == null) { + continue; + } + + DynmapStyle style = getStyle(faction); + + String markerId = FACTIONS_HOME_ + faction.getId(); + + TempMarker temp = new TempMarker(); + temp.label = ChatColor.stripColor(faction.getTag()); + temp.world = ps.getWorld().toString(); + temp.x = ps.getX(); + temp.y = ps.getY(); + temp.z = ps.getZ(); + temp.iconName = style.getHomeMarker(); + temp.description = getDescription(faction); + + ret.put(markerId, temp); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + // This method places out the faction home markers into the factions markerset. + public void updateHomes(Map homes) { + // Put all current faction markers in a map + Map markers = new HashMap<>(); + for (Marker marker : this.markerset.getMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop homes + for (Entry entry : homes.entrySet()) { + String markerId = entry.getKey(); + TempMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + Marker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerApi, this.markerset, markerId); + marker = temp.create(this.markerApi, this.markerset, markerId); + if (marker == null) { + EngineDynmap.severe("Could not get/create the home marker " + markerId); + } + } else { + temp.update(this.markerApi, marker); + } + } + + // Delete Deprecated Markers + // Only old markers should now be left + for (Marker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // -------------------------------------------- // + // UPDATE: PLAYERSET + // -------------------------------------------- // + + // Thread Safe: YES + + public Map createPolys(Map areas) { + Map ret = new HashMap(); + for (Entry entry : areas.entrySet()) { + String markerID = entry.getKey(); + TempAreaMarker area = entry.getValue(); + + int counter = 0; + for (List points : area.getPolyLine()) { + markerID = markerID + "_poly_" + counter; + TempPolyLineMarker tempPoly = new TempPolyLineMarker(); + tempPoly.polyLine = points; + tempPoly.lineColor = area.lineColor; + tempPoly.lineOpacity = area.lineOpacity; + tempPoly.lineWeight = area.lineWeight; + tempPoly.world = area.world; + ret.put(markerID, tempPoly); + counter++; + } + } + return ret; + } + + public Map createAreas() { + Map>> worldFactionChunks = createWorldFactionChunks(); + return createAreas(worldFactionChunks); + } + + // Thread Safe: YES + public Map>> createWorldFactionChunks() { + // Create map "world name --> faction --> set of chunk coords" + Map>> worldFactionChunks = new HashMap<>(); + + // Note: The board is the world. The board id is the world name. + MemoryBoard board = (MemoryBoard) Board.getInstance(); + + for (Entry entry : board.flocationIds.entrySet()) { + String world = entry.getKey().getWorldName(); + Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); + + Map> factionChunks = worldFactionChunks.get(world); + if (factionChunks == null) { + factionChunks = new HashMap<>(); + worldFactionChunks.put(world, factionChunks); + } + + Set factionTerritory = factionChunks.get(chunkOwner); + if (factionTerritory == null) { + factionTerritory = new HashSet<>(); + factionChunks.put(chunkOwner, factionTerritory); + } + + factionTerritory.add(entry.getKey()); + } + + return worldFactionChunks; + } + + // Thread Safe: YES + public Map createAreas(Map>> worldFactionChunks) { + Map ret = new HashMap<>(); + + // For each world + for (Entry>> entry : worldFactionChunks.entrySet()) { + String world = entry.getKey(); + Map> factionChunks = entry.getValue(); + + // For each faction and its chunks in that world + for (Entry> entry1 : factionChunks.entrySet()) { + Faction faction = entry1.getKey(); + Set chunks = entry1.getValue(); + Map worldFactionMarkers = createAreas(world, faction, chunks); + ret.putAll(worldFactionMarkers); + } + } + + return ret; + } + + // Thread Safe: YES + // Handle specific faction on specific world + // "handle faction on world" + public Map createAreas(String world, Faction faction, Set chunks) { + Map ret = new HashMap<>(); + + // If the faction is visible ... + if (!isVisible(faction, world)) { + return ret; + } + + // ... and has any chunks ... + if (chunks.isEmpty()) { + return ret; + } + + // Index of polygon for given faction + int markerIndex = 0; + + // Create the info window + String description = getDescription(faction); + + // Fetch Style + DynmapStyle style = this.getStyle(faction); + + // Loop through chunks: set flags on chunk map + TileFlags allChunkFlags = new TileFlags(); + LinkedList allChunks = new LinkedList<>(); + for (FLocation chunk : chunks) { + allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk + allChunks.addLast(chunk); + } + + // Loop through until we don't find more areas + while (allChunks != null) { + + TileFlags ourChunkFlags = null; + LinkedList ourChunks = null; + LinkedList newChunks = null; + + for (FLocation chunk : allChunks) { + int chunkX = (int) chunk.getX(); + int chunkZ = (int) chunk.getZ(); + + // If we need to start shape, and this block is not part of one yet + if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunkFlags = new TileFlags(); // Create map for shape + ourChunks = new LinkedList<>(); + floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape + ourChunks.add(chunk); // Add it to our chunk list + } + // If shape found, and we're in it, add to our node list + else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunks.add(chunk); + } + // Else, keep it in the list for the next polygon + else { + if (newChunks == null) { + newChunks = new LinkedList<>(); + } + newChunks.add(chunk); + } + } + + // Replace list (null if no more to process) + allChunks = newChunks; + if (ourChunkFlags == null) { + continue; + } + List outputLines = new ArrayList(); + Map lines = new HashMap(); + + if (ourChunks == null) { + continue; + } + + for (FLocation loc : ourChunks) { + int x = loc.getChunk().getX(); + int z = loc.getChunk().getZ(); + + TempLine line = new TempLine(new Point(x * 16, z * 16), new Point(x * 16 + 16, z * 16)); + if (lines.containsKey(line)) { + lines.put(line, lines.get(line) + 1); + } else { + lines.put(line, 1); + } + + line = new TempLine(new Point(x * 16 + 16, z * 16), new Point(x * 16 + 16, z * 16 + 16)); + if (lines.containsKey(line)) { + lines.put(line, lines.get(line) + 1); + } else { + lines.put(line, 1); + } + + line = new TempLine(new Point(x * 16 + 16, z * 16 + 16), new Point(x * 16, z * 16 + 16)); + if (lines.containsKey(line)) { + lines.put(line, lines.get(line) + 1); + } else { + lines.put(line, 1); + } + + line = new TempLine(new Point(x * 16, z * 16 + 16), new Point(x * 16, z * 16)); + if (lines.containsKey(line)) { + lines.put(line, lines.get(line) + 1); + } else { + lines.put(line, 1); + } + } + + Iterator> iterator = lines.entrySet().iterator(); + + List lineList = new ArrayList(); + lineList.addAll(lines.keySet()); + + while (iterator.hasNext()) { + Entry entry = iterator.next(); + if (entry.getValue() > 1) { + lineList.remove(entry.getKey()); + } + } + + // Find the leftmost MCRWPoint + + TempLine l = null; + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + TempLine tl = it.next(); + if (l == null || tl.getP1().x < l.getP1().x) + l = tl; + } + + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + TempLine tl = it.next(); + if (tl.getP2().x < l.getP2().x) + l = tl; + } + + outputLines.add(l); + lineList.remove(l); + while (lineList.size() > 0) { + // MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1); + // MCRWPointWLines.get(targetp); + + TempLine nextLine = null; + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + TempLine line = it.next(); + if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) { + + nextLine = line; + } + + } + + if (nextLine != null) { + outputLines.add(nextLine); + lineList.remove(nextLine); + l = nextLine; + } else { + outputLines.get(outputLines.size() - 1).addAdditionLines(CamScan1(lineList)); + break; + } + + } + List outputPoints = new ArrayList(); + + List polyPoints = new ArrayList(); + + for (int i = 0; i < outputLines.size(); i++) { + Point p = new Point(outputLines.get(i).getP1().x, outputLines.get(i).getP1().y); + outputPoints.add(p); + polyPoints.add(p); + if (outputLines.get(i).getConnectedLines().size() > 0) { + + outputPoints.addAll(addRecursivePoints(new Point(outputLines.get(i).getP1().x, outputLines.get(i).getP1().y), outputLines.get(i))); + } + p = new Point(outputLines.get(i).getP2().x, outputLines.get(i).getP2().y); + outputPoints.add(p); + polyPoints.add(p); + } + polyLine.add(polyPoints); + + // Build information for specific area + double[] x = new double[outputPoints.size()]; + double[] z = new double[outputPoints.size()]; + + for (int i = 0; i < outputPoints.size(); i++) { + x[i] = outputPoints.get(i).x; + z[i] = outputPoints.get(i).y; + } + + String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; + + TempAreaMarker temp = new TempAreaMarker(); + temp.label = faction.getTag(); + temp.world = world; + temp.x = x; + temp.z = z; + temp.description = description; + + temp.lineColor = style.getLineColor(); + temp.lineOpacity = style.getLineOpacity(); + temp.lineWeight = style.getLineWeight(); + + temp.fillColor = style.getFillColor(); + temp.fillOpacity = style.getFillOpacity(); + + temp.boost = style.getBoost(); + temp.setPolyLine(polyLine); + + ret.put(markerId, temp); + polyLine.clear(); + + markerIndex++; + } + + return ret; + } + + public List addRecursivePoints(Point returnPoint, TempLine line) { + List ret = new ArrayList(); + boolean shouldReturn = false; + List connectedLines = line.getConnectedLines(); + List polyPoints = new ArrayList(); + for (TempLine line2 : connectedLines) { + Point p = new Point(line2.getP1().x, line2.getP1().y); + ret.add(p); + polyPoints.add(p); + shouldReturn = true; + if (line2.getConnectedLines().size() > 0) { + ret.addAll(addRecursivePoints(new Point(line2.getP1().x, line2.getP1().y), line2)); + } + p = new Point(line2.getP2().x, line2.getP2().y); + ret.add(p); + polyPoints.add(p); + + } + if (shouldReturn) { + ret.add(returnPoint); + } + polyLine.add(polyPoints); + return ret; + } + + private List CamScan1(List lineList) { + List ret = new ArrayList(); + + // Find the leftmost MCRWPoint + + TempLine l = null; + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + + TempLine tl = it.next(); + if (l == null || tl.getP1().x < l.getP1().x) + l = tl; + } + + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + TempLine tl = it.next(); + if (tl.getP2().x < l.getP2().x) + l = tl; + } + + ret.add(l); + lineList.remove(l); + while (lineList.size() > 0) { + // MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1); + // MCRWPointWLines.get(targetp); + + TempLine thisChunkLine = null; + for (Iterator it = lineList.iterator(); it.hasNext(); ) { + TempLine line = it.next(); + if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) { + + thisChunkLine = line; + } + + } + if (thisChunkLine != null) { + ret.add(thisChunkLine); + lineList.remove(thisChunkLine); + l = thisChunkLine; + } else { + // break; + ret.get(ret.size() - 1).addAdditionLines(CamScan1(lineList)); + } + + } + return ret; + } + + // -------------------------------------------- // + // UTIL & SHARED + // -------------------------------------------- // + + public void updatePolys(Map polys) { + // Map Current + Map markers = new HashMap<>(); + for (PolyLineMarker marker : this.markerset.getPolyLineMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop New + for (Entry entry : polys.entrySet()) { + String markerId = entry.getKey(); + TempPolyLineMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + PolyLineMarker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerset, markerId); + if (marker == null) { + severe("Could not get/create the area marker " + markerId); + } + } else { + temp.update(marker); + } + } + + // Only old/outdated should now be left. Delete them. + for (PolyLineMarker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // Thread Safe: NO + public void updateAreas(Map areas) { + // Map Current + Map markers = new HashMap<>(); + for (AreaMarker marker : this.markerset.getAreaMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop New + for (Entry entry : areas.entrySet()) { + String markerId = entry.getKey(); + TempAreaMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + AreaMarker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerset, markerId); + if (marker == null) { + severe("Could not get/create the area marker " + markerId); + } + } else { + temp.update(marker); + } + } + + // Only old/outdated should now be left. Delete them. + for (AreaMarker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // Thread Safe / Asynchronous: Yes + public String createPlayersetId(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + String factionId = faction.getId(); + if (factionId == null) { + return null; + } + return FACTIONS_PLAYERSET_ + factionId; + } + + // Thread Safe / Asynchronous: Yes + public Set createPlayerset(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + + Set ret = new HashSet<>(); + + for (FPlayer fplayer : faction.getFPlayers()) { + // NOTE: We add both UUID and name. This might be a good idea for future proofing. + ret.add(fplayer.getId()); + ret.add(fplayer.getName()); + } + + return ret; + } + + // Thread Safe / Asynchronous: Yes + public Map> createPlayersets() { + if (!Conf.dynmapVisibilityByFaction) { + return null; + } + + Map> ret = new HashMap<>(); + + for (Faction faction : Factions.getInstance().getAllFactions()) { + String playersetId = createPlayersetId(faction); + if (playersetId == null) { + continue; + } + Set playerIds = createPlayerset(faction); + if (playerIds == null) { + continue; + } + ret.put(playersetId, playerIds); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + public void updatePlayersets(Map> playersets) { + if (playersets == null) { + return; + } + + // Remove + for (PlayerSet set : this.markerApi.getPlayerSets()) { + if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { + continue; + } + + // (Null means remove all) + if (playersets.containsKey(set.getSetID())) { + continue; + } + + set.deleteSet(); + } + + // Add / Update + for (Entry> entry : playersets.entrySet()) { + // Extract from Entry + String setId = entry.getKey(); + Set playerIds = entry.getValue(); + + // Get Creatively + PlayerSet set = this.markerApi.getPlayerSet(setId); + if (set == null) { + set = this.markerApi.createPlayerSet(setId, // id + true, // symmetric + playerIds, // players + false // persistent + ); + } + if (set == null) { + severe("Could not get/create the player set " + setId); + continue; + } + + // Set Content + set.setPlayers(playerIds); + } + } + + // Thread Safe / Asynchronous: Yes + private String getDescription(Faction faction) { + String ret = "
" + Conf.dynmapDescription + "
"; + + // Name + String name = faction.getTag(); + name = escapeHtml(ChatColor.stripColor(name)); + ret = ret.replace("%name%", name); + + // Description + String description = faction.getDescription(); + description = escapeHtml(ChatColor.stripColor(description)); + ret = ret.replace("%description%", description); + + // Money + + String money = "unavailable"; + if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) + money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); + ret = ret.replace("%money%", money); + + // Players + Set playersList = faction.getFPlayers(); + String playersCount = String.valueOf(playersList.size()); + String players = getHtmlPlayerString(playersList); + + FPlayer playersLeaderObject = faction.getFPlayerAdmin(); + String playersLeader = getHtmlPlayerName(playersLeaderObject); + + ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); + String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); + String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); + + ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); + String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); + String playersModerators = getHtmlPlayerString(playersModeratorsList); + + ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); + String playersNormalsCount = String.valueOf(playersNormalsList.size()); + String playersNormals = getHtmlPlayerString(playersNormalsList); + + ret = ret.replace("%players%", players); + ret = ret.replace("%players.count%", playersCount); + ret = ret.replace("%players.leader%", playersLeader); + ret = ret.replace("%players.admins%", playersCoAdmins); + ret = ret.replace("%players.admins.count%", playersCoAdminsCount); + ret = ret.replace("%players.moderators%", playersModerators); + ret = ret.replace("%players.moderators.count%", playersModeratorsCount); + ret = ret.replace("%players.normals%", playersNormals); + ret = ret.replace("%players.normals.count%", playersNormalsCount); + + return ret; + } + + // Thread Safe / Asynchronous: Yes + private boolean isVisible(Faction faction, String world) { + if (faction == null) { + return false; + } + final String factionId = faction.getId(); + if (factionId == null) { + return false; + } + final String factionName = faction.getTag(); + if (factionName == null) { + return false; + } + + Set visible = Conf.dynmapVisibleFactions; + Set hidden = Conf.dynmapHiddenFactions; + + if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { + return false; + } + + return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); + } + + // Thread Safe / Asynchronous: Yes + public DynmapStyle getStyle(Faction faction) { + DynmapStyle ret; + + ret = Conf.dynmapFactionStyles.get(faction.getId()); + if (ret != null) { + return ret; + } + + ret = Conf.dynmapFactionStyles.get(faction.getTag()); + if (ret != null) { + return ret; + } + + return Conf.dynmapDefaultStyle; + } + + // Find all contiguous blocks, set in target and clear in source + private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { + int cnt = 0; + ArrayDeque stack = new ArrayDeque<>(); + stack.push(new int[]{x, y}); + + while (!stack.isEmpty()) { + int[] nxt = stack.pop(); + x = nxt[0]; + y = nxt[1]; + if (source.getFlag(x, y)) { // Set in src + source.setFlag(x, y, false); // Clear source + destination.setFlag(x, y, true); // Set in destination + cnt++; + if (source.getFlag(x + 1, y)) { + stack.push(new int[]{x + 1, y}); + } + if (source.getFlag(x - 1, y)) { + stack.push(new int[]{x - 1, y}); + } + if (source.getFlag(x, y + 1)) { + stack.push(new int[]{x, y + 1}); + } + if (source.getFlag(x, y - 1)) { + stack.push(new int[]{x, y - 1}); + } + } + } + return cnt; + } + + enum Direction { + XPLUS, ZPLUS, XMINUS, ZMINUS + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java index ffe7cc7f..9fe7db40 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java @@ -1,151 +1,129 @@ package com.massivecraft.factions.integration.dynmap; -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; - import org.dynmap.markers.AreaMarker; import org.dynmap.markers.MarkerSet; -public class TempAreaMarker -{ +import java.awt.*; +import java.util.ArrayList; +import java.util.List; - /** - * @author FactionsUUID Team - */ +public class TempAreaMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + /** + * @author FactionsUUID Team + */ - public String label; - public String world; - public double[] x; - public double[] z; + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - private List> polyLine = new ArrayList>(); + public String label; + public String world; + public double[] x; + public double[] z; + public String description; + public int lineColor; + public double lineOpacity; + public int lineWeight; + public int fillColor; + public double fillOpacity; + public boolean boost; + private List> polyLine = new ArrayList>(); - public String description; + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - public int lineColor; - public double lineOpacity; - public int lineWeight; + public static boolean equals(AreaMarker marker, double[] x, double[] z) { + int length = marker.getCornerCount(); - public int fillColor; - public double fillOpacity; + if (x.length != length) { + return false; + } + if (z.length != length) { + return false; + } - public boolean boost; + for (int i = 0; i < length; i++) { + if (marker.getCornerX(i) != x[i]) { + return false; + } + if (marker.getCornerZ(i) != z[i]) { + return false; + } + } - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + return true; + } - public static boolean equals(AreaMarker marker, double[] x, double[] z) - { - int length = marker.getCornerCount(); + public List> getPolyLine() { + return polyLine; + } - if (x.length != length) - { - return false; - } - if (z.length != length) - { - return false; - } + public void setPolyLine(List> points) { + polyLine.clear(); + polyLine.addAll(points); + } - for (int i = 0; i < length; i++) - { - if (marker.getCornerX(i) != x[i]) - { - return false; - } - if (marker.getCornerZ(i) != z[i]) - { - return false; - } - } + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - return true; - } + public AreaMarker create(MarkerSet markerset, String markerId) { + AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent + ); + if (ret == null) { + return null; + } - public void setPolyLine(List> points) - { - polyLine.clear(); - polyLine.addAll(points); - } + int counter = 0; - public List> getPolyLine() - { - return polyLine; - } + // Description + ret.setDescription(this.description); - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + // Line Style + ret.setLineStyle(0, 0, 0); - public AreaMarker create(MarkerSet markerset, String markerId) - { - AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent - ); - if (ret == null) - { - return null; - } + // Fill Style + ret.setFillStyle(this.fillOpacity, this.fillColor); - int counter = 0; + // Boost Flag + ret.setBoostFlag(this.boost); - // Description - ret.setDescription(this.description); + return ret; + } + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - // Line Style - ret.setLineStyle(0, 0, 0); + public void update(AreaMarker marker) { + // Corner Locations + if (!equals(marker, this.x, this.z)) { + marker.setCornerLocations(this.x, this.z); + } - // Fill Style - ret.setFillStyle(this.fillOpacity, this.fillColor); + // Label + if (!marker.getLabel().equals(this.label)) { + marker.setLabel(this.label); + } + if (!marker.getDescription().equals(this.description)) { + marker.setDescription(this.description); + } - // Boost Flag - ret.setBoostFlag(this.boost); + // // Line Style + // if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor) + // { + // marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + // } - return ret; - } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // - - public void update(AreaMarker marker) - { - // Corner Locations - if (!equals(marker, this.x, this.z)) - { - marker.setCornerLocations(this.x, this.z); - } - - // Label - if (!marker.getLabel().equals(this.label)) - { - marker.setLabel(this.label); - } - if (!marker.getDescription().equals(this.description)) - { - marker.setDescription(this.description); - } - - // // Line Style - // if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor) - // { - // marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - // } - - // Fill Style - if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) - { - marker.setFillStyle(this.fillOpacity, this.fillColor); - } - // Boost Flag - if (marker.getBoostFlag() != this.boost) - { - marker.setBoostFlag(this.boost); - } - } + // Fill Style + if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { + marker.setFillStyle(this.fillOpacity, this.fillColor); + } + // Boost Flag + if (marker.getBoostFlag() != this.boost) { + marker.setBoostFlag(this.boost); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempLine.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempLine.java index 4d683240..65802d61 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempLine.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempLine.java @@ -1,62 +1,49 @@ package com.massivecraft.factions.integration.dynmap; -import java.awt.Point; +import java.awt.*; import java.util.ArrayList; import java.util.List; -public class TempLine -{ - private Point p1; - private Point p2; - private List connectedLines = new ArrayList(); +public class TempLine { + private Point p1; + private Point p2; + private List connectedLines = new ArrayList(); - TempLine(Point p1, Point p2) - { - this.p1 = p1; - this.p2 = p2; + TempLine(Point p1, Point p2) { + this.p1 = p1; + this.p2 = p2; + } + + public Point getP1() { + return p1; + } + + public Point getP2() { + return p2; + } + + public void addAdditionLines(List connectedLines) { + this.connectedLines = connectedLines; + } + + public List getConnectedLines() { + return connectedLines; + } + + @Override + public boolean equals(Object o) { + TempLine line = (TempLine) o; + if (line.p1.x == this.p1.x && line.p2.x == this.p2.x && line.p1.y == this.p1.y && line.p2.y == this.p2.y) { + return true; + } + return line.p1.x == this.p2.x && line.p2.x == this.p1.x && line.p1.y == this.p2.y && line.p2.y == this.p1.y; } - public Point getP1() - { - return p1; - } - - public Point getP2() - { - return p2; - } - - public void addAdditionLines(List connectedLines) - { - this.connectedLines = connectedLines; - } - - public List getConnectedLines() - { - return connectedLines; - } - - @Override - public boolean equals(Object o) - { - TempLine line = (TempLine) o; - if (line.p1.x == this.p1.x && line.p2.x == this.p2.x && line.p1.y == this.p1.y && line.p2.y == this.p2.y) - { - return true; - } - if (line.p1.x == this.p2.x && line.p2.x == this.p1.x && line.p1.y == this.p2.y && line.p2.y == this.p1.y) - { - return true; - } - return false; - } - - @Override - public int hashCode() - { - String test = "" + (p1.x + p2.x); - test += " " + (p1.y + p2.y); - return test.hashCode(); - } + @Override + public int hashCode() { + String test = "" + (p1.x + p2.x); + test += " " + (p1.y + p2.y); + return test.hashCode(); + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempPolyLineMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempPolyLineMarker.java index e2444fbb..56e235a8 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempPolyLineMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempPolyLineMarker.java @@ -1,111 +1,99 @@ package com.massivecraft.factions.integration.dynmap; -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; import org.dynmap.markers.MarkerSet; import org.dynmap.markers.PolyLineMarker; -public class TempPolyLineMarker -{ +import java.awt.*; +import java.util.ArrayList; +import java.util.List; - /** - * @author FactionsUUID Team - */ +public class TempPolyLineMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + /** + * @author FactionsUUID Team + */ - public String world; + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public List polyLine = new ArrayList(); + public String world; - public int lineColor; - public double lineOpacity; - public int lineWeight; + public List polyLine = new ArrayList(); - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + public int lineColor; + public double lineOpacity; + public int lineWeight; - public static boolean equals(PolyLineMarker marker, List points) - { - int length = marker.getCornerCount(); + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - if (points.size() != length) - { - return false; - } - for (int i = 0; i < length; i++) - { - if (marker.getCornerX(i) != points.get(i).x) - { - return false; - } - if (marker.getCornerZ(i) != points.get(i).y) - { - return false; - } - } + public static boolean equals(PolyLineMarker marker, List points) { + int length = marker.getCornerCount(); - return true; - } + if (points.size() != length) { + return false; + } + for (int i = 0; i < length; i++) { + if (marker.getCornerX(i) != points.get(i).x) { + return false; + } + if (marker.getCornerZ(i) != points.get(i).y) { + return false; + } + } - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + return true; + } - public PolyLineMarker create(MarkerSet markerset, String markerId) - { - double[] polyX = new double[polyLine.size()]; - double[] polyY = new double[polyLine.size()]; - double[] polyZ = new double[polyLine.size()]; - for (int i = 0; i < polyLine.size(); i++) - { - Point p = polyLine.get(i); - polyX[i] = p.getX(); - polyY[i] = 64; - polyZ[i] = p.getY(); - } - PolyLineMarker poly = markerset.createPolyLineMarker(markerId, "", false, this.world, polyX, polyY, polyZ, false); - // Poly Line Style - if (poly != null) - { - poly.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - } - return poly; - } + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + public PolyLineMarker create(MarkerSet markerset, String markerId) { + double[] polyX = new double[polyLine.size()]; + double[] polyY = new double[polyLine.size()]; + double[] polyZ = new double[polyLine.size()]; + for (int i = 0; i < polyLine.size(); i++) { + Point p = polyLine.get(i); + polyX[i] = p.getX(); + polyY[i] = 64; + polyZ[i] = p.getY(); + } + PolyLineMarker poly = markerset.createPolyLineMarker(markerId, "", false, this.world, polyX, polyY, polyZ, false); + // Poly Line Style + if (poly != null) { + poly.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + } + return poly; + } - public void update(PolyLineMarker marker) - { - // Corner Locations - if (!equals(marker, polyLine)) - { - double[] polyX = new double[polyLine.size()]; - double[] polyY = new double[polyLine.size()]; - double[] polyZ = new double[polyLine.size()]; - for (int i = 0; i < polyLine.size(); i++) - { - Point p = polyLine.get(i); - polyX[i] = p.getX(); - polyY[i] = 64; - polyZ[i] = p.getY(); - } - marker.setCornerLocations(polyX, polyY, polyZ); - marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - } + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - // Line Style - if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor) - { - marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - } + public void update(PolyLineMarker marker) { + // Corner Locations + if (!equals(marker, polyLine)) { + double[] polyX = new double[polyLine.size()]; + double[] polyY = new double[polyLine.size()]; + double[] polyZ = new double[polyLine.size()]; + for (int i = 0; i < polyLine.size(); i++) { + Point p = polyLine.get(i); + polyX[i] = p.getX(); + polyY[i] = 64; + polyZ[i] = p.getY(); + } + marker.setCornerLocations(polyX, polyY, polyZ); + marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + } - } + // Line Style + if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor) { + marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + } + + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java index a627e751..83e0700c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -42,624 +42,523 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class FactionsBlockListener implements Listener -{ +public class FactionsBlockListener implements Listener { - public static HashMap bannerLocations = new HashMap<>(); - private HashMap bannerCooldownMap = new HashMap<>(); - private long placeTimer = TimeUnit.SECONDS.toMillis(15L); + public static HashMap bannerLocations = new HashMap<>(); + private HashMap bannerCooldownMap = new HashMap<>(); + private long placeTimer = TimeUnit.SECONDS.toMillis(15L); - public static boolean playerCanBuildDestroyBlock(Player player, Location location, PermissableAction action, boolean justCheck) - { - if (Conf.playersWhoBypassAllProtection.contains(player.getName())) - return true; + public static boolean playerCanBuildDestroyBlock(Player player, Location location, PermissableAction action, boolean justCheck) { + if (Conf.playersWhoBypassAllProtection.contains(player.getName())) + return true; - FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); - if (me.isAdminBypassing()) - return true; + FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); + if (me.isAdminBypassing()) + return true; - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getInstance().getFactionAt(loc); - Faction myFaction = me.getFaction(); + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + Faction myFaction = me.getFaction(); - if (otherFaction.isWilderness()) - { - if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) - return true; - if (location.getWorld() != null) - { - if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) - return true; - } - if (!justCheck) - me.msg(TL.ACTION_DENIED_WILDERNESS, action.toString()); - return false; - } - else if (otherFaction.isSafeZone()) - { - if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) - return true; - if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) - return true; - if (!justCheck) - me.msg(TL.ACTION_DENIED_SAFEZONE, action.toString()); - return false; - } - else if (otherFaction.isWarZone()) - { - if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) - return true; - if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) - return true; - if (!justCheck) - me.msg(TL.ACTION_DENIED_WARZONE, action.toString()); - return false; - } - else if (!otherFaction.getId().equals(myFaction.getId())) - { // If the faction target is not my own - if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) - return true; - boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; - return CheckActionState(otherFaction, loc, me, action, pain, justCheck); - } - else if (otherFaction.getId().equals(myFaction.getId())) - { - boolean pain = !justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; - return CheckActionState(myFaction, loc, me, action, pain, justCheck); - } - return false; - } + if (otherFaction.isWilderness()) { + if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) + return true; + if (location.getWorld() != null) { + if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) + return true; + } + if (!justCheck) + me.msg(TL.ACTION_DENIED_WILDERNESS, action.toString()); + return false; + } else if (otherFaction.isSafeZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) + return true; + if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) + return true; + if (!justCheck) + me.msg(TL.ACTION_DENIED_SAFEZONE, action.toString()); + return false; + } else if (otherFaction.isWarZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) + return true; + if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) + return true; + if (!justCheck) + me.msg(TL.ACTION_DENIED_WARZONE, action.toString()); + return false; + } else if (!otherFaction.getId().equals(myFaction.getId())) { // If the faction target is not my own + if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) + return true; + boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; + return CheckActionState(otherFaction, loc, me, action, pain, justCheck); + } else if (otherFaction.getId().equals(myFaction.getId())) { + boolean pain = !justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; + return CheckActionState(myFaction, loc, me, action, pain, justCheck); + } + return false; + } - private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction myFaction, Access access, PermissableAction action, boolean shouldHurt, boolean justCheck) - { - boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty()); - if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId()))) - return true; - else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) - { - me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); - if (shouldHurt) - { - player.damage(Conf.actionDeniedPainAmount); - me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); - } - return false; - } - else if (!landOwned && access == Access.DENY) - { // If land is not owned but access is set to DENY anyway - if (shouldHurt) - { - player.damage(Conf.actionDeniedPainAmount); - if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null) - me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); - } - if (myFaction.getTag(me.getFaction()) != null && action != null && !justCheck) - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); - return false; - } - else if (access == Access.ALLOW) - return true; + private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction myFaction, Access access, PermissableAction action, boolean shouldHurt, boolean justCheck) { + boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty()); + if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId()))) + return true; + else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) { + me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); + if (shouldHurt) { + player.damage(Conf.actionDeniedPainAmount); + me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); + } + return false; + } else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway + if (shouldHurt) { + player.damage(Conf.actionDeniedPainAmount); + if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null) + me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); + } + if (myFaction.getTag(me.getFaction()) != null && action != null && !justCheck) + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); + return false; + } else if (access == Access.ALLOW) + return true; - if (!justCheck) - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", me.getFaction().getTag()).replace("{action}", action.toString())); - return false; - } + if (!justCheck) + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", me.getFaction().getTag()).replace("{action}", action.toString())); + return false; + } - private static boolean CheckActionState(Faction target, FLocation location, FPlayer me, PermissableAction action, boolean pain, boolean justCheck) - { - if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) - { - // If pain should be applied + private static boolean CheckActionState(Faction target, FLocation location, FPlayer me, PermissableAction action, boolean pain, boolean justCheck) { + if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) { + // If pain should be applied - if (pain && Conf.ownedAreaPainBuild) - me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace("{action}", action.toString()).replace("{faction}", target.getOwnerListString(location))); - if (Conf.ownedAreaDenyBuild && pain) - return false; - else if (Conf.ownedAreaDenyBuild) - { - if(!justCheck) - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag(me.getFaction())).replace("{action}", action.toString())); - return false; - } - } - return CheckPlayerAccess(me.getPlayer(), me, location, target, target.getAccess(me, action), action, pain, justCheck); - } + if (pain && Conf.ownedAreaPainBuild) + me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace("{action}", action.toString()).replace("{faction}", target.getOwnerListString(location))); + if (Conf.ownedAreaDenyBuild && pain) + return false; + else if (Conf.ownedAreaDenyBuild) { + if (!justCheck) + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag(me.getFaction())).replace("{action}", action.toString())); + return false; + } + } + return CheckPlayerAccess(me.getPlayer(), me, location, target, target.getAccess(me, action), action, pain, justCheck); + } - public void handleSpawnerUpdate(Faction at, Player player, ItemStack spawnerItem, LogTimer.TimerSubType subType) - { - FLogManager manager = FactionsPlugin.instance.getFlogManager(); - LogTimer logTimer = manager.getLogTimers().computeIfAbsent(player.getUniqueId(), e -> new LogTimer(player.getName(), at.getId())); - LogTimer.Timer timer = logTimer.attemptLog(LogTimer.TimerType.SPAWNER_EDIT, subType, 0L); - Map currentCounts = (timer.getExtraData() == null) ? new HashMap<>() : ((Map) timer.getExtraData()); - currentCounts.computeIfAbsent(spawnerItem.getData(), e -> new AtomicInteger(0)).addAndGet(1); - timer.setExtraData(currentCounts); - if (timer.isReadyToLog(this.placeTimer)) - { - logTimer.pushLogs(at, LogTimer.TimerType.SPAWNER_EDIT); - } - } + public void handleSpawnerUpdate(Faction at, Player player, ItemStack spawnerItem, LogTimer.TimerSubType subType) { + FLogManager manager = FactionsPlugin.instance.getFlogManager(); + LogTimer logTimer = manager.getLogTimers().computeIfAbsent(player.getUniqueId(), e -> new LogTimer(player.getName(), at.getId())); + LogTimer.Timer timer = logTimer.attemptLog(LogTimer.TimerType.SPAWNER_EDIT, subType, 0L); + Map currentCounts = (timer.getExtraData() == null) ? new HashMap<>() : ((Map) timer.getExtraData()); + currentCounts.computeIfAbsent(spawnerItem.getData(), e -> new AtomicInteger(0)).addAndGet(1); + timer.setExtraData(currentCounts); + if (timer.isReadyToLog(this.placeTimer)) { + logTimer.pushLogs(at, LogTimer.TimerType.SPAWNER_EDIT); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPlace(BlockPlaceEvent event) - { - ItemStack item = event.getItemInHand(); - if (item != null && item.getType() == XMaterial.SPAWNER.parseMaterial()) - { - Faction at = Board.getInstance().getFactionAt(new FLocation(event.getBlockPlaced())); - if (at != null && at.isNormal()) - { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fplayer != null && at.getRelationTo(fplayer.getFaction()).isAtLeast(Relation.TRUCE)) - { - this.handleSpawnerUpdate(at, event.getPlayer(), item, LogTimer.TimerSubType.SPAWNER_PLACE); - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerPlace(BlockPlaceEvent event) { + ItemStack item = event.getItemInHand(); + if (item != null && item.getType() == XMaterial.SPAWNER.parseMaterial()) { + Faction at = Board.getInstance().getFactionAt(new FLocation(event.getBlockPlaced())); + if (at != null && at.isNormal()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fplayer != null && at.getRelationTo(fplayer.getFaction()).isAtLeast(Relation.TRUCE)) { + this.handleSpawnerUpdate(at, event.getPlayer(), item, LogTimer.TimerSubType.SPAWNER_PLACE); + } + } + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) - { + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { - if (!event.canBuild()) - return; - if (event.getBlockPlaced().getType() == Material.FIRE) - return; - boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial()); - if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.BUILD, false)) - { - event.setCancelled(true); - return; - } + if (!event.canBuild()) + return; + if (event.getBlockPlaced().getType() == Material.FIRE) + return; + boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial()); + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.BUILD, false)) { + event.setCancelled(true); + return; + } - if (isSpawner) - { - if (Conf.spawnerLock) - { - event.setCancelled(true); - event.getPlayer().sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_SPAWNER_LOCK_CANNOT_PLACE.toString())); - } - } - } + if (isSpawner) { + if (Conf.spawnerLock) { + event.setCancelled(true); + event.getPlayer().sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_SPAWNER_LOCK_CANNOT_PLACE.toString())); + } + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockFromTo(BlockFromToEvent event) - { - if (!Conf.handleExploitLiquidFlow) - return; + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent event) { + if (!Conf.handleExploitLiquidFlow) + return; - if (event.getBlock().isLiquid()) - { - if (event.getToBlock().isEmpty()) - { - Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); - if (from == to) - return; - // from faction != to faction - if (to.isSystemFaction()) - { - event.setCancelled(true); - return; - } + if (event.getBlock().isLiquid()) { + if (event.getToBlock().isEmpty()) { + Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); + if (from == to) + return; + // from faction != to faction + if (to.isSystemFaction()) { + event.setCancelled(true); + return; + } - if (to.isNormal()) - { - if (from.isNormal() && from.getRelationTo(to).isAlly()) - { - return; - } - event.setCancelled(true); - } - } - } - } + if (to.isNormal()) { + if (from.isNormal() && from.getRelationTo(to).isAlly()) { + return; + } + event.setCancelled(true); + } + } + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockDamage(BlockDamageEvent event) - { - if (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.DESTROY, false)) - { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockDamage(BlockDamageEvent event) { + if (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.DESTROY, false)) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPistonExtend(BlockPistonExtendEvent event) - { - if (!Conf.pistonProtectionThroughDenyBuild) - return; - Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + if (!Conf.pistonProtectionThroughDenyBuild) + return; + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - // target end-of-the-line empty (air) block which is being pushed into, including if piston itself would extend into air - Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1); + // target end-of-the-line empty (air) block which is being pushed into, including if piston itself would extend into air + Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1); - // if potentially pushing into air/water/lava in another territory, we need to check it out - if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) - event.setCancelled(true); - } + // if potentially pushing into air/water/lava in another territory, we need to check it out + if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) + event.setCancelled(true); + } - @EventHandler - public void onVaultPlace(BlockPlaceEvent e) - { - if (e.getItemInHand().getType() == Material.CHEST) - { + @EventHandler + public void onVaultPlace(BlockPlaceEvent e) { + if (e.getItemInHand().getType() == Material.CHEST) { - ItemStack vault = new ItemBuilder(Material.CHEST).amount(1).name(FactionsPlugin.instance.getConfig().getString("fvault.Item.Name")).lore(FactionsPlugin.instance.getConfig().getStringList("fvault.Item.Lore")).build(); + ItemStack vault = new ItemBuilder(Material.CHEST).amount(1).name(FactionsPlugin.instance.getConfig().getString("fvault.Item.Name")).lore(FactionsPlugin.instance.getConfig().getStringList("fvault.Item.Lore")).build(); - if (e.getItemInHand().isSimilar(vault)) - { - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - if (fme.getFaction().getVault() != null) - { - fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); - e.setCancelled(true); - return; - } - FLocation flocation = new FLocation(e.getBlockPlaced().getLocation()); - if (Board.getInstance().getFactionAt(flocation) != fme.getFaction()) - { - fme.msg(TL.COMMAND_GETVAULT_INVALIDLOCATION); - e.setCancelled(true); - return; - } - Block start = e.getBlockPlaced(); - int radius = 1; - for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) - { - for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) - { - for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) - { - Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); - if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) - { - continue; - } - Material blockMaterial = blockLoc.getBlock().getType(); - if (blockMaterial == Material.CHEST || (FactionsPlugin.instance.getConfig().getBoolean("fvault.No-Hoppers-near-vault") && blockMaterial == Material.HOPPER)) - { - e.setCancelled(true); - fme.msg(TL.COMMAND_GETVAULT_CHESTNEAR); - return; - } - } - } - } - fme.msg(TL.COMMAND_GETVAULT_SUCCESS); - fme.getFaction().setVault(e.getBlockPlaced().getLocation()); + if (e.getItemInHand().isSimilar(vault)) { + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (fme.getFaction().getVault() != null) { + fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); + e.setCancelled(true); + return; + } + FLocation flocation = new FLocation(e.getBlockPlaced().getLocation()); + if (Board.getInstance().getFactionAt(flocation) != fme.getFaction()) { + fme.msg(TL.COMMAND_GETVAULT_INVALIDLOCATION); + e.setCancelled(true); + return; + } + Block start = e.getBlockPlaced(); + int radius = 1; + for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { + for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { + for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { + Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); + if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { + continue; + } + Material blockMaterial = blockLoc.getBlock().getType(); + if (blockMaterial == Material.CHEST || (FactionsPlugin.instance.getConfig().getBoolean("fvault.No-Hoppers-near-vault") && blockMaterial == Material.HOPPER)) { + e.setCancelled(true); + fme.msg(TL.COMMAND_GETVAULT_CHESTNEAR); + return; + } + } + } + } + fme.msg(TL.COMMAND_GETVAULT_SUCCESS); + fme.getFaction().setVault(e.getBlockPlaced().getLocation()); - } - } - } + } + } + } - @EventHandler - public void onHopperPlace(BlockPlaceEvent e) - { - if (e.getItemInHand().getType() != Material.HOPPER && !FactionsPlugin.instance.getConfig().getBoolean("fvault.No-Hoppers-near-vault")) - return; - Faction factionAt = Board.getInstance().getFactionAt(new FLocation(e.getBlockPlaced().getLocation())); - if (factionAt.isWilderness() || factionAt.getVault() == null) - return; - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - Block start = e.getBlockPlaced(); - int radius = 1; - for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) - { - for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) - { - for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) - { - Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); - if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) - { - continue; - } + @EventHandler + public void onHopperPlace(BlockPlaceEvent e) { + if (e.getItemInHand().getType() != Material.HOPPER && !FactionsPlugin.instance.getConfig().getBoolean("fvault.No-Hoppers-near-vault")) + return; + Faction factionAt = Board.getInstance().getFactionAt(new FLocation(e.getBlockPlaced().getLocation())); + if (factionAt.isWilderness() || factionAt.getVault() == null) + return; + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + Block start = e.getBlockPlaced(); + int radius = 1; + for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { + for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { + for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { + Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); + if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { + continue; + } - if (blockLoc.getBlock().getType() == XMaterial.CHEST.parseMaterial()) - { - if (factionAt.getVault().equals(blockLoc)) - { - e.setCancelled(true); - fme.msg(TL.COMMAND_VAULT_NO_HOPPER); - return; - } - } - } - } - } + if (blockLoc.getBlock().getType() == XMaterial.CHEST.parseMaterial()) { + if (factionAt.getVault().equals(blockLoc)) { + e.setCancelled(true); + fme.msg(TL.COMMAND_VAULT_NO_HOPPER); + return; + } + } + } + } + } - } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPistonRetract(BlockPistonRetractEvent event) - { - // if not a sticky piston, retraction should be fine - if (!event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) - return; + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + // if not a sticky piston, retraction should be fine + if (!event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) + return; - Location targetLoc = event.getRetractLocation(); - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(targetLoc)); + Location targetLoc = event.getRetractLocation(); + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(targetLoc)); - // Check if the piston is moving in a faction's territory. This disables pistons entirely in faction territory. - if (otherFaction.isNormal() && FactionsPlugin.instance.getConfig().getBoolean("disable-pistons-in-territory", false)) - { - event.setCancelled(true); - return; - } + // Check if the piston is moving in a faction's territory. This disables pistons entirely in faction territory. + if (otherFaction.isNormal() && FactionsPlugin.instance.getConfig().getBoolean("disable-pistons-in-territory", false)) { + event.setCancelled(true); + return; + } - // if potentially retracted block is just air/water/lava, no worries - if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) - return; - Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - if (!canPistonMoveBlock(pistonFaction, targetLoc)) - event.setCancelled(true); - } + // if potentially retracted block is just air/water/lava, no worries + if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) + return; + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + if (!canPistonMoveBlock(pistonFaction, targetLoc)) + event.setCancelled(true); + } - @EventHandler - public void onBannerBreak(BlockBreakEvent e) - { - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - if (FactionsPlugin.getInstance().mc17) - { - return; - } + @EventHandler + public void onBannerBreak(BlockBreakEvent e) { + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (FactionsPlugin.getInstance().mc17) { + return; + } - if (bannerLocations.containsValue(e.getBlock().getLocation())) - { - if (e.getBlock().getType().name().contains("BANNER")) - { - e.setCancelled(true); - fme.msg(TL.BANNER_CANNOT_BREAK); - } - } - } + if (bannerLocations.containsValue(e.getBlock().getLocation())) { + if (e.getBlock().getType().name().contains("BANNER")) { + e.setCancelled(true); + fme.msg(TL.BANNER_CANNOT_BREAK); + } + } + } - @EventHandler - public void onBannerPlace(BlockPlaceEvent e) - { - if (FactionsPlugin.getInstance().mc17) - return; + @EventHandler + public void onBannerPlace(BlockPlaceEvent e) { + if (FactionsPlugin.getInstance().mc17) + return; - if (e.getItemInHand().getType().name().contains("BANNER")) - { - ItemStack bannerInHand = e.getItemInHand(); - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - ItemStack warBanner = fme.getFaction().getBanner(); - if (warBanner == null) - return; - ItemMeta warmeta = warBanner.getItemMeta(); - warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); - warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); - warBanner.setItemMeta(warmeta); - if (warBanner.isSimilar(bannerInHand)) - { - if (fme.getFaction().isWilderness()) - { - fme.msg(TL.WARBANNER_NOFACTION); - e.setCancelled(true); - return; - } - int bannerTime = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Time") * 20; - Location placedLoc = e.getBlockPlaced().getLocation(); - FLocation fplacedLoc = new FLocation(placedLoc); - if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Warzone")) - || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Enemy"))) - { - if (bannerCooldownMap.containsKey(fme.getTag())) - { - fme.msg(TL.WARBANNER_COOLDOWN); - e.setCancelled(true); - return; - } - for (FPlayer fplayer : fme.getFaction().getFPlayers()) - { - fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!")); - } - bannerCooldownMap.put(fme.getTag(), true); - FactionsBlockListener.bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); - int bannerCooldown = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Place-Cooldown"); - ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5), EntityType.ARMOR_STAND); - as.setVisible(false); - as.setGravity(false); - as.setCanPickupItems(false); - as.setCustomName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); - as.setCustomNameVisible(true); - String tag = fme.getTag(); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> bannerCooldownMap.remove(tag), Long.parseLong(bannerCooldown + "")); - Block banner = e.getBlockPlaced(); - Material bannerType = banner.getType(); - Faction bannerFaction = fme.getFaction(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - int radius = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Effect-Radius"); - List effects = FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Effects"); - int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> - { - for (Entity e1 : Objects.requireNonNull(banner.getLocation().getWorld()).getNearbyEntities(banner.getLocation(), radius, 255.0, radius)) - { - if (e1 instanceof Player) - { - Player player = (Player) e1; - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer.getFaction() != bannerFaction) - { - continue; - } - for (String effect : effects) - { - String[] components = effect.split(":"); - player.addPotionEffect(new PotionEffect(Objects.requireNonNull(PotionEffectType.getByName(components[0])), 100, Integer.parseInt(components[1]))); - } - if (banner.getType() == bannerType) - { - continue; - } - banner.setType(bannerType); - } - } - }, 0L, 20L); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> - { - banner.setType(Material.AIR); - as.remove(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - Bukkit.getScheduler().cancelTask(affectorTask); - FactionsBlockListener.bannerLocations.remove(bannerFaction.getTag()); - }, Long.parseLong(bannerTime + "")); - } - else - { - fme.msg(TL.WARBANNER_INVALIDLOC); - e.setCancelled(true); - } - } - } - } + if (e.getItemInHand().getType().name().contains("BANNER")) { + ItemStack bannerInHand = e.getItemInHand(); + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + ItemStack warBanner = fme.getFaction().getBanner(); + if (warBanner == null) + return; + ItemMeta warmeta = warBanner.getItemMeta(); + warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); + warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); + warBanner.setItemMeta(warmeta); + if (warBanner.isSimilar(bannerInHand)) { + if (fme.getFaction().isWilderness()) { + fme.msg(TL.WARBANNER_NOFACTION); + e.setCancelled(true); + return; + } + int bannerTime = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Time") * 20; + Location placedLoc = e.getBlockPlaced().getLocation(); + FLocation fplacedLoc = new FLocation(placedLoc); + if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Warzone")) + || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Enemy"))) { + if (bannerCooldownMap.containsKey(fme.getTag())) { + fme.msg(TL.WARBANNER_COOLDOWN); + e.setCancelled(true); + return; + } + for (FPlayer fplayer : fme.getFaction().getFPlayers()) { + fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!")); + } + bannerCooldownMap.put(fme.getTag(), true); + FactionsBlockListener.bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); + int bannerCooldown = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Place-Cooldown"); + ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5), EntityType.ARMOR_STAND); + as.setVisible(false); + as.setGravity(false); + as.setCanPickupItems(false); + as.setCustomName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); + as.setCustomNameVisible(true); + String tag = fme.getTag(); + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> bannerCooldownMap.remove(tag), Long.parseLong(bannerCooldown + "")); + Block banner = e.getBlockPlaced(); + Material bannerType = banner.getType(); + Faction bannerFaction = fme.getFaction(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + int radius = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Effect-Radius"); + List effects = FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Effects"); + int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> + { + for (Entity e1 : Objects.requireNonNull(banner.getLocation().getWorld()).getNearbyEntities(banner.getLocation(), radius, 255.0, radius)) { + if (e1 instanceof Player) { + Player player = (Player) e1; + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() != bannerFaction) { + continue; + } + for (String effect : effects) { + String[] components = effect.split(":"); + player.addPotionEffect(new PotionEffect(Objects.requireNonNull(PotionEffectType.getByName(components[0])), 100, Integer.parseInt(components[1]))); + } + if (banner.getType() == bannerType) { + continue; + } + banner.setType(bannerType); + } + } + }, 0L, 20L); + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> + { + banner.setType(Material.AIR); + as.remove(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + Bukkit.getScheduler().cancelTask(affectorTask); + FactionsBlockListener.bannerLocations.remove(bannerFaction.getTag()); + }, Long.parseLong(bannerTime + "")); + } else { + fme.msg(TL.WARBANNER_INVALIDLOC); + e.setCancelled(true); + } + } + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onFrostWalker(EntityBlockFormEvent event) - { - if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null) - return; - Player player = (Player) event.getEntity(); - Location location = event.getBlock().getLocation(); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onFrostWalker(EntityBlockFormEvent event) { + if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null) + return; + Player player = (Player) event.getEntity(); + Location location = event.getBlock().getLocation(); - if (!event.getBlock().getType().equals(Material.WATER)) - { - // If we are not replacing water then this is clearly not a frostwalker event. - return; - } + if (!event.getBlock().getType().equals(Material.WATER)) { + // If we are not replacing water then this is clearly not a frostwalker event. + return; + } - // only notify every 10 seconds - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); - if (!justCheck) - fPlayer.setLastFrostwalkerMessage(); + // only notify every 10 seconds + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); + if (!justCheck) + fPlayer.setLastFrostwalkerMessage(); - // Check if they have build permissions here. If not, block this from happening. - if (!playerCanBuildDestroyBlock(player, location, PermissableAction.FROST_WALK, justCheck)) - event.setCancelled(true); - } + // Check if they have build permissions here. If not, block this from happening. + if (!playerCanBuildDestroyBlock(player, location, PermissableAction.FROST_WALK, justCheck)) + event.setCancelled(true); + } - @EventHandler - public void onFallingBlock(EntityChangeBlockEvent event) - { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("Falling-Block-Fix.Enabled")) - return; + @EventHandler + public void onFallingBlock(EntityChangeBlockEvent event) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("Falling-Block-Fix.Enabled")) + return; - Faction faction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - if (faction.isWarZone() || faction.isSafeZone()) - { - event.getBlock().setType(Material.AIR); - event.setCancelled(true); - } - } + Faction faction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + if (faction.isWarZone() || faction.isSafeZone()) { + event.getBlock().setType(Material.AIR); + event.setCancelled(true); + } + } - private boolean canPistonMoveBlock(Faction pistonFaction, Location target) - { - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target)); + private boolean canPistonMoveBlock(Faction pistonFaction, Location target) { + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target)); - if (pistonFaction == otherFaction) - return true; + if (pistonFaction == otherFaction) + return true; - if (otherFaction.isWilderness()) - return !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()); - else if (otherFaction.isSafeZone()) - return !Conf.safeZoneDenyBuild; - else if (otherFaction.isWarZone()) - return !Conf.warZoneDenyBuild; + if (otherFaction.isWilderness()) + return !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()); + else if (otherFaction.isSafeZone()) + return !Conf.safeZoneDenyBuild; + else if (otherFaction.isWarZone()) + return !Conf.warZoneDenyBuild; - Relation rel = pistonFaction.getRelationTo(otherFaction); - return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); - } + Relation rel = pistonFaction.getRelationTo(otherFaction); + return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) - { - // If there is an error its much safer to not allow the block to be broken - try - { - Block block = event.getBlock(); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + // If there is an error its much safer to not allow the block to be broken + try { + Block block = event.getBlock(); - Faction at = Board.getInstance().getFactionAt(new FLocation(block)); - boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial()); - if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.DESTROY, false)) - { - event.setCancelled(true); - return; - } + Faction at = Board.getInstance().getFactionAt(new FLocation(block)); + boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial()); + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissableAction.DESTROY, false)) { + event.setCancelled(true); + return; + } - FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fme == null || !fme.hasFaction()) - return; + FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fme == null || !fme.hasFaction()) + return; - if (isSpawner) - { - Access access = fme.getFaction().getAccess(fme, PermissableAction.SPAWNER); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) - { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "mine spawners"); - } - } + if (isSpawner) { + Access access = fme.getFaction().getAccess(fme, PermissableAction.SPAWNER); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "mine spawners"); + } + } - if (isSpawner && !fme.isAdminBypassing()) - { - ItemStack item = new ItemStack(block.getType(), 1, block.getData()); - if (at != null && at.isNormal()) - { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fplayer != null) - { - BlockState state = block.getState(); - if (state instanceof CreatureSpawner) - { - CreatureSpawner spawner = (CreatureSpawner) state; - item.setDurability(spawner.getSpawnedType().getTypeId()); - } - handleSpawnerUpdate(at, event.getPlayer(), item, LogTimer.TimerSubType.SPAWNER_BREAK); - } - } - } - } - catch (Exception e) - { - event.setCancelled(true); - e.printStackTrace(); - } - } + if (isSpawner && !fme.isAdminBypassing()) { + ItemStack item = new ItemStack(block.getType(), 1, block.getData()); + if (at != null && at.isNormal()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fplayer != null) { + BlockState state = block.getState(); + if (state instanceof CreatureSpawner) { + CreatureSpawner spawner = (CreatureSpawner) state; + item.setDurability(spawner.getSpawnedType().getTypeId()); + } + handleSpawnerUpdate(at, event.getPlayer(), item, LogTimer.TimerSubType.SPAWNER_BREAK); + } + } + } + } catch (Exception e) { + event.setCancelled(true); + e.printStackTrace(); + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void FrameRemove(HangingBreakByEntityEvent event) - { - if (event.getRemover() == null) - return; - if ((event.getRemover() instanceof Player)) - { - if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) - { - Player p = (Player) event.getRemover(); - if (!playerCanBuildDestroyBlock(p, event.getEntity().getLocation(), PermissableAction.DESTROY, true)) - { - event.setCancelled(true); - return; - } - } - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void FrameRemove(HangingBreakByEntityEvent event) { + if (event.getRemover() == null) + return; + if ((event.getRemover() instanceof Player)) { + if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) { + Player p = (Player) event.getRemover(); + if (!playerCanBuildDestroyBlock(p, event.getEntity().getLocation(), PermissableAction.DESTROY, true)) { + event.setCancelled(true); + return; + } + } + } + } - @EventHandler - public void onFarmLandDamage(EntityChangeBlockEvent event) - { - if (event.getEntity() instanceof Player) - { - Player player = (Player) event.getEntity(); - if (!playerCanBuildDestroyBlock(player, event.getBlock().getLocation(), PermissableAction.DESTROY, true)) - { - FPlayer me = FPlayers.getInstance().getByPlayer(player); - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())); - me.msg(TL.ACTION_DENIED_OTHER, otherFaction.getTag(), "trample crops"); - event.setCancelled(true); - } - } - } + @EventHandler + public void onFarmLandDamage(EntityChangeBlockEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (!playerCanBuildDestroyBlock(player, event.getBlock().getLocation(), PermissableAction.DESTROY, true)) { + FPlayer me = FPlayers.getInstance().getByPlayer(player); + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())); + me.msg(TL.ACTION_DENIED_OTHER, otherFaction.getTag(), "trample crops"); + event.setCancelled(true); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java index 1091c054..4a876a3f 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.*; import com.massivecraft.factions.event.PowerLossEvent; import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.util.MiscUtil; -import com.massivecraft.factions.util.timer.type.GraceTimer; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; import org.bukkit.Bukkit; diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java index 4a392b7b..9ee68295 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.*; import com.massivecraft.factions.cmd.CmdFGlobal; import com.massivecraft.factions.cmd.CmdFly; import com.massivecraft.factions.cmd.CmdSeeChunk; -import com.massivecraft.factions.cmd.FCmdRoot; import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.cmd.logout.LogoutHandler; import com.massivecraft.factions.cmd.wild.CmdWild; @@ -36,8 +35,6 @@ import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.TextChannel; import org.bukkit.*; import org.bukkit.block.Block; -import org.bukkit.entity.Boat; -import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; @@ -57,7 +54,9 @@ import java.util.logging.Level; public class FactionsPlayerListener implements Listener { + public final static Map lastLocations = new HashMap<>(); public static Set corners; + public static BukkitTask positionTask = null; /** * @author FactionsUUID Team */ @@ -655,9 +654,6 @@ public class FactionsPlayerListener implements Listener { return (result.length() == 3 ? result + "0" : result) + "/hrs ago"; } - public static BukkitTask positionTask = null; - public final static Map lastLocations = new HashMap<>(); - public void startPositionCheck() { positionTask = Bukkit.getScheduler().runTaskTimer(FactionsPlugin.getInstance(), () -> { if (lastLocations.isEmpty()) return; @@ -741,7 +737,8 @@ public class FactionsPlayerListener implements Listener { me.attemptClaim(me.getAutoClaimFor(), newLocation, true); } FactionsPlugin.instance.logFactionEvent(me.getAutoClaimFor(), FLogType.CHUNK_CLAIMS, me.getName(), CC.GreenB + "CLAIMED", String.valueOf(1), (new FLocation(player.getLocation())).formatXAndZ(",")); - if (Conf.disableFlightOnFactionClaimChange && FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) CmdFly.disableFlight(me); + if (Conf.disableFlightOnFactionClaimChange && FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) + CmdFly.disableFlight(me); } else if (me.isAutoSafeClaimEnabled()) { if (!Permission.MANAGE_SAFE_ZONE.has(player)) { diff --git a/src/main/java/com/massivecraft/factions/shop/ShopGUIFrame.java b/src/main/java/com/massivecraft/factions/shop/ShopGUIFrame.java index 3e79320a..103846d1 100644 --- a/src/main/java/com/massivecraft/factions/shop/ShopGUIFrame.java +++ b/src/main/java/com/massivecraft/factions/shop/ShopGUIFrame.java @@ -26,205 +26,166 @@ import java.util.Set; import java.util.logging.Level; import java.util.stream.Collectors; -public class ShopGUIFrame -{ +public class ShopGUIFrame { - /** - * @author Driftay - */ + /** + * @author Driftay + */ - private Gui gui; + private Gui gui; - public ShopGUIFrame(Faction f) - { - gui = new Gui(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Rows", 4), FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("F-Shop.GUI.Name"))); - } + public ShopGUIFrame(Faction f) { + gui = new Gui(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Rows", 4), FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("F-Shop.GUI.Name"))); + } - public void buildGUI(FPlayer fplayer) - { - PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); - List GUIItems = new ArrayList<>(); - ItemStack dummy = buildDummyItem(fplayer.getFaction()); - for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) - GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true))); + public void buildGUI(FPlayer fplayer) { + PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); + List GUIItems = new ArrayList<>(); + ItemStack dummy = buildDummyItem(fplayer.getFaction()); + for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) + GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true))); - Set items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false); - for (String s : items) - { - if (!checkShopConfig(s)) - { - continue; - } + Set items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false); + for (String s : items) { + if (!checkShopConfig(s)) { + continue; + } - int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".slot"); - ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".block")).get().parseItem(); - int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".cost"); - String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".name"); - boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean("items." + s + ".glowing"); - List lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".lore"); + int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".slot"); + ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".block")).get().parseItem(); + int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".cost"); + String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".name"); + boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean("items." + s + ".glowing"); + List lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".lore"); - assert item != null; - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(FactionsPlugin.instance.color(name)); - meta.addItemFlags(); - if (glowing) - { - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - meta.addEnchant(Enchantment.DURABILITY, 1, true); - } - if (!glowing) - meta.removeEnchant(Enchantment.DURABILITY); - List replacedLore = lore.stream().map(t -> t.replace("{cost}", cost + "")).collect(Collectors.toList()); - meta.setLore(FactionsPlugin.instance.colorList(replacedLore)); - item.setItemMeta(meta); - GUIItems.set(slot, new GuiItem(item, e -> - { - e.setCancelled(true); - FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); - if (fplayer.getFaction().getPoints() >= cost) - { - if (runCommands(FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".cmds"), fplayer.getPlayer())) - { - fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost); - for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) - { - fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString().replace("{player}", fplayer.getPlayer().getName()).replace("{item}", ChatColor.stripColor(FactionsPlugin.getInstance().color(name))) - .replace("{cost}", cost + "")); - } - buildGUI(fme); - } - else - { - fplayer.msg(TL.SHOP_ERROR_DURING_PURCHASE); - } - } - else - { - fplayer.msg(TL.SHOP_NOT_ENOUGH_POINTS); - } - })); - pane.populateWithGuiItems(GUIItems); - gui.addPane(pane); - gui.update(); - gui.show(fplayer.getPlayer()); - } - } + assert item != null; + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(FactionsPlugin.instance.color(name)); + meta.addItemFlags(); + if (glowing) { + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + meta.addEnchant(Enchantment.DURABILITY, 1, true); + } + if (!glowing) + meta.removeEnchant(Enchantment.DURABILITY); + List replacedLore = lore.stream().map(t -> t.replace("{cost}", cost + "")).collect(Collectors.toList()); + meta.setLore(FactionsPlugin.instance.colorList(replacedLore)); + item.setItemMeta(meta); + GUIItems.set(slot, new GuiItem(item, e -> + { + e.setCancelled(true); + FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); + if (fplayer.getFaction().getPoints() >= cost) { + if (runCommands(FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".cmds"), fplayer.getPlayer())) { + fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost); + for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) { + fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString().replace("{player}", fplayer.getPlayer().getName()).replace("{item}", ChatColor.stripColor(FactionsPlugin.getInstance().color(name))) + .replace("{cost}", cost + "")); + } + buildGUI(fme); + } else { + fplayer.msg(TL.SHOP_ERROR_DURING_PURCHASE); + } + } else { + fplayer.msg(TL.SHOP_NOT_ENOUGH_POINTS); + } + })); + pane.populateWithGuiItems(GUIItems); + gui.addPane(pane); + gui.update(); + gui.show(fplayer.getPlayer()); + } + } - private ItemStack buildDummyItem(Faction f) - { - ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("F-Shop.GUI.dummy-item"); - ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); - ItemMeta meta = item.getItemMeta(); - if (meta != null) - { - meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name").replace("{points}", f.getPoints() + ""))); - item.setItemMeta(meta); - } - return item; - } + private ItemStack buildDummyItem(Faction f) { + ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("F-Shop.GUI.dummy-item"); + ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); + ItemMeta meta = item.getItemMeta(); + if (meta != null) { + meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name").replace("{points}", f.getPoints() + ""))); + item.setItemMeta(meta); + } + return item; + } - public boolean checkShopConfig() - { - boolean ret = true; - Set items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false); - for (String s : items) - { - if (checkShopConfig(s) == false) - { - ret = false; - } - } - return ret; - } + public boolean checkShopConfig() { + boolean ret = true; + Set items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false); + for (String s : items) { + if (checkShopConfig(s) == false) { + ret = false; + } + } + return ret; + } - public boolean checkShopConfig(String s) - { - boolean ret = true; - if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".slot")) - { - FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item \'" + s + "\' missing slot variable"); - ret = false; - } - if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".block")) - { - FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item \'" + s + "\' missing block variable"); - ret = false; - } + public boolean checkShopConfig(String s) { + boolean ret = true; + if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".slot")) { + FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing slot variable"); + ret = false; + } + if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".block")) { + FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing block variable"); + ret = false; + } - if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cmds")) - { - FactionsPlugin.getInstance().log(Level.WARNING, "Problee with config item \'" + s + "\' missing cmds variable"); - ret = false; - } + if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cmds")) { + FactionsPlugin.getInstance().log(Level.WARNING, "Problee with config item '" + s + "' missing cmds variable"); + ret = false; + } - if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cost")) - { - FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item \'" + s + "\' missing cost variable this item will cost 0"); - } - if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".name")) - { - FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item \'" + s + "\' missing name variable"); - ret = false; - } - return ret; - } + if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cost")) { + FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing cost variable this item will cost 0"); + } + if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".name")) { + FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing name variable"); + ret = false; + } + return ret; + } - /** - * - * @param list - * The list of commands to be ran. - * @param p - * The player that is using the shop - * @return if all commands are able to be ran or if they did run. - */ - public boolean runCommands(List list, Player p) - { - for (String cmd : list) - { - cmd = cmd.replace("%player%", p.getName()); - if (cmd.toLowerCase().startsWith("give")) - { - String[] args = cmd.split(" "); - if (args.length == 4) - { - Material material = Material.matchMaterial(args[2]); - int amount = Integer.parseInt(args[3]); - Player player = Bukkit.getPlayer(args[1]); - if (!player.isOnline()) - { - return false; - } - // See if the player has this item in their inventory; - if (player.getInventory().contains(material) && player.getInventory().firstEmpty() < 0) - { - int spacesAvailable = 0; - Map contents = player.getInventory().all(material); - for (ItemStack stack : contents.values()) - { - spacesAvailable += stack.getMaxStackSize() - stack.getAmount(); - } - if (spacesAvailable < amount) - { - return false; - } + /** + * @param list The list of commands to be ran. + * @param p The player that is using the shop + * @return if all commands are able to be ran or if they did run. + */ + public boolean runCommands(List list, Player p) { + for (String cmd : list) { + cmd = cmd.replace("%player%", p.getName()); + if (cmd.toLowerCase().startsWith("give")) { + String[] args = cmd.split(" "); + if (args.length == 4) { + Material material = Material.matchMaterial(args[2]); + int amount = Integer.parseInt(args[3]); + Player player = Bukkit.getPlayer(args[1]); + if (!player.isOnline()) { + return false; + } + // See if the player has this item in their inventory; + if (player.getInventory().contains(material) && player.getInventory().firstEmpty() < 0) { + int spacesAvailable = 0; + Map contents = player.getInventory().all(material); + for (ItemStack stack : contents.values()) { + spacesAvailable += stack.getMaxStackSize() - stack.getAmount(); + } + if (spacesAvailable < amount) { + return false; + } - } - else - { - if (player.getInventory().firstEmpty() < 0) - { - return false; - } - } - } - } - } - for (String cmd : list) - { - cmd = cmd.replace("%player%", p.getName()); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - return true; - } + } else { + if (player.getInventory().firstEmpty() < 0) { + return false; + } + } + } + } + } + for (String cmd : list) { + cmd = cmd.replace("%player%", p.getName()); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); + } + return true; + } } diff --git a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java index 8d00c614..889be1d3 100644 --- a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java +++ b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java @@ -15,12 +15,15 @@ import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; -import java.util.Arrays; import java.util.UUID; import java.util.logging.Level; public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational { + private static void logInvalid(String placeholder) { + FactionsPlugin.getInstance().getLogger().log(Level.INFO, "Invalid request through PlaceholderAPI for placeholder '" + placeholder + "'"); + } + // Identifier for this expansion @Override public String getIdentifier() { @@ -214,7 +217,7 @@ public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements R case "faction_relation_color": return fPlayer.getColorTo(faction).toString(); case "grace_time": - if(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() >= 0) { + if (FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() >= 0) { return String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)); } else { return TL.GRACE_DISABLED_PLACEHOLDER.toString(); @@ -249,10 +252,6 @@ public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements R return TL.PLACEHOLDERAPI_NULL.toString(); } - private static void logInvalid(String placeholder) { - FactionsPlugin.getInstance().getLogger().log(Level.INFO, "Invalid request through PlaceholderAPI for placeholder '" + placeholder + "'"); - } - private int countOn(Faction f, Relation relation, Boolean status, FPlayer player) { int count = 0; for (Faction faction : Factions.getInstance().getAllFactions()) { diff --git a/src/main/java/com/massivecraft/factions/util/Cooldown.java b/src/main/java/com/massivecraft/factions/util/Cooldown.java index c9011fd3..510fc6db 100644 --- a/src/main/java/com/massivecraft/factions/util/Cooldown.java +++ b/src/main/java/com/massivecraft/factions/util/Cooldown.java @@ -3,7 +3,6 @@ package com.massivecraft.factions.util; import com.massivecraft.factions.FactionsPlugin; import org.bukkit.entity.Player; import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.metadata.MetadataValue; import java.util.concurrent.TimeUnit; diff --git a/src/main/java/com/massivecraft/factions/util/timer/GlobalTimer.java b/src/main/java/com/massivecraft/factions/util/timer/GlobalTimer.java index 6eddd4d8..c72d30ff 100644 --- a/src/main/java/com/massivecraft/factions/util/timer/GlobalTimer.java +++ b/src/main/java/com/massivecraft/factions/util/timer/GlobalTimer.java @@ -1,12 +1,5 @@ package com.massivecraft.factions.util.timer; -import com.massivecraft.factions.util.Config; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - /** * Factions - Developed by Driftay. * All rights reserved 2020. diff --git a/src/main/java/com/massivecraft/factions/util/timer/Timer.java b/src/main/java/com/massivecraft/factions/util/timer/Timer.java index d04bcdaf..c30779bb 100644 --- a/src/main/java/com/massivecraft/factions/util/timer/Timer.java +++ b/src/main/java/com/massivecraft/factions/util/timer/Timer.java @@ -8,8 +8,8 @@ import com.massivecraft.factions.util.Config; * Creation Date: 4/7/2020 */ public abstract class Timer { - protected final String name; public final long defaultCooldown; + protected final String name; public Timer(String name, long defaultCooldown) { diff --git a/src/main/java/com/massivecraft/factions/util/timer/TimerManager.java b/src/main/java/com/massivecraft/factions/util/timer/TimerManager.java index f79e5fb4..39e66461 100644 --- a/src/main/java/com/massivecraft/factions/util/timer/TimerManager.java +++ b/src/main/java/com/massivecraft/factions/util/timer/TimerManager.java @@ -16,14 +16,24 @@ import java.util.concurrent.TimeUnit; * Creation Date: 4/7/2020 */ public class TimerManager implements Listener, Runnable { - private final Set timers; - private final FactionsPlugin plugin; - private final List timerRunnableList = new ArrayList<>(); - private Config config; - public GraceTimer graceTimer; private static final long MINUTE = TimeUnit.MINUTES.toMillis(1L); private static final long HOUR = TimeUnit.HOURS.toMillis(1L); private static final long MULTI_HOUR = TimeUnit.HOURS.toMillis(10); + private final Set timers; + private final FactionsPlugin plugin; + private final List timerRunnableList = new ArrayList<>(); + public GraceTimer graceTimer; + private Config config; + + public TimerManager(FactionsPlugin plugin) { + this.timers = new HashSet<>(); + this.plugin = plugin; + plugin.getServer().getPluginManager().registerEvents(this, plugin); + if (Conf.useGraceSystem) { + this.registerTimer(this.graceTimer = new GraceTimer()); + } + plugin.getServer().getScheduler().runTaskTimer(plugin, this, 4, 4); + } public static String getRemaining(long millis, boolean milliseconds) { return getRemaining(millis, milliseconds, true); @@ -31,21 +41,11 @@ public class TimerManager implements Listener, Runnable { public static String getRemaining(long duration, boolean milliseconds, boolean trail) { if ((milliseconds) && (duration < MINUTE)) { - return ( (trail ? DateTimeFormats.REMAINING_SECONDS_TRAILING : DateTimeFormats.REMAINING_SECONDS).get()).format(duration * 0.001D) + 's'; + return ((trail ? DateTimeFormats.REMAINING_SECONDS_TRAILING : DateTimeFormats.REMAINING_SECONDS).get()).format(duration * 0.001D) + 's'; } return DurationFormatUtils.formatDuration(duration, (duration >= HOUR ? (duration >= MULTI_HOUR ? "d" : "") + "d:" : "") + "HH:mm:ss"); } - public TimerManager(FactionsPlugin plugin) { - this.timers = new HashSet<>(); - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - if(Conf.useGraceSystem) { - this.registerTimer(this.graceTimer = new GraceTimer()); - } - plugin.getServer().getScheduler().runTaskTimer(plugin, this, 4, 4); - } - public Collection getTimers() { return this.timers; } diff --git a/src/main/java/com/massivecraft/factions/util/timer/TimerRunnable.java b/src/main/java/com/massivecraft/factions/util/timer/TimerRunnable.java index af426821..e26aa09a 100644 --- a/src/main/java/com/massivecraft/factions/util/timer/TimerRunnable.java +++ b/src/main/java/com/massivecraft/factions/util/timer/TimerRunnable.java @@ -45,15 +45,13 @@ public class TimerRunnable { return getRemaining(false); } - public long getRemaining(long now) { - return getRemaining(false, now); - } - - public void setRemaining(long remaining) { setExpiryMillis(remaining); } + public long getRemaining(long now) { + return getRemaining(false, now); + } public long getRemaining(boolean ignorePaused) { if ((!ignorePaused) && (this.pauseMillis != 0L)) return this.pauseMillis; diff --git a/src/main/java/com/massivecraft/factions/util/timer/type/GraceTimer.java b/src/main/java/com/massivecraft/factions/util/timer/type/GraceTimer.java index f5a740df..2dcf9128 100644 --- a/src/main/java/com/massivecraft/factions/util/timer/type/GraceTimer.java +++ b/src/main/java/com/massivecraft/factions/util/timer/type/GraceTimer.java @@ -26,14 +26,14 @@ public class GraceTimer extends GlobalTimer implements Listener { @EventHandler public void onBreak(EntityExplodeEvent e) { - if(getRemaining() > 0) - e.setCancelled(true); + if (getRemaining() > 0) + e.setCancelled(true); } @EventHandler public void onTNTPlace(BlockPlaceEvent event) { FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if(getRemaining() > 0) { + if (getRemaining() > 0) { if (!fp.isAdminBypassing()) { if (event.getBlock().getType().equals(Material.TNT)) { event.setCancelled(true); diff --git a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java index cc7c4a9b..efad4167 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java @@ -3,7 +3,10 @@ package com.massivecraft.factions.zcore; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import com.massivecraft.factions.*; +import com.massivecraft.factions.Board; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; import com.massivecraft.factions.zcore.persist.SaveTask; import com.massivecraft.factions.zcore.util.PermUtil; import com.massivecraft.factions.zcore.util.Persist; diff --git a/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java b/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java index 69debea6..6dbe1b36 100644 --- a/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java +++ b/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java @@ -55,9 +55,9 @@ public class CustomFile { e.printStackTrace(); } } - + public boolean containsKey(String key) { - return getCachedObjects().containsKey(key)|| getConfig().contains(key); + return getCachedObjects().containsKey(key) || getConfig().contains(key); } public String fetchString(String key) { diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java index 8d9ad3fb..db16416a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java @@ -6,13 +6,11 @@ import com.github.stefvanschie.inventoryframework.pane.PaginatedPane; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.Faction; import com.massivecraft.factions.FactionsPlugin; -import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.util.XMaterial; import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.Permissable; import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.util.TL; -import org.bukkit.ChatColor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; diff --git a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FUpgradeFrame.java b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FUpgradeFrame.java index bae1fe27..21d6cc00 100644 --- a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FUpgradeFrame.java +++ b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FUpgradeFrame.java @@ -16,7 +16,6 @@ import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * @author Saser @@ -36,7 +35,8 @@ public class FUpgradeFrame { PaginatedPane pane = new PaginatedPane(0, 0, 9, this.gui.getRows()); List GUIItems = new ArrayList<>(); ItemStack dummy = buildDummyItem(); - for (int x = 0; x <= this.gui.getRows() * 9 - 1; ++x) GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true))); + for (int x = 0; x <= this.gui.getRows() * 9 - 1; ++x) + GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true))); for (UpgradeType value : UpgradeType.values()) { if (value.getSlot() != -1) { GUIItems.set(value.getSlot(), new GuiItem(value.buildAsset(fplayer.getFaction()), e -> { @@ -44,19 +44,19 @@ public class FUpgradeFrame { FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); if (fme.getFaction().getUpgrade(value) == value.getMaxLevel()) return; int cost = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu." + value.toString() + ".Cost.level-" + (fme.getFaction().getUpgrade(value) + 1)); - if (fme.hasMoney(cost)) { - fme.takeMoney(cost); - if (value == UpgradeType.CHEST) updateChests(fme.getFaction()); + if (fme.hasMoney(cost)) { + fme.takeMoney(cost); + if (value == UpgradeType.CHEST) updateChests(fme.getFaction()); - if (value == UpgradeType.POWER) updateFactionPowerBoost(fme.getFaction()); + if (value == UpgradeType.POWER) updateFactionPowerBoost(fme.getFaction()); - if (value == UpgradeType.TNT) updateTNT(fme.getFaction()); + if (value == UpgradeType.TNT) updateTNT(fme.getFaction()); - if (value == UpgradeType.WARP) updateWarps(fme.getFaction()); + if (value == UpgradeType.WARP) updateWarps(fme.getFaction()); - fme.getFaction().setUpgrade(value, fme.getFaction().getUpgrade(value) + 1); - buildGUI(fme); - } + fme.getFaction().setUpgrade(value, fme.getFaction().getUpgrade(value) + 1); + buildGUI(fme); + } })); } } diff --git a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/UpgradesListener.java b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/UpgradesListener.java index 438be790..3ae68a1c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/UpgradesListener.java +++ b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/UpgradesListener.java @@ -28,7 +28,7 @@ public class UpgradesListener implements Listener { if (e.isCancelled()) return; if (!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) return; - if(e.getEntity() == null) return; + if (e.getEntity() == null) return; FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getEntity()); FPlayer dame = FPlayers.getInstance().getByPlayer((Player) e.getDamager()); @@ -36,7 +36,7 @@ public class UpgradesListener implements Listener { if (fme == null || dame == null) return; FLocation floc = new FLocation(fme.getPlayer().getLocation()); - if(floc == null) return; + if (floc == null) return; if (Board.getInstance().getFactionAt(floc) == fme.getFaction()) { if (dame.getFaction() == fme.getFaction()) return; diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java index a02263be..06901d3b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java @@ -738,7 +738,7 @@ public abstract class MemoryFPlayer implements FPlayer { public void sendFactionHereMessage(Faction from) { Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); - if(Conf.worldsNoClaiming.contains(getLastStoodAt().getWorldName())) return; + if (Conf.worldsNoClaiming.contains(getLastStoodAt().getWorldName())) return; if (showInfoBoard(toShow)) { FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); @@ -860,7 +860,7 @@ public abstract class MemoryFPlayer implements FPlayer { int factionBuffer = plugin.getConfig().getInt("hcf.buffer-zone", 0); int worldBuffer = plugin.getConfig().getInt("world-border.buffer", 0) - 1; - if (Conf.worldGuardChecking && Worldguard.getInstance().checkForRegionsInChunk(flocation)) { + if (Conf.worldGuardChecking && Worldguard.getInstance().checkForRegionsInChunk(flocation)) { // Checks for WorldGuard regions in the chunk attempting to be claimed error = plugin.txt.parse(TL.CLAIM_PROTECTED.toString()); } else if (flocation.isOutsideWorldBorder(plugin.getConfig().getInt("world-border.buffer", 0) - 1)) { @@ -873,7 +873,7 @@ public abstract class MemoryFPlayer implements FPlayer { return true; } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { return true; - } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW && forFaction != currentFaction ) { + } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW && forFaction != currentFaction) { return true; } else if (myFaction != forFaction) { error = plugin.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); @@ -972,39 +972,38 @@ public abstract class MemoryFPlayer implements FPlayer { } public void setFFlying(boolean fly, boolean damage) { - if(FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) - { - Player player = getPlayer(); - if (player == null) return; - - player.setAllowFlight(fly); - player.setFlying(fly); - - if (!damage) { - msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); - if (!fly) { - sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + "")); - } - } else { - msg(TL.COMMAND_FLY_DAMAGE); - } - - // If leaving fly mode, don't let them take fall damage for x seconds. - if (!fly) { - int cooldown = FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3); - CmdFly.flyMap.remove(player.getName()); - - // If the value is 0 or lower, make them take fall damage. - // Otherwise, start a timer and have this cancel after a few seconds. - // Short task so we're just doing it in method. Not clean but eh. - if (cooldown > 0) { - setTakeFallDamage(false); - Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> setTakeFallDamage(true), 20L * cooldown); - } - } - - isFlying = fly; - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) { + Player player = getPlayer(); + if (player == null) return; + + player.setAllowFlight(fly); + player.setFlying(fly); + + if (!damage) { + msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); + if (!fly) { + sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + "")); + } + } else { + msg(TL.COMMAND_FLY_DAMAGE); + } + + // If leaving fly mode, don't let them take fall damage for x seconds. + if (!fly) { + int cooldown = FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3); + CmdFly.flyMap.remove(player.getName()); + + // If the value is 0 or lower, make them take fall damage. + // Otherwise, start a timer and have this cancel after a few seconds. + // Short task so we're just doing it in method. Not clean but eh. + if (cooldown > 0) { + setTakeFallDamage(false); + Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> setTakeFallDamage(true), 20L * cooldown); + } + } + + isFlying = fly; + } } public boolean isInFactionsChest() { @@ -1223,11 +1222,11 @@ public abstract class MemoryFPlayer implements FPlayer { } - public boolean hasFriendlyFire(){ + public boolean hasFriendlyFire() { return friendlyFire; } - public void setFriendlyFire(boolean status){ + public void setFriendlyFire(boolean status) { friendlyFire = status; } @@ -1305,7 +1304,7 @@ public abstract class MemoryFPlayer implements FPlayer { // announce success - if(!FactionsPlugin.cachedRadiusClaim) { + if (!FactionsPlugin.cachedRadiusClaim) { Set informTheseFPlayers = new HashSet<>(); informTheseFPlayers.add(this); informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java index cc363f59..9a4452c2 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java @@ -1277,7 +1277,7 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator { if (Conf.logFactionDisband) FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + "."); - if(FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast")) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast")) { for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) fplayer.msg(TL.COMMAND_DISBAND_BROADCAST_GENERIC, this.getTag(fplayer)); }