diff --git a/pom.xml b/pom.xml index 11a83a20..2f7772bd 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ UTF-8 - + clean package install Factions diff --git a/src/main/java/com/massivecraft/factions/Board.java b/src/main/java/com/massivecraft/factions/Board.java index cb166235..3e56622a 100644 --- a/src/main/java/com/massivecraft/factions/Board.java +++ b/src/main/java/com/massivecraft/factions/Board.java @@ -1,383 +1,320 @@ package com.massivecraft.factions; -import java.io.*; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.bukkit.ChatColor; -import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; import com.massivecraft.factions.integration.LWCFeatures; import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.util.AsciiCompass; import com.massivecraft.factions.zcore.util.DiscUtil; +import org.bukkit.ChatColor; +import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; + +import java.io.File; +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; -public class Board -{ - private static transient File file = new File(P.p.getDataFolder(), "board.json"); - private static transient HashMap flocationIds = new HashMap(); - - //----------------------------------------------// - // Get and Set - //----------------------------------------------// - public static String getIdAt(FLocation flocation) - { - if ( ! flocationIds.containsKey(flocation)) - { - return "0"; - } - - return flocationIds.get(flocation); - } - - public static Faction getFactionAt(FLocation flocation) - { - return Factions.i.get(getIdAt(flocation)); - } - - public static void setIdAt(String id, FLocation flocation) - { - clearOwnershipAt(flocation); +public class Board { + private static transient File file = new File(P.p.getDataFolder(), "board.json"); + private static transient HashMap flocationIds = new HashMap(); - if (id == "0") - { - removeAt(flocation); - } - - flocationIds.put(flocation, id); - } - - public static void setFactionAt(Faction faction, FLocation flocation) - { - setIdAt(faction.getId(), flocation); - } - - public static void removeAt(FLocation flocation) - { - clearOwnershipAt(flocation); - flocationIds.remove(flocation); - } - - // not to be confused with claims, ownership referring to further member-specific ownership of a claim - public static void clearOwnershipAt(FLocation flocation) - { - Faction faction = getFactionAt(flocation); - if (faction != null && faction.isNormal()) - { - faction.clearClaimOwnership(flocation); - } - } - - public static void unclaimAll(String factionId) - { - Faction faction = Factions.i.get(factionId); - if (faction != null && faction.isNormal()) - { - faction.clearAllClaimOwnership(); - } + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public static String getIdAt(FLocation flocation) { + if (!flocationIds.containsKey(flocation)) { + return "0"; + } - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) - { - Entry entry = iter.next(); - if (entry.getValue().equals(factionId)) - { - if(Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) - { - LWCFeatures.clearAllChests(entry.getKey()); - } - iter.remove(); - } - } - } + return flocationIds.get(flocation); + } - // Is this coord NOT completely surrounded by coords claimed by the same faction? - // Simpler: Is there any nearby coord with a faction other than the faction here? - public static boolean isBorderLocation(FLocation flocation) - { - Faction faction = getFactionAt(flocation); - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); - } + public static Faction getFactionAt(FLocation flocation) { + return Factions.i.get(getIdAt(flocation)); + } - // Is this coord connected to any coord claimed by the specified faction? - public static boolean isConnectedLocation(FLocation flocation, Faction faction) - { - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); - } - - - //----------------------------------------------// - // Cleaner. Remove orphaned foreign keys - //----------------------------------------------// - - public static void clean() - { - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if ( ! Factions.i.exists(entry.getValue())) - { - if(Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) - { - LWCFeatures.clearAllChests(entry.getKey()); - } - P.p.log("Board cleaner removed "+entry.getValue()+" from "+entry.getKey()); - iter.remove(); - } - } - } - - //----------------------------------------------// - // Coord count - //----------------------------------------------// - - public static int getFactionCoordCount(String factionId) - { - int ret = 0; - for (String thatFactionId : flocationIds.values()) - { - if(thatFactionId.equals(factionId)) - { - ret += 1; - } - } - return ret; - } - - public static int getFactionCoordCount(Faction faction) - { - return getFactionCoordCount(faction.getId()); - } - - public static int getFactionCoordCountInWorld(Faction faction, String worldName) - { - String factionId = faction.getId(); - int ret = 0; - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) - { - ret += 1; - } - } - return ret; - } - - //----------------------------------------------// - // Map generation - //----------------------------------------------// - - /** - * The map is relative to a coord and a faction - * north is in the direction of decreasing x - * east is in the direction of decreasing z - */ - public static ArrayList getMap(Faction faction, FLocation flocation, double inDegrees) - { - ArrayList ret = new ArrayList(); - Faction factionLoc = getFactionAt(flocation); - ret.add(P.p.txt.titleize("("+flocation.getCoordString()+") "+factionLoc.getTag(faction))); - - int halfWidth = Conf.mapWidth / 2; - int halfHeight = Conf.mapHeight / 2; - FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); - int width = halfWidth * 2 + 1; - int height = halfHeight * 2 + 1; - - if (Conf.showMapFactionKey) - { - height--; - } - - Map fList = new HashMap(); - int chrIdx = 0; - - // For each row - for (int dz = 0; dz < height; dz++) - { - // Draw and add that row - String row = ""; - for (int dx = 0; dx < width; dx++) - { - if(dx == halfWidth && dz == halfHeight) - { - row += ChatColor.AQUA+"+"; - } - else - { - FLocation flocationHere = topLeft.getRelative(dx, dz); - Faction factionHere = getFactionAt(flocationHere); - Relation relation = faction.getRelationTo(factionHere); - if (factionHere.isNone()) - { - row += ChatColor.GRAY+"-"; - } - else if (factionHere.isSafeZone()) - { - row += Conf.colorPeaceful+"+"; - } - else if (factionHere.isWarZone()) - { - row += ChatColor.DARK_RED+"+"; - } - else if - ( - factionHere == faction - || - factionHere == factionLoc - || - relation.isAtLeast(Relation.ALLY) - || - (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) - || - (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) - ) - { - if (!fList.containsKey(factionHere.getTag())) - fList.put(factionHere.getTag(), Conf.mapKeyChrs[chrIdx++]); - char tag = fList.get(factionHere.getTag()); - row += factionHere.getColorTo(faction) + "" + tag; - } - else - { - row += ChatColor.GRAY+"-"; - } - } - } - ret.add(row); - } - - // Get the compass - ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.RED, P.p.txt.parse("")); + public static void setIdAt(String id, FLocation flocation) { + clearOwnershipAt(flocation); - // Add the compass - ret.set(1, asciiCompass.get(0)+ret.get(1).substring(3*3)); - ret.set(2, asciiCompass.get(1)+ret.get(2).substring(3*3)); - ret.set(3, asciiCompass.get(2)+ret.get(3).substring(3*3)); - - // Add the faction key - if (Conf.showMapFactionKey) - { - String fRow = ""; - for(String key : fList.keySet()) - { - fRow += String.format("%s%s: %s ", ChatColor.GRAY, fList.get(key), key); - } - ret.add(fRow); - } - - return ret; - } - - - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // - - public static Map> dumpAsSaveFormat() - { - Map> worldCoordIds = new HashMap>(); - - String worldName, coords; - String id; - - for (Entry entry : flocationIds.entrySet()) - { - worldName = entry.getKey().getWorldName(); - coords = entry.getKey().getCoordString(); - id = entry.getValue(); - if ( ! worldCoordIds.containsKey(worldName)) - { - worldCoordIds.put(worldName, new TreeMap()); - } - - worldCoordIds.get(worldName).put(coords, id); - } - - return worldCoordIds; - } - - public static void loadFromSaveFormat(Map> worldCoordIds) - { - flocationIds.clear(); - - String worldName; - String[] coords; - int x, z; - String factionId; - - for (Entry> entry : worldCoordIds.entrySet()) - { - worldName = entry.getKey(); - for (Entry entry2 : entry.getValue().entrySet()) - { - coords = entry2.getKey().trim().split("[,\\s]+"); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); - factionId = entry2.getValue(); - flocationIds.put(new FLocation(worldName, x, z), factionId); - } - } - } - - public static boolean save() - { - //Factions.log("Saving board to disk"); - - try - { - DiscUtil.write(file, P.p.gson.toJson(dumpAsSaveFormat())); - } - catch (Exception e) - { - e.printStackTrace(); - P.p.log("Failed to save the board to disk."); - return false; - } - - return true; - } - - public static boolean load() - { - P.p.log("Loading board from disk"); - - if ( ! file.exists()) - { - P.p.log("No board to load from disk. Creating new file."); - save(); - return true; - } - - try - { - Type type = new TypeToken>>(){}.getType(); - Map> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); - loadFromSaveFormat(worldCoordIds); - } - catch (Exception e) - { - e.printStackTrace(); - P.p.log("Failed to load the board from disk."); - return false; - } - - return true; - } + if (id == "0") { + removeAt(flocation); + } + + flocationIds.put(flocation, id); + } + + public static void setFactionAt(Faction faction, FLocation flocation) { + setIdAt(faction.getId(), flocation); + } + + public static void removeAt(FLocation flocation) { + clearOwnershipAt(flocation); + flocationIds.remove(flocation); + } + + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public static void clearOwnershipAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + if (faction != null && faction.isNormal()) { + faction.clearClaimOwnership(flocation); + } + } + + public static void unclaimAll(String factionId) { + Faction faction = Factions.i.get(factionId); + if (faction != null && faction.isNormal()) { + faction.clearAllClaimOwnership(); + } + + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (entry.getValue().equals(factionId)) { + if (Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) { + LWCFeatures.clearAllChests(entry.getKey()); + } + iter.remove(); + } + } + } + + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public static boolean isBorderLocation(FLocation flocation) { + Faction faction = getFactionAt(flocation); + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); + } + + // Is this coord connected to any coord claimed by the specified faction? + public static boolean isConnectedLocation(FLocation flocation, Faction faction) { + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); + } + + + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// + + public static void clean() { + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (!Factions.i.exists(entry.getValue())) { + if (Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) { + LWCFeatures.clearAllChests(entry.getKey()); + } + P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); + iter.remove(); + } + } + } + + //----------------------------------------------// + // Coord count + //----------------------------------------------// + + public static int getFactionCoordCount(String factionId) { + int ret = 0; + for (String thatFactionId : flocationIds.values()) { + if (thatFactionId.equals(factionId)) { + ret += 1; + } + } + return ret; + } + + public static int getFactionCoordCount(Faction faction) { + return getFactionCoordCount(faction.getId()); + } + + public static int getFactionCoordCountInWorld(Faction faction, String worldName) { + String factionId = faction.getId(); + int ret = 0; + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { + ret += 1; + } + } + return ret; + } + + //----------------------------------------------// + // Map generation + //----------------------------------------------// + + /** + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public static ArrayList getMap(Faction faction, FLocation flocation, double inDegrees) { + ArrayList ret = new ArrayList(); + Faction factionLoc = getFactionAt(flocation); + ret.add(P.p.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(faction))); + + int halfWidth = Conf.mapWidth / 2; + int halfHeight = Conf.mapHeight / 2; + FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); + int width = halfWidth * 2 + 1; + int height = halfHeight * 2 + 1; + + if (Conf.showMapFactionKey) { + height--; + } + + Map fList = new HashMap(); + int chrIdx = 0; + + // For each row + for (int dz = 0; dz < height; dz++) { + // Draw and add that row + String row = ""; + for (int dx = 0; dx < width; dx++) { + if (dx == halfWidth && dz == halfHeight) { + row += ChatColor.AQUA + "+"; + } else { + FLocation flocationHere = topLeft.getRelative(dx, dz); + Faction factionHere = getFactionAt(flocationHere); + Relation relation = faction.getRelationTo(factionHere); + if (factionHere.isNone()) { + row += ChatColor.GRAY + "-"; + } else if (factionHere.isSafeZone()) { + row += Conf.colorPeaceful + "+"; + } else if (factionHere.isWarZone()) { + row += ChatColor.DARK_RED + "+"; + } else if + ( + factionHere == faction + || + factionHere == factionLoc + || + relation.isAtLeast(Relation.ALLY) + || + (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) + || + (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) + ) { + if (!fList.containsKey(factionHere.getTag())) + fList.put(factionHere.getTag(), Conf.mapKeyChrs[chrIdx++]); + char tag = fList.get(factionHere.getTag()); + row += factionHere.getColorTo(faction) + "" + tag; + } else { + row += ChatColor.GRAY + "-"; + } + } + } + ret.add(row); + } + + // Get the compass + ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.RED, P.p.txt.parse("")); + + // Add the compass + ret.set(1, asciiCompass.get(0) + ret.get(1).substring(3 * 3)); + ret.set(2, asciiCompass.get(1) + ret.get(2).substring(3 * 3)); + ret.set(3, asciiCompass.get(2) + ret.get(3).substring(3 * 3)); + + // Add the faction key + if (Conf.showMapFactionKey) { + String fRow = ""; + for (String key : fList.keySet()) { + fRow += String.format("%s%s: %s ", ChatColor.GRAY, fList.get(key), key); + } + ret.add(fRow); + } + + return ret; + } + + + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // + + public static Map> dumpAsSaveFormat() { + Map> worldCoordIds = new HashMap>(); + + String worldName, coords; + String id; + + for (Entry entry : flocationIds.entrySet()) { + worldName = entry.getKey().getWorldName(); + coords = entry.getKey().getCoordString(); + id = entry.getValue(); + if (!worldCoordIds.containsKey(worldName)) { + worldCoordIds.put(worldName, new TreeMap()); + } + + worldCoordIds.get(worldName).put(coords, id); + } + + return worldCoordIds; + } + + public static void loadFromSaveFormat(Map> worldCoordIds) { + flocationIds.clear(); + + String worldName; + String[] coords; + int x, z; + String factionId; + + for (Entry> entry : worldCoordIds.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + factionId = entry2.getValue(); + flocationIds.put(new FLocation(worldName, x, z), factionId); + } + } + } + + public static boolean save() { + //Factions.log("Saving board to disk"); + + try { + DiscUtil.write(file, P.p.gson.toJson(dumpAsSaveFormat())); + } catch (Exception e) { + e.printStackTrace(); + P.p.log("Failed to save the board to disk."); + return false; + } + + return true; + } + + public static boolean load() { + P.p.log("Loading board from disk"); + + if (!file.exists()) { + P.p.log("No board to load from disk. Creating new file."); + save(); + return true; + } + + try { + Type type = new TypeToken>>() { + }.getType(); + Map> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); + loadFromSaveFormat(worldCoordIds); + } catch (Exception e) { + e.printStackTrace(); + P.p.log("Failed to load the board from disk."); + return false; + } + + return true; + } } diff --git a/src/main/java/com/massivecraft/factions/Conf.java b/src/main/java/com/massivecraft/factions/Conf.java index df055ca8..febbe3db 100644 --- a/src/main/java/com/massivecraft/factions/Conf.java +++ b/src/main/java/com/massivecraft/factions/Conf.java @@ -1,385 +1,383 @@ package com.massivecraft.factions; -import java.util.*; - import org.bukkit.*; import org.bukkit.entity.EntityType; -public class Conf -{ - public static List baseCommandAliases = new ArrayList(); - public static boolean allowNoSlashCommand = true; - - // Colors - public static ChatColor colorMember = ChatColor.GREEN; - public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; - public static ChatColor colorNeutral = ChatColor.WHITE; - public static ChatColor colorEnemy = ChatColor.RED; - - public static ChatColor colorPeaceful = ChatColor.GOLD; - public static ChatColor colorWar = ChatColor.DARK_RED; - //public static ChatColor colorWilderness = ChatColor.DARK_GREEN; - - // Power - public static double powerPlayerMax = 10.0; - public static double powerPlayerMin = -10.0; - public static double powerPlayerStarting = 0.0; - public static double powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one power - public static double powerPerDeath = 4.0; // A death makes you lose 4 power - public static boolean powerRegenOffline = false; // does player power regenerate even while they're offline? - public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline - public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less - public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) - - public static String prefixAdmin = "**"; - public static String prefixMod = "*"; - - public static int factionTagLengthMin = 3; - public static int factionTagLengthMax = 10; - public static boolean factionTagForceUpperCase = false; - - public static boolean newFactionsDefaultOpen = false; +import java.util.*; - // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit - public static int factionMemberLimit = 0; +public class Conf { + public static List baseCommandAliases = new ArrayList(); + public static boolean allowNoSlashCommand = true; - // what faction ID to start new players in when they first join the server; default is 0, "no faction" - public static String newPlayerStartingFactionID = "0"; + // Colors + public static ChatColor colorMember = ChatColor.GREEN; + public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; + public static ChatColor colorNeutral = ChatColor.WHITE; + public static ChatColor colorEnemy = ChatColor.RED; - public static boolean showMapFactionKey = true; - public static boolean showNeutralFactionsOnMap = true; - public static boolean showEnemyFactionsOnMap = true; - - // Disallow joining/leaving/kicking while power is negative - public static boolean canLeaveWithNegativePower = true; - - // Configuration for faction-only chat - public static boolean factionOnlyChat = true; - // Configuration on the Faction tag in chat messages. - public static boolean chatTagEnabled = true; - public static transient boolean chatTagHandledByAnotherPlugin = false; - public static boolean chatTagRelationColored = true; - public static String chatTagReplaceString = "[FACTION]"; - public static String chatTagInsertAfterString = ""; - public static String chatTagInsertBeforeString = ""; - public static int chatTagInsertIndex = 1; - public static boolean chatTagPadBefore = false; - public static boolean chatTagPadAfter = true; - public static String chatTagFormat = "%s"+ChatColor.WHITE; - public static String factionChatFormat = "%s:"+ChatColor.WHITE+" %s"; - public static String allianceChatFormat = ChatColor.LIGHT_PURPLE+"%s:"+ChatColor.WHITE+" %s"; + public static ChatColor colorPeaceful = ChatColor.GOLD; + public static ChatColor colorWar = ChatColor.DARK_RED; + //public static ChatColor colorWilderness = ChatColor.DARK_GREEN; - public static boolean broadcastDescriptionChanges = false; + // Power + public static double powerPlayerMax = 10.0; + public static double powerPlayerMin = -10.0; + public static double powerPlayerStarting = 0.0; + public static double powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one power + public static double powerPerDeath = 4.0; // A death makes you lose 4 power + public static boolean powerRegenOffline = false; // does player power regenerate even while they're offline? + public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline + public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less + public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) - public static double saveToFileEveryXMinutes = 30.0; + public static String prefixAdmin = "**"; + public static String prefixMod = "*"; - public static double autoLeaveAfterDaysOfInactivity = 10.0; - public static double autoLeaveRoutineRunsEveryXMinutes = 5.0; - public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick - public static boolean removePlayerDataWhenBanned = true; + public static int factionTagLengthMin = 3; + public static int factionTagLengthMax = 10; + public static boolean factionTagForceUpperCase = false; - public static boolean worldGuardChecking = false; - public static boolean worldGuardBuildPriority = false; - - //LWC - public static boolean lwcIntegration = false; - public static boolean onUnclaimResetLwcLocks = false; - public static boolean onCaptureResetLwcLocks = false; + public static boolean newFactionsDefaultOpen = false; - // server logging options - public static boolean logFactionCreate = true; - public static boolean logFactionDisband = true; - public static boolean logFactionJoin = true; - public static boolean logFactionKick = true; - public static boolean logFactionLeave = true; - public static boolean logLandClaims = true; - public static boolean logLandUnclaims = true; - public static boolean logMoneyTransactions = true; - public static boolean logPlayerCommands = true; + // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit + public static int factionMemberLimit = 0; - // prevent some potential exploits - public static boolean handleExploitObsidianGenerators = true; - public static boolean handleExploitEnderPearlClipping = true; - public static boolean handleExploitInteractionSpam = true; - public static boolean handleExploitTNTWaterlog = false; + // what faction ID to start new players in when they first join the server; default is 0, "no faction" + public static String newPlayerStartingFactionID = "0"; - public static boolean homesEnabled = true; - public static boolean homesMustBeInClaimedTerritory = true; - public static boolean homesTeleportToOnDeath = true; - public static boolean homesRespawnFromNoPowerLossWorlds = true; - public static boolean homesTeleportCommandEnabled = true; - public static boolean homesTeleportCommandEssentialsIntegration = true; - public static boolean homesTeleportCommandSmokeEffectEnabled = true; - public static float homesTeleportCommandSmokeEffectThickness = 3f; - public static boolean homesTeleportAllowedFromEnemyTerritory = true; - public static boolean homesTeleportAllowedFromDifferentWorld = true; - public static double homesTeleportAllowedEnemyDistance = 32.0; - public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; - - public static boolean disablePVPBetweenNeutralFactions = false; - public static boolean disablePVPForFactionlessPlayers = false; - public static boolean enablePVPAgainstFactionlessInAttackersLand = false; - - public static int noPVPDamageToOthersForXSecondsAfterLogin = 3; + public static boolean showMapFactionKey = true; + public static boolean showNeutralFactionsOnMap = true; + public static boolean showEnemyFactionsOnMap = true; - public static boolean peacefulTerritoryDisablePVP = true; - public static boolean peacefulTerritoryDisableMonsters = false; - public static boolean peacefulMembersDisablePowerLoss = true; - - public static boolean permanentFactionsDisableLeaderPromotion = false; - - public static boolean claimsMustBeConnected = false; - public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; - public static int claimsRequireMinFactionMembers = 1; - public static int claimedLandsMax = 0; + // Disallow joining/leaving/kicking while power is negative + public static boolean canLeaveWithNegativePower = true; - // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit - public static int radiusClaimFailureLimit = 9; + // Configuration for faction-only chat + public static boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + public static boolean chatTagEnabled = true; + public static transient boolean chatTagHandledByAnotherPlugin = false; + public static boolean chatTagRelationColored = true; + public static String chatTagReplaceString = "[FACTION]"; + public static String chatTagInsertAfterString = ""; + public static String chatTagInsertBeforeString = ""; + public static int chatTagInsertIndex = 1; + public static boolean chatTagPadBefore = false; + public static boolean chatTagPadAfter = true; + public static String chatTagFormat = "%s" + ChatColor.WHITE; + public static String factionChatFormat = "%s:" + ChatColor.WHITE + " %s"; + public static String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s"; - public static double considerFactionsReallyOfflineAfterXMinutes = 0.0; - - public static int actionDeniedPainAmount = 1; + public static boolean broadcastDescriptionChanges = false; - // commands which will be prevented if the player is a member of a permanent faction - public static Set permanentFactionMemberDenyCommands = new LinkedHashSet(); + public static double saveToFileEveryXMinutes = 30.0; - // commands which will be prevented when in claimed territory of another faction - public static Set territoryNeutralDenyCommands = new LinkedHashSet(); - public static Set territoryEnemyDenyCommands = new LinkedHashSet(); - - public static double territoryShieldFactor = 0.3; - public static boolean territoryDenyBuild = true; - public static boolean territoryDenyBuildWhenOffline = true; - public static boolean territoryPainBuild = false; - public static boolean territoryPainBuildWhenOffline = false; - public static boolean territoryDenyUseage = true; - public static boolean territoryEnemyDenyBuild = true; - public static boolean territoryEnemyDenyBuildWhenOffline = true; - public static boolean territoryEnemyPainBuild = false; - public static boolean territoryEnemyPainBuildWhenOffline = false; - public static boolean territoryEnemyDenyUseage = true; - public static boolean territoryEnemyProtectMaterials = true; - public static boolean territoryAllyDenyBuild = true; - public static boolean territoryAllyDenyBuildWhenOffline = true; - public static boolean territoryAllyPainBuild = false; - public static boolean territoryAllyPainBuildWhenOffline = false; - public static boolean territoryAllyDenyUseage = true; - public static boolean territoryAllyProtectMaterials = true; - public static boolean territoryBlockCreepers = false; - public static boolean territoryBlockCreepersWhenOffline = false; - public static boolean territoryBlockFireballs = false; - public static boolean territoryBlockFireballsWhenOffline = false; - public static boolean territoryBlockTNT = false; - public static boolean territoryBlockTNTWhenOffline = false; - public static boolean territoryDenyEndermanBlocks = true; - public static boolean territoryDenyEndermanBlocksWhenOffline = true; + public static double autoLeaveAfterDaysOfInactivity = 10.0; + public static double autoLeaveRoutineRunsEveryXMinutes = 5.0; + public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + public static boolean removePlayerDataWhenBanned = true; - public static boolean safeZoneDenyBuild = true; - public static boolean safeZoneDenyUseage = true; - public static boolean safeZoneBlockTNT = true; - public static boolean safeZonePreventAllDamageToPlayers = false; - public static boolean safeZoneDenyEndermanBlocks = true; - - public static boolean warZoneDenyBuild = true; - public static boolean warZoneDenyUseage = true; - public static boolean warZoneBlockCreepers = false; - public static boolean warZoneBlockFireballs = false; - public static boolean warZoneBlockTNT = true; - public static boolean warZonePowerLoss = true; - public static boolean warZoneFriendlyFire = false; - public static boolean warZoneDenyEndermanBlocks = true; - - public static boolean wildernessDenyBuild = false; - public static boolean wildernessDenyUseage = false; - public static boolean wildernessBlockCreepers = false; - public static boolean wildernessBlockFireballs = false; - public static boolean wildernessBlockTNT = false; - public static boolean wildernessPowerLoss = true; - public static boolean wildernessDenyEndermanBlocks = false; + public static boolean worldGuardChecking = false; + public static boolean worldGuardBuildPriority = false; - // for claimed areas where further faction-member ownership can be defined - public static boolean ownedAreasEnabled = true; - public static int ownedAreasLimitPerFaction = 0; - public static boolean ownedAreasModeratorsCanSet = false; - public static boolean ownedAreaModeratorsBypass = true; - public static boolean ownedAreaDenyBuild = true; - public static boolean ownedAreaPainBuild = false; - public static boolean ownedAreaProtectMaterials = true; - public static boolean ownedAreaDenyUseage = true; + //LWC + public static boolean lwcIntegration = false; + public static boolean onUnclaimResetLwcLocks = false; + public static boolean onCaptureResetLwcLocks = false; - public static String ownedLandMessage = "Owner(s): "; - public static String publicLandMessage = "Public faction land."; - public static boolean ownedMessageOnBorder = true; - public static boolean ownedMessageInsideTerritory = true; - public static boolean ownedMessageByChunk = false; + // server logging options + public static boolean logFactionCreate = true; + public static boolean logFactionDisband = true; + public static boolean logFactionJoin = true; + public static boolean logFactionKick = true; + public static boolean logFactionLeave = true; + public static boolean logLandClaims = true; + public static boolean logLandUnclaims = true; + public static boolean logMoneyTransactions = true; + public static boolean logPlayerCommands = true; - public static boolean pistonProtectionThroughDenyBuild = true; + // prevent some potential exploits + public static boolean handleExploitObsidianGenerators = true; + public static boolean handleExploitEnderPearlClipping = true; + public static boolean handleExploitInteractionSpam = true; + public static boolean handleExploitTNTWaterlog = false; - public static Set territoryProtectedMaterials = EnumSet.noneOf(Material.class); - public static Set territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); - public static Set territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); - public static Set territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); - - public static transient Set safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class); + public static boolean homesEnabled = true; + public static boolean homesMustBeInClaimedTerritory = true; + public static boolean homesTeleportToOnDeath = true; + public static boolean homesRespawnFromNoPowerLossWorlds = true; + public static boolean homesTeleportCommandEnabled = true; + public static boolean homesTeleportCommandEssentialsIntegration = true; + public static boolean homesTeleportCommandSmokeEffectEnabled = true; + public static float homesTeleportCommandSmokeEffectThickness = 3f; + public static boolean homesTeleportAllowedFromEnemyTerritory = true; + public static boolean homesTeleportAllowedFromDifferentWorld = true; + public static double homesTeleportAllowedEnemyDistance = 32.0; + public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; - // Spout features - public static boolean spoutFactionTagsOverNames = true; // show faction tags over names over player heads - public static boolean spoutFactionTitlesOverNames = true; // whether to include player's title in that - public static boolean spoutFactionAdminCapes = true; // Show capes on faction admins, colored based on the viewer's relation to the target player - public static boolean spoutFactionModeratorCapes = true; // same, but for faction moderators - public static int spoutTerritoryDisplayPosition = 1; // permanent territory display, instead of by chat; 0 = disabled, 1 = top left, 2 = top center, 3+ = top right - public static float spoutTerritoryDisplaySize = 1.0f; // text scale (size) for territory display - public static boolean spoutTerritoryDisplayShowDescription = true; // whether to show the faction description, not just the faction tag - public static boolean spoutTerritoryOwnersShow = true; // show territory owner list as well - public static boolean spoutTerritoryNoticeShow = true; // show additional brief territory notice near center of screen, to be sure player notices transition - public static int spoutTerritoryNoticeTop = 40; // how far down the screen to place the additional notice - public static boolean spoutTerritoryNoticeShowDescription = false; // whether to show the faction description in the notice, not just the faction tag - public static float spoutTerritoryNoticeSize = 1.5f; // text scale (size) for notice - public static float spoutTerritoryNoticeLeaveAfterSeconds = 2.00f; // how many seconds before the notice goes away - public static String capeAlly = "https://github.com/MassiveCraft/Factions/raw/master/capes/ally.png"; - public static String capeEnemy = "https://github.com/MassiveCraft/Factions/raw/master/capes/enemy.png"; - public static String capeMember = "https://github.com/MassiveCraft/Factions/raw/master/capes/member.png"; - public static String capeNeutral = "https://github.com/MassiveCraft/Factions/raw/master/capes/neutral.png"; - public static String capePeaceful = "https://github.com/MassiveCraft/Factions/raw/master/capes/peaceful.png"; - - // Economy settings - public static boolean econEnabled = false; - public static String econUniverseAccount = ""; - public static double econCostClaimWilderness = 30.0; - public static double econCostClaimFromFactionBonus = 30.0; - public static double econClaimAdditionalMultiplier = 0.5; - public static double econClaimRefundMultiplier = 0.7; - public static double econClaimUnconnectedFee = 0.0; - public static double econCostCreate = 100.0; - public static double econCostOwner = 15.0; - public static double econCostSethome = 30.0; - public static double econCostJoin = 0.0; - public static double econCostLeave = 0.0; - public static double econCostKick = 0.0; - public static double econCostInvite = 0.0; - public static double econCostHome = 0.0; - public static double econCostTag = 0.0; - public static double econCostDesc = 0.0; - public static double econCostTitle = 0.0; - public static double econCostList = 0.0; - public static double econCostMap = 0.0; - public static double econCostPower = 0.0; - public static double econCostShow = 0.0; - public static double econCostOpen = 0.0; - public static double econCostAlly = 0.0; - public static double econCostEnemy = 0.0; - public static double econCostNeutral = 0.0; - public static double econCostNoBoom = 0.0; - - //Faction banks, to pay for land claiming and other costs instead of individuals paying for them - public static boolean bankEnabled = true; - public static boolean bankMembersCanWithdraw = false; //Have to be at least moderator to withdraw or pay money to another faction - public static boolean bankFactionPaysCosts = true; //The faction pays for faction command costs, such as sethome - public static boolean bankFactionPaysLandCosts = true; //The faction pays for land claiming costs. + public static boolean disablePVPBetweenNeutralFactions = false; + public static boolean disablePVPForFactionlessPlayers = false; + public static boolean enablePVPAgainstFactionlessInAttackersLand = false; - // mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections - public static Set playersWhoBypassAllProtection = new LinkedHashSet(); + public static int noPVPDamageToOthersForXSecondsAfterLogin = 3; - public static Set worldsNoClaiming = new LinkedHashSet(); - public static Set worldsNoPowerLoss = new LinkedHashSet(); - public static Set worldsIgnorePvP = new LinkedHashSet(); - public static Set worldsNoWildernessProtection = new LinkedHashSet(); - - public static transient int mapHeight = 8; - public static transient int mapWidth = 39; - public static transient char[] mapKeyChrs = "\\/#?$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz".toCharArray(); - - static - { - baseCommandAliases.add("f"); - - territoryEnemyDenyCommands.add("home"); - territoryEnemyDenyCommands.add("sethome"); - territoryEnemyDenyCommands.add("spawn"); - territoryEnemyDenyCommands.add("tpahere"); - territoryEnemyDenyCommands.add("tpaccept"); - territoryEnemyDenyCommands.add("tpa"); + public static boolean peacefulTerritoryDisablePVP = true; + public static boolean peacefulTerritoryDisableMonsters = false; + public static boolean peacefulMembersDisablePowerLoss = true; - territoryProtectedMaterials.add(Material.WOODEN_DOOR); - territoryProtectedMaterials.add(Material.TRAP_DOOR); - territoryProtectedMaterials.add(Material.FENCE_GATE); - territoryProtectedMaterials.add(Material.DISPENSER); - territoryProtectedMaterials.add(Material.CHEST); - territoryProtectedMaterials.add(Material.FURNACE); - territoryProtectedMaterials.add(Material.BURNING_FURNACE); - territoryProtectedMaterials.add(Material.DIODE_BLOCK_OFF); - territoryProtectedMaterials.add(Material.DIODE_BLOCK_ON); - territoryProtectedMaterials.add(Material.JUKEBOX); - territoryProtectedMaterials.add(Material.BREWING_STAND); - territoryProtectedMaterials.add(Material.ENCHANTMENT_TABLE); - territoryProtectedMaterials.add(Material.CAULDRON); - territoryProtectedMaterials.add(Material.SOIL); - territoryProtectedMaterials.add(Material.BEACON); - territoryProtectedMaterials.add(Material.ANVIL); - territoryProtectedMaterials.add(Material.TRAPPED_CHEST); - territoryProtectedMaterials.add(Material.DROPPER); - territoryProtectedMaterials.add(Material.HOPPER); + public static boolean permanentFactionsDisableLeaderPromotion = false; - territoryDenyUseageMaterials.add(Material.FIREBALL); - territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterials.add(Material.BUCKET); - territoryDenyUseageMaterials.add(Material.WATER_BUCKET); - territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); + public static boolean claimsMustBeConnected = false; + public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; + public static int claimsRequireMinFactionMembers = 1; + public static int claimedLandsMax = 0; - territoryProtectedMaterialsWhenOffline.add(Material.WOODEN_DOOR); - territoryProtectedMaterialsWhenOffline.add(Material.TRAP_DOOR); - territoryProtectedMaterialsWhenOffline.add(Material.FENCE_GATE); - territoryProtectedMaterialsWhenOffline.add(Material.DISPENSER); - territoryProtectedMaterialsWhenOffline.add(Material.CHEST); - territoryProtectedMaterialsWhenOffline.add(Material.FURNACE); - territoryProtectedMaterialsWhenOffline.add(Material.BURNING_FURNACE); - territoryProtectedMaterialsWhenOffline.add(Material.DIODE_BLOCK_OFF); - territoryProtectedMaterialsWhenOffline.add(Material.DIODE_BLOCK_ON); - territoryProtectedMaterialsWhenOffline.add(Material.JUKEBOX); - territoryProtectedMaterialsWhenOffline.add(Material.BREWING_STAND); - territoryProtectedMaterialsWhenOffline.add(Material.ENCHANTMENT_TABLE); - territoryProtectedMaterialsWhenOffline.add(Material.CAULDRON); - territoryProtectedMaterialsWhenOffline.add(Material.SOIL); - territoryProtectedMaterialsWhenOffline.add(Material.BEACON); - territoryProtectedMaterialsWhenOffline.add(Material.ANVIL); - territoryProtectedMaterialsWhenOffline.add(Material.TRAPPED_CHEST); - territoryProtectedMaterialsWhenOffline.add(Material.DROPPER); - territoryProtectedMaterialsWhenOffline.add(Material.HOPPER); + // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit + public static int radiusClaimFailureLimit = 9; - territoryDenyUseageMaterialsWhenOffline.add(Material.FIREBALL); - territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); + public static double considerFactionsReallyOfflineAfterXMinutes = 0.0; - safeZoneNerfedCreatureTypes.add(EntityType.BLAZE); - safeZoneNerfedCreatureTypes.add(EntityType.CAVE_SPIDER); - safeZoneNerfedCreatureTypes.add(EntityType.CREEPER); - safeZoneNerfedCreatureTypes.add(EntityType.ENDER_DRAGON); - safeZoneNerfedCreatureTypes.add(EntityType.ENDERMAN); - safeZoneNerfedCreatureTypes.add(EntityType.GHAST); - safeZoneNerfedCreatureTypes.add(EntityType.MAGMA_CUBE); - safeZoneNerfedCreatureTypes.add(EntityType.PIG_ZOMBIE); - safeZoneNerfedCreatureTypes.add(EntityType.SILVERFISH); - safeZoneNerfedCreatureTypes.add(EntityType.SKELETON); - safeZoneNerfedCreatureTypes.add(EntityType.SPIDER); - safeZoneNerfedCreatureTypes.add(EntityType.SLIME); - safeZoneNerfedCreatureTypes.add(EntityType.WITCH); - safeZoneNerfedCreatureTypes.add(EntityType.WITHER); - safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE); - } + public static int actionDeniedPainAmount = 1; - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // - private static transient Conf i = new Conf(); - public static void load() - { - P.p.persist.loadOrSaveDefault(i, Conf.class, "conf"); - } - public static void save() - { - P.p.persist.save(i); - } + // commands which will be prevented if the player is a member of a permanent faction + public static Set permanentFactionMemberDenyCommands = new LinkedHashSet(); + + // commands which will be prevented when in claimed territory of another faction + public static Set territoryNeutralDenyCommands = new LinkedHashSet(); + public static Set territoryEnemyDenyCommands = new LinkedHashSet(); + + public static double territoryShieldFactor = 0.3; + public static boolean territoryDenyBuild = true; + public static boolean territoryDenyBuildWhenOffline = true; + public static boolean territoryPainBuild = false; + public static boolean territoryPainBuildWhenOffline = false; + public static boolean territoryDenyUseage = true; + public static boolean territoryEnemyDenyBuild = true; + public static boolean territoryEnemyDenyBuildWhenOffline = true; + public static boolean territoryEnemyPainBuild = false; + public static boolean territoryEnemyPainBuildWhenOffline = false; + public static boolean territoryEnemyDenyUseage = true; + public static boolean territoryEnemyProtectMaterials = true; + public static boolean territoryAllyDenyBuild = true; + public static boolean territoryAllyDenyBuildWhenOffline = true; + public static boolean territoryAllyPainBuild = false; + public static boolean territoryAllyPainBuildWhenOffline = false; + public static boolean territoryAllyDenyUseage = true; + public static boolean territoryAllyProtectMaterials = true; + public static boolean territoryBlockCreepers = false; + public static boolean territoryBlockCreepersWhenOffline = false; + public static boolean territoryBlockFireballs = false; + public static boolean territoryBlockFireballsWhenOffline = false; + public static boolean territoryBlockTNT = false; + public static boolean territoryBlockTNTWhenOffline = false; + public static boolean territoryDenyEndermanBlocks = true; + public static boolean territoryDenyEndermanBlocksWhenOffline = true; + + public static boolean safeZoneDenyBuild = true; + public static boolean safeZoneDenyUseage = true; + public static boolean safeZoneBlockTNT = true; + public static boolean safeZonePreventAllDamageToPlayers = false; + public static boolean safeZoneDenyEndermanBlocks = true; + + public static boolean warZoneDenyBuild = true; + public static boolean warZoneDenyUseage = true; + public static boolean warZoneBlockCreepers = false; + public static boolean warZoneBlockFireballs = false; + public static boolean warZoneBlockTNT = true; + public static boolean warZonePowerLoss = true; + public static boolean warZoneFriendlyFire = false; + public static boolean warZoneDenyEndermanBlocks = true; + + public static boolean wildernessDenyBuild = false; + public static boolean wildernessDenyUseage = false; + public static boolean wildernessBlockCreepers = false; + public static boolean wildernessBlockFireballs = false; + public static boolean wildernessBlockTNT = false; + public static boolean wildernessPowerLoss = true; + public static boolean wildernessDenyEndermanBlocks = false; + + // for claimed areas where further faction-member ownership can be defined + public static boolean ownedAreasEnabled = true; + public static int ownedAreasLimitPerFaction = 0; + public static boolean ownedAreasModeratorsCanSet = false; + public static boolean ownedAreaModeratorsBypass = true; + public static boolean ownedAreaDenyBuild = true; + public static boolean ownedAreaPainBuild = false; + public static boolean ownedAreaProtectMaterials = true; + public static boolean ownedAreaDenyUseage = true; + + public static String ownedLandMessage = "Owner(s): "; + public static String publicLandMessage = "Public faction land."; + public static boolean ownedMessageOnBorder = true; + public static boolean ownedMessageInsideTerritory = true; + public static boolean ownedMessageByChunk = false; + + public static boolean pistonProtectionThroughDenyBuild = true; + + public static Set territoryProtectedMaterials = EnumSet.noneOf(Material.class); + public static Set territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); + public static Set territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); + public static Set territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); + + public static transient Set safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class); + + // Spout features + public static boolean spoutFactionTagsOverNames = true; // show faction tags over names over player heads + public static boolean spoutFactionTitlesOverNames = true; // whether to include player's title in that + public static boolean spoutFactionAdminCapes = true; // Show capes on faction admins, colored based on the viewer's relation to the target player + public static boolean spoutFactionModeratorCapes = true; // same, but for faction moderators + public static int spoutTerritoryDisplayPosition = 1; // permanent territory display, instead of by chat; 0 = disabled, 1 = top left, 2 = top center, 3+ = top right + public static float spoutTerritoryDisplaySize = 1.0f; // text scale (size) for territory display + public static boolean spoutTerritoryDisplayShowDescription = true; // whether to show the faction description, not just the faction tag + public static boolean spoutTerritoryOwnersShow = true; // show territory owner list as well + public static boolean spoutTerritoryNoticeShow = true; // show additional brief territory notice near center of screen, to be sure player notices transition + public static int spoutTerritoryNoticeTop = 40; // how far down the screen to place the additional notice + public static boolean spoutTerritoryNoticeShowDescription = false; // whether to show the faction description in the notice, not just the faction tag + public static float spoutTerritoryNoticeSize = 1.5f; // text scale (size) for notice + public static float spoutTerritoryNoticeLeaveAfterSeconds = 2.00f; // how many seconds before the notice goes away + public static String capeAlly = "https://github.com/MassiveCraft/Factions/raw/master/capes/ally.png"; + public static String capeEnemy = "https://github.com/MassiveCraft/Factions/raw/master/capes/enemy.png"; + public static String capeMember = "https://github.com/MassiveCraft/Factions/raw/master/capes/member.png"; + public static String capeNeutral = "https://github.com/MassiveCraft/Factions/raw/master/capes/neutral.png"; + public static String capePeaceful = "https://github.com/MassiveCraft/Factions/raw/master/capes/peaceful.png"; + + // Economy settings + public static boolean econEnabled = false; + public static String econUniverseAccount = ""; + public static double econCostClaimWilderness = 30.0; + public static double econCostClaimFromFactionBonus = 30.0; + public static double econClaimAdditionalMultiplier = 0.5; + public static double econClaimRefundMultiplier = 0.7; + public static double econClaimUnconnectedFee = 0.0; + public static double econCostCreate = 100.0; + public static double econCostOwner = 15.0; + public static double econCostSethome = 30.0; + public static double econCostJoin = 0.0; + public static double econCostLeave = 0.0; + public static double econCostKick = 0.0; + public static double econCostInvite = 0.0; + public static double econCostHome = 0.0; + public static double econCostTag = 0.0; + public static double econCostDesc = 0.0; + public static double econCostTitle = 0.0; + public static double econCostList = 0.0; + public static double econCostMap = 0.0; + public static double econCostPower = 0.0; + public static double econCostShow = 0.0; + public static double econCostOpen = 0.0; + public static double econCostAlly = 0.0; + public static double econCostEnemy = 0.0; + public static double econCostNeutral = 0.0; + public static double econCostNoBoom = 0.0; + + //Faction banks, to pay for land claiming and other costs instead of individuals paying for them + public static boolean bankEnabled = true; + public static boolean bankMembersCanWithdraw = false; //Have to be at least moderator to withdraw or pay money to another faction + public static boolean bankFactionPaysCosts = true; //The faction pays for faction command costs, such as sethome + public static boolean bankFactionPaysLandCosts = true; //The faction pays for land claiming costs. + + // mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections + public static Set playersWhoBypassAllProtection = new LinkedHashSet(); + + public static Set worldsNoClaiming = new LinkedHashSet(); + public static Set worldsNoPowerLoss = new LinkedHashSet(); + public static Set worldsIgnorePvP = new LinkedHashSet(); + public static Set worldsNoWildernessProtection = new LinkedHashSet(); + + public static transient int mapHeight = 8; + public static transient int mapWidth = 39; + public static transient char[] mapKeyChrs = "\\/#?$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz".toCharArray(); + + static { + baseCommandAliases.add("f"); + + territoryEnemyDenyCommands.add("home"); + territoryEnemyDenyCommands.add("sethome"); + territoryEnemyDenyCommands.add("spawn"); + territoryEnemyDenyCommands.add("tpahere"); + territoryEnemyDenyCommands.add("tpaccept"); + territoryEnemyDenyCommands.add("tpa"); + + territoryProtectedMaterials.add(Material.WOODEN_DOOR); + territoryProtectedMaterials.add(Material.TRAP_DOOR); + territoryProtectedMaterials.add(Material.FENCE_GATE); + territoryProtectedMaterials.add(Material.DISPENSER); + territoryProtectedMaterials.add(Material.CHEST); + territoryProtectedMaterials.add(Material.FURNACE); + territoryProtectedMaterials.add(Material.BURNING_FURNACE); + territoryProtectedMaterials.add(Material.DIODE_BLOCK_OFF); + territoryProtectedMaterials.add(Material.DIODE_BLOCK_ON); + territoryProtectedMaterials.add(Material.JUKEBOX); + territoryProtectedMaterials.add(Material.BREWING_STAND); + territoryProtectedMaterials.add(Material.ENCHANTMENT_TABLE); + territoryProtectedMaterials.add(Material.CAULDRON); + territoryProtectedMaterials.add(Material.SOIL); + territoryProtectedMaterials.add(Material.BEACON); + territoryProtectedMaterials.add(Material.ANVIL); + territoryProtectedMaterials.add(Material.TRAPPED_CHEST); + territoryProtectedMaterials.add(Material.DROPPER); + territoryProtectedMaterials.add(Material.HOPPER); + + territoryDenyUseageMaterials.add(Material.FIREBALL); + territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterials.add(Material.BUCKET); + territoryDenyUseageMaterials.add(Material.WATER_BUCKET); + territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); + + territoryProtectedMaterialsWhenOffline.add(Material.WOODEN_DOOR); + territoryProtectedMaterialsWhenOffline.add(Material.TRAP_DOOR); + territoryProtectedMaterialsWhenOffline.add(Material.FENCE_GATE); + territoryProtectedMaterialsWhenOffline.add(Material.DISPENSER); + territoryProtectedMaterialsWhenOffline.add(Material.CHEST); + territoryProtectedMaterialsWhenOffline.add(Material.FURNACE); + territoryProtectedMaterialsWhenOffline.add(Material.BURNING_FURNACE); + territoryProtectedMaterialsWhenOffline.add(Material.DIODE_BLOCK_OFF); + territoryProtectedMaterialsWhenOffline.add(Material.DIODE_BLOCK_ON); + territoryProtectedMaterialsWhenOffline.add(Material.JUKEBOX); + territoryProtectedMaterialsWhenOffline.add(Material.BREWING_STAND); + territoryProtectedMaterialsWhenOffline.add(Material.ENCHANTMENT_TABLE); + territoryProtectedMaterialsWhenOffline.add(Material.CAULDRON); + territoryProtectedMaterialsWhenOffline.add(Material.SOIL); + territoryProtectedMaterialsWhenOffline.add(Material.BEACON); + territoryProtectedMaterialsWhenOffline.add(Material.ANVIL); + territoryProtectedMaterialsWhenOffline.add(Material.TRAPPED_CHEST); + territoryProtectedMaterialsWhenOffline.add(Material.DROPPER); + territoryProtectedMaterialsWhenOffline.add(Material.HOPPER); + + territoryDenyUseageMaterialsWhenOffline.add(Material.FIREBALL); + territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); + + safeZoneNerfedCreatureTypes.add(EntityType.BLAZE); + safeZoneNerfedCreatureTypes.add(EntityType.CAVE_SPIDER); + safeZoneNerfedCreatureTypes.add(EntityType.CREEPER); + safeZoneNerfedCreatureTypes.add(EntityType.ENDER_DRAGON); + safeZoneNerfedCreatureTypes.add(EntityType.ENDERMAN); + safeZoneNerfedCreatureTypes.add(EntityType.GHAST); + safeZoneNerfedCreatureTypes.add(EntityType.MAGMA_CUBE); + safeZoneNerfedCreatureTypes.add(EntityType.PIG_ZOMBIE); + safeZoneNerfedCreatureTypes.add(EntityType.SILVERFISH); + safeZoneNerfedCreatureTypes.add(EntityType.SKELETON); + safeZoneNerfedCreatureTypes.add(EntityType.SPIDER); + safeZoneNerfedCreatureTypes.add(EntityType.SLIME); + safeZoneNerfedCreatureTypes.add(EntityType.WITCH); + safeZoneNerfedCreatureTypes.add(EntityType.WITHER); + safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE); + } + + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // + private static transient Conf i = new Conf(); + + public static void load() { + P.p.persist.loadOrSaveDefault(i, Conf.class, "conf"); + } + + public static void save() { + P.p.persist.save(i); + } } diff --git a/src/main/java/com/massivecraft/factions/FLocation.java b/src/main/java/com/massivecraft/factions/FLocation.java index 66e75174..6b782e36 100644 --- a/src/main/java/com/massivecraft/factions/FLocation.java +++ b/src/main/java/com/massivecraft/factions/FLocation.java @@ -1,221 +1,189 @@ package com.massivecraft.factions; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - +import com.massivecraft.factions.util.MiscUtil; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; -import com.massivecraft.factions.util.MiscUtil; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; -public class FLocation -{ +public class FLocation { - private String worldName = "world"; - private int x = 0; - private int z = 0; - - //----------------------------------------------// - // Constructors - //----------------------------------------------// - - public FLocation() - { - - } - - public FLocation(String worldName, int x, int z) - { - this.worldName = worldName; - this.x = x; - this.z = z; - } - - public FLocation(Location location) - { - this( location.getWorld().getName(), blockToChunk(location.getBlockX()), blockToChunk(location.getBlockZ()) ); - } - - public FLocation(Player player) - { - this(player.getLocation()); - } - - public FLocation(FPlayer fplayer) - { - this(fplayer.getPlayer()); - } - - public FLocation(Block block) - { - this(block.getLocation()); - } - - //----------------------------------------------// - // Getters and Setters - //----------------------------------------------// - - public String getWorldName() - { - return worldName; - } + private String worldName = "world"; + private int x = 0; + private int z = 0; - public World getWorld() - { - return Bukkit.getWorld(worldName); - } + //----------------------------------------------// + // Constructors + //----------------------------------------------// - public void setWorldName(String worldName) - { - this.worldName = worldName; - } - - public long getX() - { - return x; - } + public FLocation() { - public void setX(int x) - { - this.x = x; - } + } - public long getZ() - { - return z; - } + public FLocation(String worldName, int x, int z) { + this.worldName = worldName; + this.x = x; + this.z = z; + } - public void setZ(int z) - { - this.z = z; - } - - public String getCoordString() - { - return ""+x+","+z; - } - - @Override - public String toString() { - return "["+this.getWorldName()+","+this.getCoordString()+"]"; - } + public FLocation(Location location) { + this(location.getWorld().getName(), blockToChunk(location.getBlockX()), blockToChunk(location.getBlockZ())); + } - //----------------------------------------------// - // Block/Chunk/Region Value Transformation - //----------------------------------------------// + public FLocation(Player player) { + this(player.getLocation()); + } - // bit-shifting is used because it's much faster than standard division and multiplication - public static int blockToChunk(int blockVal) - { // 1 chunk is 16x16 blocks - return blockVal >> 4; // ">> 4" == "/ 16" - } + public FLocation(FPlayer fplayer) { + this(fplayer.getPlayer()); + } - public static int blockToRegion(int blockVal) - { // 1 region is 512x512 blocks - return blockVal >> 9; // ">> 9" == "/ 512" - } + public FLocation(Block block) { + this(block.getLocation()); + } - public static int chunkToRegion(int chunkVal) - { // 1 region is 32x32 chunks - return chunkVal >> 5; // ">> 5" == "/ 32" - } + //----------------------------------------------// + // Getters and Setters + //----------------------------------------------// - public static int chunkToBlock(int chunkVal) - { - return chunkVal << 4; // "<< 4" == "* 16" - } + public String getWorldName() { + return worldName; + } - public static int regionToBlock(int regionVal) - { - return regionVal << 9; // "<< 9" == "* 512" - } + public World getWorld() { + return Bukkit.getWorld(worldName); + } - public static int regionToChunk(int regionVal) - { - return regionVal << 5; // "<< 5" == "* 32" - } + public void setWorldName(String worldName) { + this.worldName = worldName; + } - //----------------------------------------------// - // Misc Geometry - //----------------------------------------------// - - public FLocation getRelative(int dx, int dz) - { - return new FLocation(this.worldName, this.x + dx, this.z + dz); - } + public long getX() { + return x; + } - public double getDistanceTo(FLocation that) - { - double dx = that.x - this.x; - double dz = that.z - this.z; - return Math.sqrt(dx*dx+dz*dz); - } + public void setX(int x) { + this.x = x; + } - //----------------------------------------------// - // Some Geometry - //----------------------------------------------// - public Set getCircle(double radius) - { - Set ret = new LinkedHashSet(); - if (radius <= 0) return ret; + public long getZ() { + return z; + } - int xfrom = (int) Math.floor(this.x - radius); - int xto = (int) Math.ceil(this.x + radius); - int zfrom = (int) Math.floor(this.z - radius); - int zto = (int) Math.ceil(this.z + radius); + public void setZ(int z) { + this.z = z; + } - for (int x=xfrom; x<=xto; x++) - { - for (int z=zfrom; z<=zto; z++) - { - FLocation potential = new FLocation(this.worldName, x, z); - if (this.getDistanceTo(potential) <= radius) - ret.add(potential); - } - } + public String getCoordString() { + return "" + x + "," + z; + } - return ret; - } + @Override + public String toString() { + return "[" + this.getWorldName() + "," + this.getCoordString() + "]"; + } - public static HashSet getArea(FLocation from, FLocation to) - { - HashSet ret = new HashSet(); - - for (long x : MiscUtil.range(from.getX(), to.getX())) - { - for (long z : MiscUtil.range(from.getZ(), to.getZ())) - { - ret.add(new FLocation(from.getWorldName(), (int)x, (int)z)); - } - } - - return ret; - } - - //----------------------------------------------// - // Comparison - //----------------------------------------------// - - @Override - public int hashCode() - { - // should be fast, with good range and few hash collisions: (x * 512) + z + worldName.hashCode - return (this.x << 9) + this.z + (this.worldName != null ? this.worldName.hashCode() : 0); - } - - @Override - public boolean equals(Object obj) - { - if (obj == this) - return true; - if (!(obj instanceof FLocation)) - return false; + //----------------------------------------------// + // Block/Chunk/Region Value Transformation + //----------------------------------------------// - FLocation that = (FLocation) obj; - return this.x == that.x && this.z == that.z && ( this.worldName==null ? that.worldName==null : this.worldName.equals(that.worldName) ); - } + // bit-shifting is used because it's much faster than standard division and multiplication + public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks + return blockVal >> 4; // ">> 4" == "/ 16" + } + + public static int blockToRegion(int blockVal) { // 1 region is 512x512 blocks + return blockVal >> 9; // ">> 9" == "/ 512" + } + + public static int chunkToRegion(int chunkVal) { // 1 region is 32x32 chunks + return chunkVal >> 5; // ">> 5" == "/ 32" + } + + public static int chunkToBlock(int chunkVal) { + return chunkVal << 4; // "<< 4" == "* 16" + } + + public static int regionToBlock(int regionVal) { + return regionVal << 9; // "<< 9" == "* 512" + } + + public static int regionToChunk(int regionVal) { + return regionVal << 5; // "<< 5" == "* 32" + } + + //----------------------------------------------// + // Misc Geometry + //----------------------------------------------// + + public FLocation getRelative(int dx, int dz) { + return new FLocation(this.worldName, this.x + dx, this.z + dz); + } + + public double getDistanceTo(FLocation that) { + double dx = that.x - this.x; + double dz = that.z - this.z; + return Math.sqrt(dx * dx + dz * dz); + } + + //----------------------------------------------// + // Some Geometry + //----------------------------------------------// + public Set getCircle(double radius) { + Set ret = new LinkedHashSet(); + if (radius <= 0) return ret; + + int xfrom = (int) Math.floor(this.x - radius); + int xto = (int) Math.ceil(this.x + radius); + int zfrom = (int) Math.floor(this.z - radius); + int zto = (int) Math.ceil(this.z + radius); + + for (int x = xfrom; x <= xto; x++) { + for (int z = zfrom; z <= zto; z++) { + FLocation potential = new FLocation(this.worldName, x, z); + if (this.getDistanceTo(potential) <= radius) + ret.add(potential); + } + } + + return ret; + } + + public static HashSet getArea(FLocation from, FLocation to) { + HashSet ret = new HashSet(); + + for (long x : MiscUtil.range(from.getX(), to.getX())) { + for (long z : MiscUtil.range(from.getZ(), to.getZ())) { + ret.add(new FLocation(from.getWorldName(), (int) x, (int) z)); + } + } + + return ret; + } + + //----------------------------------------------// + // Comparison + //----------------------------------------------// + + @Override + public int hashCode() { + // should be fast, with good range and few hash collisions: (x * 512) + z + worldName.hashCode + return (this.x << 9) + this.z + (this.worldName != null ? this.worldName.hashCode() : 0); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) + return true; + if (!(obj instanceof FLocation)) + return false; + + FLocation that = (FLocation) obj; + return this.x == that.x && this.z == that.z && (this.worldName == null ? that.worldName == null : this.worldName.equals(that.worldName)); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/FPlayer.java b/src/main/java/com/massivecraft/factions/FPlayer.java index 9c229568..087c680c 100644 --- a/src/main/java/com/massivecraft/factions/FPlayer.java +++ b/src/main/java/com/massivecraft/factions/FPlayer.java @@ -1,13 +1,5 @@ package com.massivecraft.factions; -import java.util.HashSet; -import java.util.Set; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.Player; - import com.massivecraft.factions.event.FPlayerLeaveEvent; import com.massivecraft.factions.event.LandClaimEvent; import com.massivecraft.factions.iface.EconomyParticipator; @@ -22,320 +14,340 @@ import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.util.RelationUtil; import com.massivecraft.factions.zcore.persist.PlayerEntity; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.HashSet; +import java.util.Set; /** - * Logged in players always have exactly one FPlayer instance. - * Logged out players may or may not have an FPlayer instance. They will always have one if they are part of a faction. - * This is because only players with a faction are saved to disk (in order to not waste disk space). - * + * Logged in players always have exactly one FPlayer instance. Logged out players may or may not have an FPlayer + * instance. They will always have one if they are part of a faction. This is because only players with a faction are + * saved to disk (in order to not waste disk space). + *

* The FPlayer is linked to a minecraft player using the player name. - * - * The same instance is always returned for the same player. - * This means you can use the == operator. No .equals method necessary. + *

+ * The same instance is always returned for the same player. This means you can use the == operator. No .equals method + * necessary. */ -public class FPlayer extends PlayerEntity implements EconomyParticipator -{ - //private transient String playerName; - private transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? - - // FIELD: factionId - private String factionId; - public Faction getFaction() { if(this.factionId == null) {return null;} return Factions.i.get(this.factionId); } - public String getFactionId() { return this.factionId; } - public boolean hasFaction() { return ! factionId.equals("0"); } - public void setFaction(Faction faction) - { - Faction oldFaction = this.getFaction(); - if (oldFaction != null) oldFaction.removeFPlayer(this); - faction.addFPlayer(this); - this.factionId = faction.getId(); - SpoutFeatures.updateAppearances(this.getPlayer()); - } - - // FIELD: role - private Role role; - public Role getRole() { return this.role; } - public void setRole(Role role) { this.role = role; SpoutFeatures.updateAppearances(this.getPlayer()); } - - // FIELD: title - private String title; - - // FIELD: power - private double power; +public class FPlayer extends PlayerEntity implements EconomyParticipator { + //private transient String playerName; + private transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? - // FIELD: powerBoost - // special increase/decrease to min and max power for this player - private double powerBoost; - public double getPowerBoost() { return this.powerBoost; } - public void setPowerBoost(double powerBoost) { this.powerBoost = powerBoost; } + // FIELD: factionId + private String factionId; - // FIELD: lastPowerUpdateTime - private long lastPowerUpdateTime; - - // FIELD: lastLoginTime - private long lastLoginTime; - - // FIELD: mapAutoUpdating - private transient boolean mapAutoUpdating; - - // FIELD: autoClaimEnabled - private transient Faction autoClaimFor; - public Faction getAutoClaimFor() - { - return autoClaimFor; - } - public void setAutoClaimFor(Faction faction) - { - this.autoClaimFor = faction; - if (this.autoClaimFor != null) - { - // TODO: merge these into same autoclaim - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - } - } - - // FIELD: autoSafeZoneEnabled - private transient boolean autoSafeZoneEnabled; - public boolean isAutoSafeClaimEnabled() { return autoSafeZoneEnabled; } - public void setIsAutoSafeClaimEnabled(boolean enabled) - { - this.autoSafeZoneEnabled = enabled; - if (enabled) - { - this.autoClaimFor = null; - this.autoWarZoneEnabled = false; - } - } + public Faction getFaction() { + if (this.factionId == null) { + return null; + } + return Factions.i.get(this.factionId); + } - // FIELD: autoWarZoneEnabled - private transient boolean autoWarZoneEnabled; - public boolean isAutoWarClaimEnabled() { return autoWarZoneEnabled; } - public void setIsAutoWarClaimEnabled(boolean enabled) - { - this.autoWarZoneEnabled = enabled; - if (enabled) - { - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; - } - } - - private transient boolean isAdminBypassing = false; - public boolean isAdminBypassing() { return this.isAdminBypassing; } - public void setIsAdminBypassing(boolean val) { this.isAdminBypassing = val; } - - // FIELD: loginPvpDisabled - private transient boolean loginPvpDisabled; - - // FIELD: deleteMe - private transient boolean deleteMe; - - // FIELD: chatMode - private ChatMode chatMode; - public void setChatMode(ChatMode chatMode) { this.chatMode = chatMode; } - public ChatMode getChatMode() - { - if(this.factionId.equals("0") || ! Conf.factionOnlyChat) - { - this.chatMode = ChatMode.PUBLIC; - } - return chatMode; - } + public String getFactionId() { + return this.factionId; + } - // FIELD: chatSpy - private transient boolean spyingChat = false; - public void setSpyingChat(boolean chatSpying) { this.spyingChat = chatSpying; } - public boolean isSpyingChat() { return spyingChat; } + public boolean hasFaction() { + return !factionId.equals("0"); + } - // FIELD: account - public String getAccountId() { return this.getId(); } - - // -------------------------------------------- // - // Construct - // -------------------------------------------- // - - // GSON need this noarg constructor. - public FPlayer() - { - this.resetFactionData(false); - this.power = Conf.powerPlayerStarting; - this.lastPowerUpdateTime = System.currentTimeMillis(); - this.lastLoginTime = System.currentTimeMillis(); - this.mapAutoUpdating = false; - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - this.loginPvpDisabled = (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) ? true : false; - this.deleteMe = false; - this.powerBoost = 0.0; + public void setFaction(Faction faction) { + Faction oldFaction = this.getFaction(); + if (oldFaction != null) oldFaction.removeFPlayer(this); + faction.addFPlayer(this); + this.factionId = faction.getId(); + SpoutFeatures.updateAppearances(this.getPlayer()); + } - if ( ! Conf.newPlayerStartingFactionID.equals("0") && Factions.i.exists(Conf.newPlayerStartingFactionID)) - { - this.factionId = Conf.newPlayerStartingFactionID; - } - } - - public final void resetFactionData(boolean doSpoutUpdate) - { - // clean up any territory ownership in old faction, if there is one - if (Factions.i.exists(this.getFactionId())) - { - Faction currentFaction = this.getFaction(); - currentFaction.removeFPlayer(this); - if (currentFaction.isNormal()) - { - currentFaction.clearClaimOwnership(this.getId()); - } - } - - this.factionId = "0"; // The default neutral faction - this.chatMode = ChatMode.PUBLIC; - this.role = Role.NORMAL; - this.title = ""; - this.autoClaimFor = null; + // FIELD: role + private Role role; - if (doSpoutUpdate) - { - SpoutFeatures.updateAppearances(this.getPlayer()); - } - } - - public void resetFactionData() - { - this.resetFactionData(true); - } - - // -------------------------------------------- // - // Getters And Setters - // -------------------------------------------- // - - - - - public long getLastLoginTime() - { - return lastLoginTime; - } + public Role getRole() { + return this.role; + } - + public void setRole(Role role) { + this.role = role; + SpoutFeatures.updateAppearances(this.getPlayer()); + } - public void setLastLoginTime(long lastLoginTime) - { - losePowerFromBeingOffline(); - this.lastLoginTime = lastLoginTime; - this.lastPowerUpdateTime = lastLoginTime; - if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) - { - this.loginPvpDisabled = true; - } - } + // FIELD: title + private String title; - public boolean isMapAutoUpdating() - { - return mapAutoUpdating; - } + // FIELD: power + private double power; - public void setMapAutoUpdating(boolean mapAutoUpdating) - { - this.mapAutoUpdating = mapAutoUpdating; - } + // FIELD: powerBoost + // special increase/decrease to min and max power for this player + private double powerBoost; - public boolean hasLoginPvpDisabled() - { - if (!loginPvpDisabled) - { - return false; - } - if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) - { - this.loginPvpDisabled = false; - return false; - } - return true; - } - - public FLocation getLastStoodAt() - { - return this.lastStoodAt; - } - - public void setLastStoodAt(FLocation flocation) - { - this.lastStoodAt = flocation; - } + public double getPowerBoost() { + return this.powerBoost; + } - public void markForDeletion(boolean delete) - { - deleteMe = delete; - } - - //----------------------------------------------// - // Title, Name, Faction Tag and Chat - //----------------------------------------------// - - // Base: - - public String getTitle() - { - return this.title; - } + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + // FIELD: lastPowerUpdateTime + private long lastPowerUpdateTime; + + // FIELD: lastLoginTime + private long lastLoginTime; + + // FIELD: mapAutoUpdating + private transient boolean mapAutoUpdating; + + // FIELD: autoClaimEnabled + private transient Faction autoClaimFor; + + public Faction getAutoClaimFor() { + return autoClaimFor; + } + + public void setAutoClaimFor(Faction faction) { + this.autoClaimFor = faction; + if (this.autoClaimFor != null) { + // TODO: merge these into same autoclaim + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + } + } + + // FIELD: autoSafeZoneEnabled + private transient boolean autoSafeZoneEnabled; + + public boolean isAutoSafeClaimEnabled() { + return autoSafeZoneEnabled; + } + + public void setIsAutoSafeClaimEnabled(boolean enabled) { + this.autoSafeZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoWarZoneEnabled = false; + } + } + + // FIELD: autoWarZoneEnabled + private transient boolean autoWarZoneEnabled; + + public boolean isAutoWarClaimEnabled() { + return autoWarZoneEnabled; + } + + public void setIsAutoWarClaimEnabled(boolean enabled) { + this.autoWarZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + } + } + + private transient boolean isAdminBypassing = false; + + public boolean isAdminBypassing() { + return this.isAdminBypassing; + } + + public void setIsAdminBypassing(boolean val) { + this.isAdminBypassing = val; + } + + // FIELD: loginPvpDisabled + private transient boolean loginPvpDisabled; + + // FIELD: deleteMe + private transient boolean deleteMe; + + // FIELD: chatMode + private ChatMode chatMode; + + public void setChatMode(ChatMode chatMode) { + this.chatMode = chatMode; + } + + public ChatMode getChatMode() { + if (this.factionId.equals("0") || !Conf.factionOnlyChat) { + this.chatMode = ChatMode.PUBLIC; + } + return chatMode; + } + + // FIELD: chatSpy + private transient boolean spyingChat = false; + + public void setSpyingChat(boolean chatSpying) { + this.spyingChat = chatSpying; + } + + public boolean isSpyingChat() { + return spyingChat; + } + + // FIELD: account + public String getAccountId() { + return this.getId(); + } + + // -------------------------------------------- // + // Construct + // -------------------------------------------- // + + // GSON need this noarg constructor. + public FPlayer() { + this.resetFactionData(false); + this.power = Conf.powerPlayerStarting; + this.lastPowerUpdateTime = System.currentTimeMillis(); + this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + this.loginPvpDisabled = (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) ? true : false; + this.deleteMe = false; + this.powerBoost = 0.0; + + if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.i.exists(Conf.newPlayerStartingFactionID)) { + this.factionId = Conf.newPlayerStartingFactionID; + } + } + + public final void resetFactionData(boolean doSpoutUpdate) { + // clean up any territory ownership in old faction, if there is one + if (Factions.i.exists(this.getFactionId())) { + Faction currentFaction = this.getFaction(); + currentFaction.removeFPlayer(this); + if (currentFaction.isNormal()) { + currentFaction.clearClaimOwnership(this.getId()); + } + } + + this.factionId = "0"; // The default neutral faction + this.chatMode = ChatMode.PUBLIC; + this.role = Role.NORMAL; + this.title = ""; + this.autoClaimFor = null; + + if (doSpoutUpdate) { + SpoutFeatures.updateAppearances(this.getPlayer()); + } + } + + public void resetFactionData() { + this.resetFactionData(true); + } + + // -------------------------------------------- // + // Getters And Setters + // -------------------------------------------- // + + + public long getLastLoginTime() { + return lastLoginTime; + } + + + public void setLastLoginTime(long lastLoginTime) { + losePowerFromBeingOffline(); + this.lastLoginTime = lastLoginTime; + this.lastPowerUpdateTime = lastLoginTime; + if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { + this.loginPvpDisabled = true; + } + } + + public boolean isMapAutoUpdating() { + return mapAutoUpdating; + } + + public void setMapAutoUpdating(boolean mapAutoUpdating) { + this.mapAutoUpdating = mapAutoUpdating; + } + + public boolean hasLoginPvpDisabled() { + if (!loginPvpDisabled) { + return false; + } + if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { + this.loginPvpDisabled = false; + return false; + } + return true; + } + + public FLocation getLastStoodAt() { + return this.lastStoodAt; + } + + public void setLastStoodAt(FLocation flocation) { + this.lastStoodAt = flocation; + } + + public void markForDeletion(boolean delete) { + deleteMe = delete; + } + + //----------------------------------------------// + // Title, Name, Faction Tag and Chat + //----------------------------------------------// + + // Base: + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getName() { + return this.getId(); // TODO: ... display name or remove completeley + } + + public String getTag() { + if (!this.hasFaction()) { + return ""; + } + return this.getFaction().getTag(); + } + + // Base concatenations: + + public String getNameAndSomething(String something) { + String ret = this.role.getPrefix(); + if (something.length() > 0) { + ret += something + " "; + } + ret += this.getName(); + return ret; + } + + public String getNameAndTitle() { + return this.getNameAndSomething(this.getTitle()); + } + + public String getNameAndTag() { + return this.getNameAndSomething(this.getTag()); + } + + // Colored concatenations: + // These are used in information messages + + public String getNameAndTitle(Faction faction) { + return this.getColorTo(faction) + this.getNameAndTitle(); + } + + public String getNameAndTitle(FPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } - public void setTitle(String title) - { - this.title = title; - } - - public String getName() - { - return this.getId(); // TODO: ... display name or remove completeley - } - - public String getTag() - { - if ( ! this.hasFaction()) - { - return ""; - } - return this.getFaction().getTag(); - } - - // Base concatenations: - - public String getNameAndSomething(String something) - { - String ret = this.role.getPrefix(); - if (something.length() > 0) { - ret += something+" "; - } - ret += this.getName(); - return ret; - } - - public String getNameAndTitle() - { - return this.getNameAndSomething(this.getTitle()); - } - - public String getNameAndTag() - { - return this.getNameAndSomething(this.getTag()); - } - - // Colored concatenations: - // These are used in information messages - - public String getNameAndTitle(Faction faction) - { - return this.getColorTo(faction)+this.getNameAndTitle(); - } - public String getNameAndTitle(FPlayer fplayer) - { - return this.getColorTo(fplayer)+this.getNameAndTitle(); - } - /*public String getNameAndTag(Faction faction) { return this.getRelationColor(faction)+this.getNameAndTag(); @@ -344,8 +356,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { return this.getRelationColor(fplayer)+this.getNameAndTag(); }*/ - - // TODO: REmovded for refactoring. + + // TODO: REmovded for refactoring. /*public String getNameAndRelevant(Faction faction) { @@ -364,499 +376,410 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { return getNameAndRelevant(fplayer.getFaction()); }*/ - - // Chat Tag: - // These are injected into the format of global chat messages. - - public String getChatTag() - { - if ( ! this.hasFaction()) { - return ""; - } - - return String.format(Conf.chatTagFormat, this.role.getPrefix()+this.getTag()); - } - - // Colored Chat Tag - public String getChatTag(Faction faction) - { - if ( ! this.hasFaction()) { - return ""; - } - - return this.getRelationTo(faction).getColor()+getChatTag(); - } - - public String getChatTag(FPlayer fplayer) - { - if ( ! this.hasFaction()) - { - return ""; - } - - return this.getColorTo(fplayer)+getChatTag(); - } - - // ------------------------------- - // Relation and relation colors - // ------------------------------- - - @Override - public String describeTo(RelationParticipator that, boolean ucfirst) - { - return RelationUtil.describeThatToMe(this, that, ucfirst); - } - - @Override - public String describeTo(RelationParticipator that) - { - return RelationUtil.describeThatToMe(this, that); - } - - @Override - public Relation getRelationTo(RelationParticipator rp) - { - return RelationUtil.getRelationTo(this, rp); - } - - @Override - public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) - { - return RelationUtil.getRelationTo(this, rp, ignorePeaceful); - } - - public Relation getRelationToLocation() - { - return Board.getFactionAt(new FLocation(this)).getRelationTo(this); - } - - @Override - public ChatColor getColorTo(RelationParticipator rp) - { - return RelationUtil.getColorOfThatToMe(this, rp); - } - - //----------------------------------------------// - // Health - //----------------------------------------------// - public void heal(int amnt) - { - Player player = this.getPlayer(); - if (player == null) - { - return; - } - player.setHealth(player.getHealth() + amnt); - } - - - //----------------------------------------------// - // Power - //----------------------------------------------// - public double getPower() - { - this.updatePower(); - return this.power; - } - - protected void alterPower(double delta) - { - this.power += delta; - if (this.power > this.getPowerMax()) - this.power = this.getPowerMax(); - else if (this.power < this.getPowerMin()) - this.power = this.getPowerMin(); - } - - public double getPowerMax() - { - return Conf.powerPlayerMax + this.powerBoost; - } - - public double getPowerMin() - { - return Conf.powerPlayerMin + this.powerBoost; - } - - public int getPowerRounded() - { - return (int) Math.round(this.getPower()); - } - - public int getPowerMaxRounded() - { - return (int) Math.round(this.getPowerMax()); - } - - public int getPowerMinRounded() - { - return (int) Math.round(this.getPowerMin()); - } - - protected void updatePower() - { - if (this.isOffline()) - { - losePowerFromBeingOffline(); - if (!Conf.powerRegenOffline) - { - return; - } - } - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; - Player thisPlayer = this.getPlayer(); - if (thisPlayer != null && thisPlayer.isDead()) return; // don't let dead players regain power until they respawn + // Chat Tag: + // These are injected into the format of global chat messages. - int millisPerMinute = 60*1000; - this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute); - } + public String getChatTag() { + if (!this.hasFaction()) { + return ""; + } - protected void losePowerFromBeingOffline() - { - if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) - { - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; + return String.format(Conf.chatTagFormat, this.role.getPrefix() + this.getTag()); + } - double loss = millisPassed * Conf.powerOfflineLossPerDay / (24*60*60*1000); - if (this.power - loss < Conf.powerOfflineLossLimit) - { - loss = this.power; - } - this.alterPower(-loss); - } - } - - public void onDeath() - { - this.updatePower(); - this.alterPower(-Conf.powerPerDeath); - } - - //----------------------------------------------// - // Territory - //----------------------------------------------// - public boolean isInOwnTerritory() - { - return Board.getFactionAt(new FLocation(this)) == this.getFaction(); - } - - public boolean isInOthersTerritory() - { - Faction factionHere = Board.getFactionAt(new FLocation(this)); - return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); - } + // Colored Chat Tag + public String getChatTag(Faction faction) { + if (!this.hasFaction()) { + return ""; + } - public boolean isInAllyTerritory() - { - return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); - } + return this.getRelationTo(faction).getColor() + getChatTag(); + } - public boolean isInNeutralTerritory() - { - return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); - } + public String getChatTag(FPlayer fplayer) { + if (!this.hasFaction()) { + return ""; + } - public boolean isInEnemyTerritory() - { - return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); - } + return this.getColorTo(fplayer) + getChatTag(); + } - public void sendFactionHereMessage() - { - if (SpoutFeatures.updateTerritoryDisplay(this)) - { - return; - } - Faction factionHere = Board.getFactionAt(this.getLastStoodAt()); - String msg = P.p.txt.parse("")+" ~ "+factionHere.getTag(this); - if (factionHere.getDescription().length() > 0) - { - msg += " - "+factionHere.getDescription(); - } - this.sendMessage(msg); - } - - // ------------------------------- - // Actions - // ------------------------------- - - public void leave(boolean makePay) - { - Faction myFaction = this.getFaction(); - makePay = makePay && Econ.shouldBeUsed() && ! this.isAdminBypassing(); + // ------------------------------- + // Relation and relation colors + // ------------------------------- - if (myFaction == null) - { - resetFactionData(); - return; - } + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } - boolean perm = myFaction.isPermanent(); - - if (!perm && this.getRole() == Role.ADMIN && myFaction.getFPlayers().size() > 1) - { - msg("You must give the admin role to someone else first."); - return; - } + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } - if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) - { - msg("You cannot leave until your power is positive."); - return; - } + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } - // if economy is enabled and they're not on the bypass list, make sure they can pay - if (makePay && ! Econ.hasAtLeast(this, Conf.econCostLeave, "to leave your faction.")) return; + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } - FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this,myFaction,FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); - Bukkit.getServer().getPluginManager().callEvent(leaveEvent); - if (leaveEvent.isCancelled()) return; + public Relation getRelationToLocation() { + return Board.getFactionAt(new FLocation(this)).getRelationTo(this); + } - // then make 'em pay (if applicable) - if (makePay && ! Econ.modifyMoney(this, -Conf.econCostLeave, "to leave your faction.", "for leaving your faction.")) return; + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } - // Am I the last one in the faction? - if (myFaction.getFPlayers().size() == 1) - { - // Transfer all money - if (Econ.shouldBeUsed()) - Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); - } - - if (myFaction.isNormal()) - { - for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) - { - fplayer.msg("%s left %s.", this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); - } + //----------------------------------------------// + // Health + //----------------------------------------------// + public void heal(int amnt) { + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.setHealth(player.getHealth() + amnt); + } - if (Conf.logFactionLeave) - P.p.log(this.getName()+" left the faction: "+myFaction.getTag()); - } - - this.resetFactionData(); - if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) - { - // Remove this faction - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - fplayer.msg("%s was disbanded.", myFaction.describeTo(fplayer, true)); - } + //----------------------------------------------// + // Power + //----------------------------------------------// + public double getPower() { + this.updatePower(); + return this.power; + } - myFaction.detach(); - if (Conf.logFactionDisband) - P.p.log("The faction "+myFaction.getTag()+" ("+myFaction.getId()+") was disbanded due to the last player ("+this.getName()+") leaving."); - } - } - - public boolean canClaimForFaction(Faction forFaction) - { - if (forFaction.isNone()) return false; + protected void alterPower(double delta) { + this.power += delta; + if (this.power > this.getPowerMax()) + this.power = this.getPowerMax(); + else if (this.power < this.getPowerMin()) + this.power = this.getPowerMin(); + } - if - ( - this.isAdminBypassing() - || (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) - || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) - || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) - ) - { - return true; - } + public double getPowerMax() { + return Conf.powerPlayerMax + this.powerBoost; + } - return false; - } + public double getPowerMin() { + return Conf.powerPlayerMin + this.powerBoost; + } - public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) - { - String error = null; - FLocation flocation = new FLocation(location); - Faction myFaction = getFaction(); - Faction currentFaction = Board.getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); - - if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(location)) - { - // Checks for WorldGuard regions in the chunk attempting to be claimed - error = P.p.txt.parse("This land is protected"); - } - else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) - { - error = P.p.txt.parse("Sorry, this world has land claiming disabled."); - } - else if (this.isAdminBypassing()) - { - return true; - } - else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) - { - return true; - } - else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) - { - return true; - } - else if (myFaction != forFaction) - { - error = P.p.txt.parse("You can't claim land for %s.", forFaction.describeTo(this)); - } - else if (forFaction == currentFaction) - { - error = P.p.txt.parse("%s already own this land.", forFaction.describeTo(this, true)); - } - else if (this.getRole().value < Role.MODERATOR.value) - { - error = P.p.txt.parse("You must be %s to claim land.", Role.MODERATOR.toString()); - } - else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) - { - error = P.p.txt.parse("Factions must have at least %s members to claim land.", Conf.claimsRequireMinFactionMembers); - } - else if (currentFaction.isSafeZone()) - { - error = P.p.txt.parse("You can not claim a Safe Zone."); - } - else if (currentFaction.isWarZone()) - { - error = P.p.txt.parse("You can not claim a War Zone."); - } - else if (ownedLand >= forFaction.getPowerRounded()) - { - error = P.p.txt.parse("You can't claim more land! You need more power!"); - } - else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) - { - error = P.p.txt.parse("Limit reached. You can't claim more land!"); - } - else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) - { - error = P.p.txt.parse("You can't claim the land of your allies."); - } - else if - ( - Conf.claimsMustBeConnected - && ! this.isAdminBypassing() - && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 - && !Board.isConnectedLocation(flocation, myFaction) - && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal()) - ) - { - if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) - error = P.p.txt.parse("You can only claim additional land which is connected to your first claim or controlled by another faction!"); - else - error = P.p.txt.parse("You can only claim additional land which is connected to your first claim!"); - } - else if (currentFaction.isNormal()) - { - if (myFaction.isPeaceful()) - { - error = P.p.txt.parse("%s owns this land. Your faction is peaceful, so you cannot claim land from other factions.", currentFaction.getTag(this)); - } - else if (currentFaction.isPeaceful()) - { - error = P.p.txt.parse("%s owns this land, and is a peaceful faction. You cannot claim land from them.", currentFaction.getTag(this)); - } - else if ( ! currentFaction.hasLandInflation()) - { - // TODO more messages WARN current faction most importantly - error = P.p.txt.parse("%s owns this land and is strong enough to keep it.", currentFaction.getTag(this)); - } - else if ( ! Board.isBorderLocation(flocation)) - { - error = P.p.txt.parse("You must start claiming land at the border of the territory."); - } - } - - if (notifyFailure && error != null) - { - msg(error); - } - return error == null; - } - - public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) - { - // notifyFailure is false if called by auto-claim; no need to notify on every failure for it - // return value is false on failure, true on success - - FLocation flocation = new FLocation(location); - Faction currentFaction = Board.getFactionAt(flocation); - - int ownedLand = forFaction.getLandRounded(); - - if ( ! this.canClaimForFactionAtLocation(forFaction, location, notifyFailure)) return false; + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } - // if economy is enabled and they're not on the bypass list, make sure they can pay - boolean mustPay = Econ.shouldBeUsed() && ! this.isAdminBypassing() && ! forFaction.isSafeZone() && ! forFaction.isWarZone(); - double cost = 0.0; - EconomyParticipator payee = null; - if (mustPay) - { - cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } - if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.isConnectedLocation(flocation, forFaction)) - cost += Conf.econClaimUnconnectedFee; + public int getPowerMinRounded() { + return (int) Math.round(this.getPowerMin()); + } - if(Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) - payee = this.getFaction(); - else - payee = this; + protected void updatePower() { + if (this.isOffline()) { + losePowerFromBeingOffline(); + if (!Conf.powerRegenOffline) { + return; + } + } + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; - if ( ! Econ.hasAtLeast(payee, cost, "to claim this land")) return false; - } + Player thisPlayer = this.getPlayer(); + if (thisPlayer != null && thisPlayer.isDead()) + return; // don't let dead players regain power until they respawn - LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); - Bukkit.getServer().getPluginManager().callEvent(claimEvent); - if(claimEvent.isCancelled()) return false; + int millisPerMinute = 60 * 1000; + this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute); + } - // then make 'em pay (if applicable) - if (mustPay && ! Econ.modifyMoney(payee, -cost, "to claim this land", "for claiming this land")) return false; + protected void losePowerFromBeingOffline() { + if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; - if (LWCFeatures.getEnabled() && forFaction.isNormal() && Conf.onCaptureResetLwcLocks) - { - LWCFeatures.clearOtherChests(flocation, this.getFaction()); - } - - // announce success - Set informTheseFPlayers = new HashSet(); - informTheseFPlayers.add(this); - informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); - for (FPlayer fp : informTheseFPlayers) - { - fp.msg("%s claimed land for %s from %s.", this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); - } - - Board.setFactionAt(forFaction, flocation); - SpoutFeatures.updateTerritoryDisplayLoc(flocation); + double loss = millisPassed * Conf.powerOfflineLossPerDay / (24 * 60 * 60 * 1000); + if (this.power - loss < Conf.powerOfflineLossLimit) { + loss = this.power; + } + this.alterPower(-loss); + } + } - if (Conf.logLandClaims) - P.p.log(this.getName()+" claimed land at ("+flocation.getCoordString()+") for the faction: "+forFaction.getTag()); + public void onDeath() { + this.updatePower(); + this.alterPower(-Conf.powerPerDeath); + } - return true; - } - - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // - - @Override - public boolean shouldBeSaved() - { - if (!this.hasFaction() && - (this.getPowerRounded() == this.getPowerMaxRounded() || this.getPowerRounded() == (int) Math.round(Conf.powerPlayerStarting)) - ) - return false; - return ! this.deleteMe; - } - - public void msg(String str, Object... args) - { - this.sendMessage(P.p.txt.parse(str, args)); - } + //----------------------------------------------// + // Territory + //----------------------------------------------// + public boolean isInOwnTerritory() { + return Board.getFactionAt(new FLocation(this)) == this.getFaction(); + } + + public boolean isInOthersTerritory() { + Faction factionHere = Board.getFactionAt(new FLocation(this)); + return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); + } + + public boolean isInAllyTerritory() { + return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); + } + + public boolean isInNeutralTerritory() { + return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); + } + + public boolean isInEnemyTerritory() { + return Board.getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); + } + + public void sendFactionHereMessage() { + if (SpoutFeatures.updateTerritoryDisplay(this)) { + return; + } + Faction factionHere = Board.getFactionAt(this.getLastStoodAt()); + String msg = P.p.txt.parse("") + " ~ " + factionHere.getTag(this); + if (factionHere.getDescription().length() > 0) { + msg += " - " + factionHere.getDescription(); + } + this.sendMessage(msg); + } + + // ------------------------------- + // Actions + // ------------------------------- + + public void leave(boolean makePay) { + Faction myFaction = this.getFaction(); + makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); + + if (myFaction == null) { + resetFactionData(); + return; + } + + boolean perm = myFaction.isPermanent(); + + if (!perm && this.getRole() == Role.ADMIN && myFaction.getFPlayers().size() > 1) { + msg("You must give the admin role to someone else first."); + return; + } + + if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { + msg("You cannot leave until your power is positive."); + return; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + if (makePay && !Econ.hasAtLeast(this, Conf.econCostLeave, "to leave your faction.")) return; + + FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); + Bukkit.getServer().getPluginManager().callEvent(leaveEvent); + if (leaveEvent.isCancelled()) return; + + // then make 'em pay (if applicable) + if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, "to leave your faction.", "for leaving your faction.")) + return; + + // Am I the last one in the faction? + if (myFaction.getFPlayers().size() == 1) { + // Transfer all money + if (Econ.shouldBeUsed()) + Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); + } + + if (myFaction.isNormal()) { + for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { + fplayer.msg("%s left %s.", this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); + } + + if (Conf.logFactionLeave) + P.p.log(this.getName() + " left the faction: " + myFaction.getTag()); + } + + this.resetFactionData(); + + if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { + // Remove this faction + for (FPlayer fplayer : FPlayers.i.getOnline()) { + fplayer.msg("%s was disbanded.", myFaction.describeTo(fplayer, true)); + } + + myFaction.detach(); + if (Conf.logFactionDisband) + P.p.log("The faction " + myFaction.getTag() + " (" + myFaction.getId() + ") was disbanded due to the last player (" + this.getName() + ") leaving."); + } + } + + public boolean canClaimForFaction(Faction forFaction) { + if (forFaction.isNone()) return false; + + if + ( + this.isAdminBypassing() + || (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) + || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) + || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) + ) { + return true; + } + + return false; + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { + String error = null; + FLocation flocation = new FLocation(location); + Faction myFaction = getFaction(); + Faction currentFaction = Board.getFactionAt(flocation); + int ownedLand = forFaction.getLandRounded(); + + if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(location)) { + // Checks for WorldGuard regions in the chunk attempting to be claimed + error = P.p.txt.parse("This land is protected"); + } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { + error = P.p.txt.parse("Sorry, this world has land claiming disabled."); + } else if (this.isAdminBypassing()) { + return true; + } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { + return true; + } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { + return true; + } else if (myFaction != forFaction) { + error = P.p.txt.parse("You can't claim land for %s.", forFaction.describeTo(this)); + } else if (forFaction == currentFaction) { + error = P.p.txt.parse("%s already own this land.", forFaction.describeTo(this, true)); + } else if (this.getRole().value < Role.MODERATOR.value) { + error = P.p.txt.parse("You must be %s to claim land.", Role.MODERATOR.toString()); + } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { + error = P.p.txt.parse("Factions must have at least %s members to claim land.", Conf.claimsRequireMinFactionMembers); + } else if (currentFaction.isSafeZone()) { + error = P.p.txt.parse("You can not claim a Safe Zone."); + } else if (currentFaction.isWarZone()) { + error = P.p.txt.parse("You can not claim a War Zone."); + } else if (ownedLand >= forFaction.getPowerRounded()) { + error = P.p.txt.parse("You can't claim more land! You need more power!"); + } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { + error = P.p.txt.parse("Limit reached. You can't claim more land!"); + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + error = P.p.txt.parse("You can't claim the land of your allies."); + } else if + ( + Conf.claimsMustBeConnected + && !this.isAdminBypassing() + && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 + && !Board.isConnectedLocation(flocation, myFaction) + && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal()) + ) { + if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) + error = P.p.txt.parse("You can only claim additional land which is connected to your first claim or controlled by another faction!"); + else + error = P.p.txt.parse("You can only claim additional land which is connected to your first claim!"); + } else if (currentFaction.isNormal()) { + if (myFaction.isPeaceful()) { + error = P.p.txt.parse("%s owns this land. Your faction is peaceful, so you cannot claim land from other factions.", currentFaction.getTag(this)); + } else if (currentFaction.isPeaceful()) { + error = P.p.txt.parse("%s owns this land, and is a peaceful faction. You cannot claim land from them.", currentFaction.getTag(this)); + } else if (!currentFaction.hasLandInflation()) { + // TODO more messages WARN current faction most importantly + error = P.p.txt.parse("%s owns this land and is strong enough to keep it.", currentFaction.getTag(this)); + } else if (!Board.isBorderLocation(flocation)) { + error = P.p.txt.parse("You must start claiming land at the border of the territory."); + } + } + + if (notifyFailure && error != null) { + msg(error); + } + return error == null; + } + + public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { + // notifyFailure is false if called by auto-claim; no need to notify on every failure for it + // return value is false on failure, true on success + + FLocation flocation = new FLocation(location); + Faction currentFaction = Board.getFactionAt(flocation); + + int ownedLand = forFaction.getLandRounded(); + + if (!this.canClaimForFactionAtLocation(forFaction, location, notifyFailure)) return false; + + // if economy is enabled and they're not on the bypass list, make sure they can pay + boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); + double cost = 0.0; + EconomyParticipator payee = null; + if (mustPay) { + cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); + + if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.isConnectedLocation(flocation, forFaction)) + cost += Conf.econClaimUnconnectedFee; + + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) + payee = this.getFaction(); + else + payee = this; + + if (!Econ.hasAtLeast(payee, cost, "to claim this land")) return false; + } + + LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); + Bukkit.getServer().getPluginManager().callEvent(claimEvent); + if (claimEvent.isCancelled()) return false; + + // then make 'em pay (if applicable) + if (mustPay && !Econ.modifyMoney(payee, -cost, "to claim this land", "for claiming this land")) return false; + + if (LWCFeatures.getEnabled() && forFaction.isNormal() && Conf.onCaptureResetLwcLocks) { + LWCFeatures.clearOtherChests(flocation, this.getFaction()); + } + + // announce success + Set informTheseFPlayers = new HashSet(); + informTheseFPlayers.add(this); + informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); + for (FPlayer fp : informTheseFPlayers) { + fp.msg("%s claimed land for %s from %s.", this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); + } + + Board.setFactionAt(forFaction, flocation); + SpoutFeatures.updateTerritoryDisplayLoc(flocation); + + if (Conf.logLandClaims) + P.p.log(this.getName() + " claimed land at (" + flocation.getCoordString() + ") for the faction: " + forFaction.getTag()); + + return true; + } + + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // + + @Override + public boolean shouldBeSaved() { + if (!this.hasFaction() && + (this.getPowerRounded() == this.getPowerMaxRounded() || this.getPowerRounded() == (int) Math.round(Conf.powerPlayerStarting)) + ) + return false; + return !this.deleteMe; + } + + public void msg(String str, Object... args) { + this.sendMessage(P.p.txt.parse(str, args)); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/FPlayers.java b/src/main/java/com/massivecraft/factions/FPlayers.java index 0456295a..a18456f0 100644 --- a/src/main/java/com/massivecraft/factions/FPlayers.java +++ b/src/main/java/com/massivecraft/factions/FPlayers.java @@ -1,50 +1,44 @@ package com.massivecraft.factions; +import com.massivecraft.factions.zcore.persist.PlayerEntityCollection; +import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; + import java.io.File; import java.lang.reflect.Type; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.CopyOnWriteArrayList; -import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; -import com.massivecraft.factions.struct.Role; -import com.massivecraft.factions.zcore.persist.PlayerEntityCollection; +public class FPlayers extends PlayerEntityCollection { + public static FPlayers i = new FPlayers(); -public class FPlayers extends PlayerEntityCollection -{ - public static FPlayers i = new FPlayers(); - - P p = P.p; - - private FPlayers() - { - super - ( - FPlayer.class, - new CopyOnWriteArrayList(), - new ConcurrentSkipListMap(String.CASE_INSENSITIVE_ORDER), - new File(P.p.getDataFolder(), "players.json"), - P.p.gson - ); - - this.setCreative(true); - } - - @Override - public Type getMapType() - { - return new TypeToken>(){}.getType(); - } - - public void clean() - { - for (FPlayer fplayer : this.get()) - { - if ( ! Factions.i.exists(fplayer.getFactionId())) - { - p.log("Reset faction data (invalid faction) for player "+fplayer.getName()); - fplayer.resetFactionData(false); - } - } - } + P p = P.p; + + private FPlayers() { + super + ( + FPlayer.class, + new CopyOnWriteArrayList(), + new ConcurrentSkipListMap(String.CASE_INSENSITIVE_ORDER), + new File(P.p.getDataFolder(), "players.json"), + P.p.gson + ); + + this.setCreative(true); + } + + @Override + public Type getMapType() { + return new TypeToken>() { + }.getType(); + } + + public void clean() { + for (FPlayer fplayer : this.get()) { + if (!Factions.i.exists(fplayer.getFactionId())) { + p.log("Reset faction data (invalid faction) for player " + fplayer.getName()); + fplayer.resetFactionData(false); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/Faction.java b/src/main/java/com/massivecraft/factions/Faction.java index 9f45869e..40855313 100644 --- a/src/main/java/com/massivecraft/factions/Faction.java +++ b/src/main/java/com/massivecraft/factions/Faction.java @@ -1,14 +1,5 @@ package com.massivecraft.factions; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.Player; - import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.iface.RelationParticipator; import com.massivecraft.factions.integration.Econ; @@ -18,702 +9,688 @@ import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.util.*; import com.massivecraft.factions.zcore.persist.Entity; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; -public class Faction extends Entity implements EconomyParticipator -{ - // FIELD: relationWish - private Map relationWish; - - // FIELD: claimOwnership - private Map> claimOwnership = new ConcurrentHashMap>(); +public class Faction extends Entity implements EconomyParticipator { + // FIELD: relationWish + private Map relationWish; - // FIELD: fplayers - // speedy lookup of players in faction - private transient Set fplayers = new HashSet(); + // FIELD: claimOwnership + private Map> claimOwnership = new ConcurrentHashMap>(); - // FIELD: invites - // Where string is a lowercase player name - private Set invites; - public void invite(FPlayer fplayer) { this.invites.add(fplayer.getName().toLowerCase()); } - public void deinvite(FPlayer fplayer) { this.invites.remove(fplayer.getName().toLowerCase()); } - public boolean isInvited(FPlayer fplayer) { return this.invites.contains(fplayer.getName().toLowerCase()); } - - // FIELD: open - private boolean open; - public boolean getOpen() { return open; } - public void setOpen(boolean isOpen) { open = isOpen; } - - // FIELD: peaceful - // "peaceful" status can only be set by server admins/moderators/ops, and prevents PvP and land capture to/from the faction - private boolean peaceful; - public boolean isPeaceful() { return this.peaceful; } - public void setPeaceful(boolean isPeaceful) { this.peaceful = isPeaceful; } - - // FIELD: peacefulExplosionsEnabled - private boolean peacefulExplosionsEnabled; - public void setPeacefulExplosionsEnabled(boolean val) { peacefulExplosionsEnabled = val; } - public boolean getPeacefulExplosionsEnabled(){ return this.peacefulExplosionsEnabled; } - - public boolean noExplosionsInTerritory() { return this.peaceful && ! peacefulExplosionsEnabled; } + // FIELD: fplayers + // speedy lookup of players in faction + private transient Set fplayers = new HashSet(); - // FIELD: permanent - // "permanent" status can only be set by server admins/moderators/ops, and allows the faction to remain even with 0 members - private boolean permanent; - public boolean isPermanent() { return permanent || !this.isNormal(); } - public void setPermanent(boolean isPermanent) { permanent = isPermanent; } - - // FIELD: tag - private String tag; - public String getTag() { return this.tag; } - public String getTag(String prefix) { return prefix+this.tag; } - public String getTag(Faction otherFaction) - { - if (otherFaction == null) - { - return getTag(); - } - return this.getTag(this.getColorTo(otherFaction).toString()); - } - public String getTag(FPlayer otherFplayer) { - if (otherFplayer == null) - { - return getTag(); - } - return this.getTag(this.getColorTo(otherFplayer).toString()); - } - public void setTag(String str) - { - if (Conf.factionTagForceUpperCase) - { - str = str.toUpperCase(); - } - this.tag = str; - } - public String getComparisonTag() { return MiscUtil.getComparisonString(this.tag); } - - // FIELD: description - private String description; - public String getDescription() { return this.description; } - public void setDescription(String value) { this.description = value; } - - // FIELD: home - private LazyLocation home; - public void setHome(Location home) { this.home = new LazyLocation(home); } - public boolean hasHome() { return this.getHome() != null; } - public Location getHome() - { - confirmValidHome(); - return (this.home != null) ? this.home.getLocation() : null; - } - public void confirmValidHome() - { - if (!Conf.homesMustBeInClaimedTerritory || this.home == null || (this.home.getLocation() != null && Board.getFactionAt(new FLocation(this.home.getLocation())) == this)) - return; + // FIELD: invites + // Where string is a lowercase player name + private Set invites; - msg("Your faction home has been un-set since it is no longer in your territory."); - this.home = null; - } - - // FIELD: lastPlayerLoggedOffTime - private transient long lastPlayerLoggedOffTime; - - // FIELD: account (fake field) - // Bank functions - public double money; - public String getAccountId() - { - String aid = "faction-"+this.getId(); + public void invite(FPlayer fplayer) { + this.invites.add(fplayer.getName().toLowerCase()); + } - // We need to override the default money given to players. - if ( ! Econ.hasAccount(aid)) - Econ.setBalance(aid, 0); + public void deinvite(FPlayer fplayer) { + this.invites.remove(fplayer.getName().toLowerCase()); + } - return aid; - } - - // FIELD: permanentPower - private Integer permanentPower; - public Integer getPermanentPower() { return this.permanentPower; } - public void setPermanentPower(Integer permanentPower) { this.permanentPower = permanentPower; } - public boolean hasPermanentPower() { return this.permanentPower != null; } + public boolean isInvited(FPlayer fplayer) { + return this.invites.contains(fplayer.getName().toLowerCase()); + } - // FIELD: powerBoost - // special increase/decrease to default and max power for this faction - private double powerBoost; - public double getPowerBoost() { return this.powerBoost; } - public void setPowerBoost(double powerBoost) { this.powerBoost = powerBoost; } + // FIELD: open + private boolean open; + + public boolean getOpen() { + return open; + } + + public void setOpen(boolean isOpen) { + open = isOpen; + } + + // FIELD: peaceful + // "peaceful" status can only be set by server admins/moderators/ops, and prevents PvP and land capture to/from the faction + private boolean peaceful; + + public boolean isPeaceful() { + return this.peaceful; + } + + public void setPeaceful(boolean isPeaceful) { + this.peaceful = isPeaceful; + } + + // FIELD: peacefulExplosionsEnabled + private boolean peacefulExplosionsEnabled; + + public void setPeacefulExplosionsEnabled(boolean val) { + peacefulExplosionsEnabled = val; + } + + public boolean getPeacefulExplosionsEnabled() { + return this.peacefulExplosionsEnabled; + } + + public boolean noExplosionsInTerritory() { + return this.peaceful && !peacefulExplosionsEnabled; + } + + // FIELD: permanent + // "permanent" status can only be set by server admins/moderators/ops, and allows the faction to remain even with 0 members + private boolean permanent; + + public boolean isPermanent() { + return permanent || !this.isNormal(); + } + + public void setPermanent(boolean isPermanent) { + permanent = isPermanent; + } + + // FIELD: tag + private String tag; + + public String getTag() { + return this.tag; + } + + public String getTag(String prefix) { + return prefix + this.tag; + } + + public String getTag(Faction otherFaction) { + if (otherFaction == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFaction).toString()); + } + + public String getTag(FPlayer otherFplayer) { + if (otherFplayer == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFplayer).toString()); + } + + public void setTag(String str) { + if (Conf.factionTagForceUpperCase) { + str = str.toUpperCase(); + } + this.tag = str; + } + + public String getComparisonTag() { + return MiscUtil.getComparisonString(this.tag); + } + + // FIELD: description + private String description; + + public String getDescription() { + return this.description; + } + + public void setDescription(String value) { + this.description = value; + } + + // FIELD: home + private LazyLocation home; + + public void setHome(Location home) { + this.home = new LazyLocation(home); + } + + public boolean hasHome() { + return this.getHome() != null; + } + + public Location getHome() { + confirmValidHome(); + return (this.home != null) ? this.home.getLocation() : null; + } + + public void confirmValidHome() { + if (!Conf.homesMustBeInClaimedTerritory || this.home == null || (this.home.getLocation() != null && Board.getFactionAt(new FLocation(this.home.getLocation())) == this)) + return; + + msg("Your faction home has been un-set since it is no longer in your territory."); + this.home = null; + } + + // FIELD: lastPlayerLoggedOffTime + private transient long lastPlayerLoggedOffTime; + + // FIELD: account (fake field) + // Bank functions + public double money; + + public String getAccountId() { + String aid = "faction-" + this.getId(); + + // We need to override the default money given to players. + if (!Econ.hasAccount(aid)) + Econ.setBalance(aid, 0); + + return aid; + } + + // FIELD: permanentPower + private Integer permanentPower; + + public Integer getPermanentPower() { + return this.permanentPower; + } + + public void setPermanentPower(Integer permanentPower) { + this.permanentPower = permanentPower; + } + + public boolean hasPermanentPower() { + return this.permanentPower != null; + } + + // FIELD: powerBoost + // special increase/decrease to default and max power for this faction + private double powerBoost; + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } - // -------------------------------------------- // - // Construct - // -------------------------------------------- // - - public Faction() - { - this.relationWish = new HashMap(); - this.invites = new HashSet(); - this.open = Conf.newFactionsDefaultOpen; - this.tag = "???"; - this.description = "Default faction description :("; - this.lastPlayerLoggedOffTime = 0; - this.peaceful = false; - this.peacefulExplosionsEnabled = false; - this.permanent = false; - this.money = 0.0; - this.powerBoost = 0.0; - } - - // -------------------------------------------- // - // Extra Getters And Setters - // -------------------------------------------- // + // -------------------------------------------- // + // Construct + // -------------------------------------------- // - public boolean noPvPInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); } + public Faction() { + this.relationWish = new HashMap(); + this.invites = new HashSet(); + this.open = Conf.newFactionsDefaultOpen; + this.tag = "???"; + this.description = "Default faction description :("; + this.lastPlayerLoggedOffTime = 0; + this.peaceful = false; + this.peacefulExplosionsEnabled = false; + this.permanent = false; + this.money = 0.0; + this.powerBoost = 0.0; + } - public boolean noMonstersInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); } + // -------------------------------------------- // + // Extra Getters And Setters + // -------------------------------------------- // - + public boolean noPvPInTerritory() { + return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); + } - // ------------------------------- - // Understand the types - // ------------------------------- - - public boolean isNormal() - { - return ! (this.isNone() || this.isSafeZone() || this.isWarZone()); - } - - public boolean isNone() - { - return this.getId().equals("0"); - } - - public boolean isSafeZone() - { - return this.getId().equals("-1"); - } - - public boolean isWarZone() - { - return this.getId().equals("-2"); - } - - public boolean isPlayerFreeType() - { - return this.isSafeZone() || this.isWarZone(); - } - - - // ------------------------------- - // Relation and relation colors - // ------------------------------- - - @Override - public String describeTo(RelationParticipator that, boolean ucfirst) - { - return RelationUtil.describeThatToMe(this, that, ucfirst); - } - - @Override - public String describeTo(RelationParticipator that) - { - return RelationUtil.describeThatToMe(this, that); - } - - @Override - public Relation getRelationTo(RelationParticipator rp) - { - return RelationUtil.getRelationTo(this, rp); - } - - @Override - public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) - { - return RelationUtil.getRelationTo(this, rp, ignorePeaceful); - } - - @Override - public ChatColor getColorTo(RelationParticipator rp) - { - return RelationUtil.getColorOfThatToMe(this, rp); - } - - public Relation getRelationWish(Faction otherFaction) - { - if (this.relationWish.containsKey(otherFaction.getId())) - { - return this.relationWish.get(otherFaction.getId()); - } - return Relation.NEUTRAL; - } - - public void setRelationWish(Faction otherFaction, Relation relation) - { - if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) - { - this.relationWish.remove(otherFaction.getId()); - } - else - { - this.relationWish.put(otherFaction.getId(), relation); - } - } - - //----------------------------------------------// - // Power - //----------------------------------------------// - public double getPower() - { - if (this.hasPermanentPower()) - { - return this.getPermanentPower(); - } - - double ret = 0; - for (FPlayer fplayer : fplayers) - { - ret += fplayer.getPower(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) - { - ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; - } - - public double getPowerMax() - { - if (this.hasPermanentPower()) - { - return this.getPermanentPower(); - } - - double ret = 0; - for (FPlayer fplayer : fplayers) - { - ret += fplayer.getPowerMax(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) - { - ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; - } - - public int getPowerRounded() - { - return (int) Math.round(this.getPower()); - } - - public int getPowerMaxRounded() - { - return (int) Math.round(this.getPowerMax()); - } - - public int getLandRounded() { - return Board.getFactionCoordCount(this); - } - - public int getLandRoundedInWorld(String worldName) - { - return Board.getFactionCoordCountInWorld(this, worldName); - } - - public boolean hasLandInflation() - { - return this.getLandRounded() > this.getPowerRounded(); - } - - // ------------------------------- - // FPlayers - // ------------------------------- - - // maintain the reference list of FPlayers in this faction - public void refreshFPlayers() - { - fplayers.clear(); - if (this.isPlayerFreeType()) return; - - for (FPlayer fplayer : FPlayers.i.get()) - { - if (fplayer.getFaction() == this) - { - fplayers.add(fplayer); - } - } - } - protected boolean addFPlayer(FPlayer fplayer) - { - if (this.isPlayerFreeType()) return false; - - return fplayers.add(fplayer); - } - protected boolean removeFPlayer(FPlayer fplayer) - { - if (this.isPlayerFreeType()) return false; - - return fplayers.remove(fplayer); - } - - public Set getFPlayers() - { - // return a shallow copy of the FPlayer list, to prevent tampering and concurrency issues - Set ret = new HashSet(fplayers); - return ret; - } - - public Set getFPlayersWhereOnline(boolean online) - { - Set ret = new HashSet(); - - for (FPlayer fplayer : fplayers) - { - if (fplayer.isOnline() == online) - { - ret.add(fplayer); - } - } - - return ret; - } - - public FPlayer getFPlayerAdmin() - { - if ( ! this.isNormal()) return null; - - for (FPlayer fplayer : fplayers) - { - if (fplayer.getRole() == Role.ADMIN) - { - return fplayer; - } - } - return null; - } - - public ArrayList getFPlayersWhereRole(Role role) - { - ArrayList ret = new ArrayList(); - if ( ! this.isNormal()) return ret; - - for (FPlayer fplayer : fplayers) - { - if (fplayer.getRole() == role) - { - ret.add(fplayer); - } - } - - return ret; - } - - public ArrayList getOnlinePlayers() - { - ArrayList ret = new ArrayList(); - if (this.isPlayerFreeType()) return ret; - - for (Player player: P.p.getServer().getOnlinePlayers()) - { - FPlayer fplayer = FPlayers.i.get(player); - if (fplayer.getFaction() == this) - { - ret.add(player); - } - } - - return ret; - } - - // slightly faster check than getOnlinePlayers() if you just want to see if there are any players online - public boolean hasPlayersOnline() - { - // only real factions can have players online, not safe zone / war zone - if (this.isPlayerFreeType()) return false; - - for (Player player: P.p.getServer().getOnlinePlayers()) - { - FPlayer fplayer = FPlayers.i.get(player); - if (fplayer.getFaction() == this) - { - return true; - } - } - - // even if all players are technically logged off, maybe someone was on recently enough to not consider them officially offline yet - if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000)) - { - return true; - } - return false; - } - - public void memberLoggedOff() - { - if (this.isNormal()) - { - lastPlayerLoggedOffTime = System.currentTimeMillis(); - } - } - - // used when current leader is about to be removed from the faction; promotes new leader, or disbands faction if no other members left - public void promoteNewLeader() - { - if (! this.isNormal()) return; - if (this.isPermanent() && Conf.permanentFactionsDisableLeaderPromotion) return; - - FPlayer oldLeader = this.getFPlayerAdmin(); - - // get list of moderators, or list of normal members if there are no moderators - ArrayList replacements = this.getFPlayersWhereRole(Role.MODERATOR); - if (replacements == null || replacements.isEmpty()) - replacements = this.getFPlayersWhereRole(Role.NORMAL); - - if (replacements == null || replacements.isEmpty()) - { // faction admin is the only member; one-man faction - if (this.isPermanent()) - { - if (oldLeader != null) - oldLeader.setRole(Role.NORMAL); - return; - } - - // no members left and faction isn't permanent, so disband it - if (Conf.logFactionDisband) - P.p.log("The faction "+this.getTag()+" ("+this.getId()+") has been disbanded since it has no members left."); - - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - fplayer.msg("The faction %s was disbanded.", this.getTag(fplayer)); - } - - this.detach(); - } - else - { // promote new faction admin - if (oldLeader != null) - oldLeader.setRole(Role.NORMAL); - replacements.get(0).setRole(Role.ADMIN); - this.msg("Faction admin %s has been removed. %s has been promoted as the new faction admin.", oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName()); - P.p.log("Faction "+this.getTag()+" ("+this.getId()+") admin was removed. Replacement admin: "+replacements.get(0).getName()); - } - } + public boolean noMonstersInTerritory() { + return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); + } - //----------------------------------------------// - // Messages - //----------------------------------------------// - public void msg(String message, Object... args) - { - message = P.p.txt.parse(message, args); - - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) - { - fplayer.sendMessage(message); - } - } - - public void sendMessage(String message) - { - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) - { - fplayer.sendMessage(message); - } - } - - public void sendMessage(List messages) - { - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) - { - fplayer.sendMessage(messages); - } - } - - //----------------------------------------------// - // Ownership of specific claims - //----------------------------------------------// + // ------------------------------- + // Understand the types + // ------------------------------- - public void clearAllClaimOwnership() - { - claimOwnership.clear(); - } + public boolean isNormal() { + return !(this.isNone() || this.isSafeZone() || this.isWarZone()); + } - public void clearClaimOwnership(FLocation loc) - { - if(Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) - { - LWCFeatures.clearAllChests(loc); - } - claimOwnership.remove(loc); - } + public boolean isNone() { + return this.getId().equals("0"); + } - public void clearClaimOwnership(String playerName) - { - if (playerName == null || playerName.isEmpty()) - { - return; - } + public boolean isSafeZone() { + return this.getId().equals("-1"); + } - Set ownerData; - String player = playerName.toLowerCase(); + public boolean isWarZone() { + return this.getId().equals("-2"); + } - for (Entry> entry : claimOwnership.entrySet()) - { - ownerData = entry.getValue(); + public boolean isPlayerFreeType() { + return this.isSafeZone() || this.isWarZone(); + } - if (ownerData == null) continue; - Iterator iter = ownerData.iterator(); - while (iter.hasNext()) - { - if (iter.next().equals(player)) - { - iter.remove(); - } - } + // ------------------------------- + // Relation and relation colors + // ------------------------------- - if (ownerData.isEmpty()) - { - if(Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) - { - LWCFeatures.clearAllChests(entry.getKey()); - } - claimOwnership.remove(entry.getKey()); - } - } - } + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } - public int getCountOfClaimsWithOwners() - { - return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); - } + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } - public boolean doesLocationHaveOwnersSet(FLocation loc) - { - if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) - { - return false; - } - - Set ownerData = claimOwnership.get(loc); - return ownerData != null && !ownerData.isEmpty(); - } + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } - public boolean isPlayerInOwnerList(String playerName, FLocation loc) - { - if (claimOwnership.isEmpty()) - { - return false; - } - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) - { - return false; - } - if (ownerData.contains(playerName.toLowerCase())) - { - return true; - } - - return false; - } + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } - public void setPlayerAsOwner(String playerName, FLocation loc) - { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) - { - ownerData = new HashSet(); - } - ownerData.add(playerName.toLowerCase()); - claimOwnership.put(loc, ownerData); - } + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } - public void removePlayerAsOwner(String playerName, FLocation loc) - { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) - { - return; - } - ownerData.remove(playerName.toLowerCase()); - claimOwnership.put(loc, ownerData); - } + public Relation getRelationWish(Faction otherFaction) { + if (this.relationWish.containsKey(otherFaction.getId())) { + return this.relationWish.get(otherFaction.getId()); + } + return Relation.NEUTRAL; + } - public Set getOwnerList(FLocation loc) - { - return claimOwnership.get(loc); - } + public void setRelationWish(Faction otherFaction, Relation relation) { + if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) { + this.relationWish.remove(otherFaction.getId()); + } else { + this.relationWish.put(otherFaction.getId(), relation); + } + } - public String getOwnerListString(FLocation loc) - { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null || ownerData.isEmpty()) - { - return ""; - } + //----------------------------------------------// + // Power + //----------------------------------------------// + public double getPower() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } - String ownerList = ""; + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPower(); + } + if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + ret = Conf.powerFactionMax; + } + return ret + this.powerBoost; + } - Iterator iter = ownerData.iterator(); - while (iter.hasNext()) { - if (!ownerList.isEmpty()) - { - ownerList += ", "; - } - ownerList += iter.next(); - } - return ownerList; - } + public double getPowerMax() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } - public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) - { - // in own faction, with sufficient role or permission to bypass ownership? - if - ( - fplayer.getFaction() == this - && - ( - fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.ADMIN) - || - Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()) - ) - ) - { - return true; - } + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPowerMax(); + } + if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + ret = Conf.powerFactionMax; + } + return ret + this.powerBoost; + } - // make sure claimOwnership is initialized - if (claimOwnership.isEmpty()) - return true; + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } - // need to check the ownership list, then - Set ownerData = claimOwnership.get(loc); + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } - // if no owner list, owner list is empty, or player is in owner list, they're allowed - if (ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getName().toLowerCase())) - return true; + public int getLandRounded() { + return Board.getFactionCoordCount(this); + } - return false; - } - - - //----------------------------------------------// - // Persistance and entity management - //----------------------------------------------// + public int getLandRoundedInWorld(String worldName) { + return Board.getFactionCoordCountInWorld(this, worldName); + } - - @Override - public void postDetach() - { - if (Econ.shouldBeUsed()) - { - Econ.setBalance(getAccountId(), 0); - } - - // Clean the board - Board.clean(); - - // Clean the fplayers - FPlayers.i.clean(); - } + public boolean hasLandInflation() { + return this.getLandRounded() > this.getPowerRounded(); + } + + // ------------------------------- + // FPlayers + // ------------------------------- + + // maintain the reference list of FPlayers in this faction + public void refreshFPlayers() { + fplayers.clear(); + if (this.isPlayerFreeType()) return; + + for (FPlayer fplayer : FPlayers.i.get()) { + if (fplayer.getFaction() == this) { + fplayers.add(fplayer); + } + } + } + + protected boolean addFPlayer(FPlayer fplayer) { + if (this.isPlayerFreeType()) return false; + + return fplayers.add(fplayer); + } + + protected boolean removeFPlayer(FPlayer fplayer) { + if (this.isPlayerFreeType()) return false; + + return fplayers.remove(fplayer); + } + + public Set getFPlayers() { + // return a shallow copy of the FPlayer list, to prevent tampering and concurrency issues + Set ret = new HashSet(fplayers); + return ret; + } + + public Set getFPlayersWhereOnline(boolean online) { + Set ret = new HashSet(); + + for (FPlayer fplayer : fplayers) { + if (fplayer.isOnline() == online) { + ret.add(fplayer); + } + } + + return ret; + } + + public FPlayer getFPlayerAdmin() { + if (!this.isNormal()) return null; + + for (FPlayer fplayer : fplayers) { + if (fplayer.getRole() == Role.ADMIN) { + return fplayer; + } + } + return null; + } + + public ArrayList getFPlayersWhereRole(Role role) { + ArrayList ret = new ArrayList(); + if (!this.isNormal()) return ret; + + for (FPlayer fplayer : fplayers) { + if (fplayer.getRole() == role) { + ret.add(fplayer); + } + } + + return ret; + } + + public ArrayList getOnlinePlayers() { + ArrayList ret = new ArrayList(); + if (this.isPlayerFreeType()) return ret; + + for (Player player : P.p.getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.i.get(player); + if (fplayer.getFaction() == this) { + ret.add(player); + } + } + + return ret; + } + + // slightly faster check than getOnlinePlayers() if you just want to see if there are any players online + public boolean hasPlayersOnline() { + // only real factions can have players online, not safe zone / war zone + if (this.isPlayerFreeType()) return false; + + for (Player player : P.p.getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.i.get(player); + if (fplayer.getFaction() == this) { + return true; + } + } + + // even if all players are technically logged off, maybe someone was on recently enough to not consider them officially offline yet + if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000)) { + return true; + } + return false; + } + + public void memberLoggedOff() { + if (this.isNormal()) { + lastPlayerLoggedOffTime = System.currentTimeMillis(); + } + } + + // used when current leader is about to be removed from the faction; promotes new leader, or disbands faction if no other members left + public void promoteNewLeader() { + if (!this.isNormal()) return; + if (this.isPermanent() && Conf.permanentFactionsDisableLeaderPromotion) return; + + FPlayer oldLeader = this.getFPlayerAdmin(); + + // get list of moderators, or list of normal members if there are no moderators + ArrayList replacements = this.getFPlayersWhereRole(Role.MODERATOR); + if (replacements == null || replacements.isEmpty()) + replacements = this.getFPlayersWhereRole(Role.NORMAL); + + if (replacements == null || replacements.isEmpty()) { // faction admin is the only member; one-man faction + if (this.isPermanent()) { + if (oldLeader != null) + oldLeader.setRole(Role.NORMAL); + return; + } + + // no members left and faction isn't permanent, so disband it + if (Conf.logFactionDisband) + P.p.log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left."); + + for (FPlayer fplayer : FPlayers.i.getOnline()) { + fplayer.msg("The faction %s was disbanded.", this.getTag(fplayer)); + } + + this.detach(); + } else { // promote new faction admin + if (oldLeader != null) + oldLeader.setRole(Role.NORMAL); + replacements.get(0).setRole(Role.ADMIN); + this.msg("Faction admin %s has been removed. %s has been promoted as the new faction admin.", oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName()); + P.p.log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); + } + } + + + //----------------------------------------------// + // Messages + //----------------------------------------------// + public void msg(String message, Object... args) { + message = P.p.txt.parse(message, args); + + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void sendMessage(String message) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void sendMessage(List messages) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(messages); + } + } + + //----------------------------------------------// + // Ownership of specific claims + //----------------------------------------------// + + public void clearAllClaimOwnership() { + claimOwnership.clear(); + } + + public void clearClaimOwnership(FLocation loc) { + if (Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) { + LWCFeatures.clearAllChests(loc); + } + claimOwnership.remove(loc); + } + + public void clearClaimOwnership(String playerName) { + if (playerName == null || playerName.isEmpty()) { + return; + } + + Set ownerData; + String player = playerName.toLowerCase(); + + for (Entry> entry : claimOwnership.entrySet()) { + ownerData = entry.getValue(); + + if (ownerData == null) continue; + + Iterator iter = ownerData.iterator(); + while (iter.hasNext()) { + if (iter.next().equals(player)) { + iter.remove(); + } + } + + if (ownerData.isEmpty()) { + if (Conf.onUnclaimResetLwcLocks && LWCFeatures.getEnabled()) { + LWCFeatures.clearAllChests(entry.getKey()); + } + claimOwnership.remove(entry.getKey()); + } + } + } + + public int getCountOfClaimsWithOwners() { + return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); + } + + public boolean doesLocationHaveOwnersSet(FLocation loc) { + if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { + return false; + } + + Set ownerData = claimOwnership.get(loc); + return ownerData != null && !ownerData.isEmpty(); + } + + public boolean isPlayerInOwnerList(String playerName, FLocation loc) { + if (claimOwnership.isEmpty()) { + return false; + } + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + return false; + } + if (ownerData.contains(playerName.toLowerCase())) { + return true; + } + + return false; + } + + public void setPlayerAsOwner(String playerName, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + ownerData = new HashSet(); + } + ownerData.add(playerName.toLowerCase()); + claimOwnership.put(loc, ownerData); + } + + public void removePlayerAsOwner(String playerName, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + return; + } + ownerData.remove(playerName.toLowerCase()); + claimOwnership.put(loc, ownerData); + } + + public Set getOwnerList(FLocation loc) { + return claimOwnership.get(loc); + } + + public String getOwnerListString(FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null || ownerData.isEmpty()) { + return ""; + } + + String ownerList = ""; + + Iterator iter = ownerData.iterator(); + while (iter.hasNext()) { + if (!ownerList.isEmpty()) { + ownerList += ", "; + } + ownerList += iter.next(); + } + return ownerList; + } + + public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { + // in own faction, with sufficient role or permission to bypass ownership? + if + ( + fplayer.getFaction() == this + && + ( + fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.ADMIN) + || + Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()) + ) + ) { + return true; + } + + // make sure claimOwnership is initialized + if (claimOwnership.isEmpty()) + return true; + + // need to check the ownership list, then + Set ownerData = claimOwnership.get(loc); + + // if no owner list, owner list is empty, or player is in owner list, they're allowed + if (ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getName().toLowerCase())) + return true; + + return false; + } + + + //----------------------------------------------// + // Persistance and entity management + //----------------------------------------------// + + + @Override + public void postDetach() { + if (Econ.shouldBeUsed()) { + Econ.setBalance(getAccountId(), 0); + } + + // Clean the board + Board.clean(); + + // Clean the fplayers + FPlayers.i.clean(); + } } diff --git a/src/main/java/com/massivecraft/factions/Factions.java b/src/main/java/com/massivecraft/factions/Factions.java index 7fb9ea03..4a6ac175 100644 --- a/src/main/java/com/massivecraft/factions/Factions.java +++ b/src/main/java/com/massivecraft/factions/Factions.java @@ -1,189 +1,163 @@ package com.massivecraft.factions; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.zcore.persist.EntityCollection; +import com.massivecraft.factions.zcore.util.TextUtil; +import org.bukkit.ChatColor; +import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; + import java.io.File; import java.lang.reflect.Type; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; -import org.bukkit.ChatColor; +public class Factions extends EntityCollection { + public static Factions i = new Factions(); -import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; -import com.massivecraft.factions.util.MiscUtil; -import com.massivecraft.factions.zcore.persist.EntityCollection; -import com.massivecraft.factions.zcore.util.TextUtil; + P p = P.p; -public class Factions extends EntityCollection -{ - public static Factions i = new Factions(); - - P p = P.p; - - private Factions() - { - super - ( - Faction.class, - new CopyOnWriteArrayList(), - new ConcurrentHashMap(), - new File(P.p.getDataFolder(), "factions.json"), - P.p.gson - ); - } - - @Override - public Type getMapType() - { - return new TypeToken>(){}.getType(); - } - - @Override - public boolean loadFromDisc() - { - if ( ! super.loadFromDisc()) return false; - - // Make sure the default neutral faction exists - if ( ! this.exists("0")) - { - Faction faction = this.create("0"); - faction.setTag(ChatColor.DARK_GREEN+"Wilderness"); - faction.setDescription(""); - } - - // Make sure the safe zone faction exists - if ( ! this.exists("-1")) - { - Faction faction = this.create("-1"); - faction.setTag("SafeZone"); - faction.setDescription("Free from PVP and monsters"); - } - else - { - // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " - Faction faction = this.getSafeZone(); - if (faction.getTag().contains(" ")) - faction.setTag("SafeZone"); - } - - // Make sure the war zone faction exists - if ( ! this.exists("-2")) - { - Faction faction = this.create("-2"); - faction.setTag("WarZone"); - faction.setDescription("Not the safest place to be"); - } - else - { - // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " - Faction faction = this.getWarZone(); - if (faction.getTag().contains(" ")) - faction.setTag("WarZone"); - } + private Factions() { + super + ( + Faction.class, + new CopyOnWriteArrayList(), + new ConcurrentHashMap(), + new File(P.p.getDataFolder(), "factions.json"), + P.p.gson + ); + } - // populate all faction player lists - for (Faction faction : i.get()) - { - faction.refreshFPlayers(); - } + @Override + public Type getMapType() { + return new TypeToken>() { + }.getType(); + } - return true; - } - - - //----------------------------------------------// - // GET - //----------------------------------------------// - - @Override - public Faction get(String id) - { - if ( ! this.exists(id)) - { - p.log(Level.WARNING, "Non existing factionId "+id+" requested! Issuing cleaning!"); - Board.clean(); - FPlayers.i.clean(); - } - - return super.get(id); - } - - public Faction getNone() - { - return this.get("0"); - } - - public Faction getSafeZone() - { - return this.get("-1"); - } - - public Faction getWarZone() - { - return this.get("-2"); - } - - - //----------------------------------------------// - // Faction tag - //----------------------------------------------// - - public static ArrayList validateTag(String str) - { - ArrayList errors = new ArrayList(); - - if(MiscUtil.getComparisonString(str).length() < Conf.factionTagLengthMin) - { - errors.add(P.p.txt.parse("The faction tag can't be shorter than %s chars.", Conf.factionTagLengthMin)); - } - - if(str.length() > Conf.factionTagLengthMax) - { - errors.add(P.p.txt.parse("The faction tag can't be longer than %s chars.", Conf.factionTagLengthMax)); - } - - for (char c : str.toCharArray()) - { - if ( ! MiscUtil.substanceChars.contains(String.valueOf(c))) - { - errors.add(P.p.txt.parse("Faction tag must be alphanumeric. \"%s\" is not allowed.", c)); - } - } - - return errors; - } - - public Faction getByTag(String str) - { - String compStr = MiscUtil.getComparisonString(str); - for (Faction faction : this.get()) - { - if (faction.getComparisonTag().equals(compStr)) - { - return faction; - } - } - return null; - } - - public Faction getBestTagMatch(String searchFor) - { - Map tag2faction = new HashMap(); - - // TODO: Slow index building - for (Faction faction : this.get()) - { - tag2faction.put(ChatColor.stripColor(faction.getTag()), faction); - } - - String tag = TextUtil.getBestStartWithCI(tag2faction.keySet(), searchFor); - if (tag == null) return null; - return tag2faction.get(tag); - } - - public boolean isTagTaken(String str) - { - return this.getByTag(str) != null; - } + @Override + public boolean loadFromDisc() { + if (!super.loadFromDisc()) return false; + + // Make sure the default neutral faction exists + if (!this.exists("0")) { + Faction faction = this.create("0"); + faction.setTag(ChatColor.DARK_GREEN + "Wilderness"); + faction.setDescription(""); + } + + // Make sure the safe zone faction exists + if (!this.exists("-1")) { + Faction faction = this.create("-1"); + faction.setTag("SafeZone"); + faction.setDescription("Free from PVP and monsters"); + } else { + // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " + Faction faction = this.getSafeZone(); + if (faction.getTag().contains(" ")) + faction.setTag("SafeZone"); + } + + // Make sure the war zone faction exists + if (!this.exists("-2")) { + Faction faction = this.create("-2"); + faction.setTag("WarZone"); + faction.setDescription("Not the safest place to be"); + } else { + // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " + Faction faction = this.getWarZone(); + if (faction.getTag().contains(" ")) + faction.setTag("WarZone"); + } + + // populate all faction player lists + for (Faction faction : i.get()) { + faction.refreshFPlayers(); + } + + return true; + } + + + //----------------------------------------------// + // GET + //----------------------------------------------// + + @Override + public Faction get(String id) { + if (!this.exists(id)) { + p.log(Level.WARNING, "Non existing factionId " + id + " requested! Issuing cleaning!"); + Board.clean(); + FPlayers.i.clean(); + } + + return super.get(id); + } + + public Faction getNone() { + return this.get("0"); + } + + public Faction getSafeZone() { + return this.get("-1"); + } + + public Faction getWarZone() { + return this.get("-2"); + } + + + //----------------------------------------------// + // Faction tag + //----------------------------------------------// + + public static ArrayList validateTag(String str) { + ArrayList errors = new ArrayList(); + + if (MiscUtil.getComparisonString(str).length() < Conf.factionTagLengthMin) { + errors.add(P.p.txt.parse("The faction tag can't be shorter than %s chars.", Conf.factionTagLengthMin)); + } + + if (str.length() > Conf.factionTagLengthMax) { + errors.add(P.p.txt.parse("The faction tag can't be longer than %s chars.", Conf.factionTagLengthMax)); + } + + for (char c : str.toCharArray()) { + if (!MiscUtil.substanceChars.contains(String.valueOf(c))) { + errors.add(P.p.txt.parse("Faction tag must be alphanumeric. \"%s\" is not allowed.", c)); + } + } + + return errors; + } + + public Faction getByTag(String str) { + String compStr = MiscUtil.getComparisonString(str); + for (Faction faction : this.get()) { + if (faction.getComparisonTag().equals(compStr)) { + return faction; + } + } + return null; + } + + public Faction getBestTagMatch(String searchFor) { + Map tag2faction = new HashMap(); + + // TODO: Slow index building + for (Faction faction : this.get()) { + tag2faction.put(ChatColor.stripColor(faction.getTag()), faction); + } + + String tag = TextUtil.getBestStartWithCI(tag2faction.keySet(), searchFor); + if (tag == null) return null; + return tag2faction.get(tag); + } + + public boolean isTagTaken(String str) { + return this.getByTag(str) != null; + } } diff --git a/src/main/java/com/massivecraft/factions/P.java b/src/main/java/com/massivecraft/factions/P.java index 523b10c5..1bbabdaf 100644 --- a/src/main/java/com/massivecraft/factions/P.java +++ b/src/main/java/com/massivecraft/factions/P.java @@ -1,34 +1,10 @@ package com.massivecraft.factions; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.bukkit.block.Block; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.Location; -import org.bukkit.Material; - import com.massivecraft.factions.cmd.CmdAutoHelp; import com.massivecraft.factions.cmd.FCmdRoot; -import com.massivecraft.factions.integration.Econ; -import com.massivecraft.factions.integration.EssentialsFeatures; -import com.massivecraft.factions.integration.LWCFeatures; -import com.massivecraft.factions.integration.SpoutFeatures; -import com.massivecraft.factions.integration.Worldguard; +import com.massivecraft.factions.integration.*; import com.massivecraft.factions.integration.capi.CapiFeatures; -import com.massivecraft.factions.listeners.FactionsBlockListener; -import com.massivecraft.factions.listeners.FactionsChatListener; -import com.massivecraft.factions.listeners.FactionsEntityListener; -import com.massivecraft.factions.listeners.FactionsExploitListener; -import com.massivecraft.factions.listeners.FactionsPlayerListener; -import com.massivecraft.factions.listeners.FactionsServerListener; +import com.massivecraft.factions.listeners.*; import com.massivecraft.factions.struct.ChatMode; import com.massivecraft.factions.util.AutoLeaveTask; import com.massivecraft.factions.util.LazyLocation; @@ -36,334 +12,319 @@ import com.massivecraft.factions.util.MapFLocToStringSetTypeAdapter; import com.massivecraft.factions.util.MyLocationTypeAdapter; import com.massivecraft.factions.zcore.MPlugin; import com.massivecraft.factions.zcore.util.TextUtil; - -import java.util.logging.Level; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder; import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; +import org.bukkit.entity.Player; +import org.bukkit.event.player.AsyncPlayerChatEvent; + +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; -public class P extends MPlugin -{ - // Our single plugin instance - public static P p; - - // Listeners - public final FactionsPlayerListener playerListener; - public final FactionsChatListener chatListener; - public final FactionsEntityListener entityListener; - public final FactionsExploitListener exploitListener; - public final FactionsBlockListener blockListener; - public final FactionsServerListener serverListener; - - // Persistance related - private boolean locked = false; - public boolean getLocked() {return this.locked;} - public void setLocked(boolean val) {this.locked = val; this.setAutoSave(val);} - private Integer AutoLeaveTask = null; - - // Commands - public FCmdRoot cmdBase; - public CmdAutoHelp cmdAutoHelp; - - public P() - { - p = this; - this.playerListener = new FactionsPlayerListener(this); - this.chatListener = new FactionsChatListener(this); - this.entityListener = new FactionsEntityListener(this); - this.exploitListener = new FactionsExploitListener(); - this.blockListener = new FactionsBlockListener(this); - this.serverListener = new FactionsServerListener(this); - } +public class P extends MPlugin { + // Our single plugin instance + public static P p; + + // Listeners + public final FactionsPlayerListener playerListener; + public final FactionsChatListener chatListener; + public final FactionsEntityListener entityListener; + public final FactionsExploitListener exploitListener; + public final FactionsBlockListener blockListener; + public final FactionsServerListener serverListener; + + // Persistance related + private boolean locked = false; + + public boolean getLocked() { + return this.locked; + } + + public void setLocked(boolean val) { + this.locked = val; + this.setAutoSave(val); + } + + private Integer AutoLeaveTask = null; + + // Commands + public FCmdRoot cmdBase; + public CmdAutoHelp cmdAutoHelp; + + public P() { + p = this; + this.playerListener = new FactionsPlayerListener(this); + this.chatListener = new FactionsChatListener(this); + this.entityListener = new FactionsEntityListener(this); + this.exploitListener = new FactionsExploitListener(); + this.blockListener = new FactionsBlockListener(this); + this.serverListener = new FactionsServerListener(this); + } - @Override - public void onEnable() - { - // bit of (apparently absolutely necessary) idiot-proofing for CB version support due to changed GSON lib package name - try - { - Class.forName("org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken"); - } - catch (ClassNotFoundException ex) - { - this.log(Level.SEVERE, "GSON lib not found. Your CraftBukkit build is too old (< 1.3.2) or otherwise not compatible."); - this.suicide(); - return; - } + @Override + public void onEnable() { + // bit of (apparently absolutely necessary) idiot-proofing for CB version support due to changed GSON lib package name + try { + Class.forName("org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken"); + } catch (ClassNotFoundException ex) { + this.log(Level.SEVERE, "GSON lib not found. Your CraftBukkit build is too old (< 1.3.2) or otherwise not compatible."); + this.suicide(); + return; + } - if ( ! preEnable()) return; - this.loadSuccessful = false; + if (!preEnable()) return; + this.loadSuccessful = false; - // Load Conf from disk - Conf.load(); - FPlayers.i.loadFromDisc(); - Factions.i.loadFromDisc(); - Board.load(); - - // Add Base Commands - this.cmdBase = new FCmdRoot(); - this.cmdAutoHelp = new CmdAutoHelp(); - this.getBaseCommands().add(cmdBase); + // Load Conf from disk + Conf.load(); + FPlayers.i.loadFromDisc(); + Factions.i.loadFromDisc(); + Board.load(); - EssentialsFeatures.setup(); - SpoutFeatures.setup(); - Econ.setup(); - CapiFeatures.setup(); - LWCFeatures.setup(); + // Add Base Commands + this.cmdBase = new FCmdRoot(); + this.cmdAutoHelp = new CmdAutoHelp(); + this.getBaseCommands().add(cmdBase); - if(Conf.worldGuardChecking || Conf.worldGuardBuildPriority) - { - Worldguard.init(this); - } + EssentialsFeatures.setup(); + SpoutFeatures.setup(); + Econ.setup(); + CapiFeatures.setup(); + LWCFeatures.setup(); - // start up task which runs the autoLeaveAfterDaysOfInactivity routine - startAutoLeaveTask(false); + if (Conf.worldGuardChecking || Conf.worldGuardBuildPriority) { + Worldguard.init(this); + } - // Register Event Handlers - getServer().getPluginManager().registerEvents(playerListener, this); - getServer().getPluginManager().registerEvents(chatListener, this); - getServer().getPluginManager().registerEvents(entityListener, this); - getServer().getPluginManager().registerEvents(exploitListener, this); - getServer().getPluginManager().registerEvents(blockListener, this); - getServer().getPluginManager().registerEvents(serverListener, this); + // start up task which runs the autoLeaveAfterDaysOfInactivity routine + startAutoLeaveTask(false); - // since some other plugins execute commands directly through this command interface, provide it - this.getCommand(this.refCommand).setExecutor(this); + // Register Event Handlers + getServer().getPluginManager().registerEvents(playerListener, this); + getServer().getPluginManager().registerEvents(chatListener, this); + getServer().getPluginManager().registerEvents(entityListener, this); + getServer().getPluginManager().registerEvents(exploitListener, this); + getServer().getPluginManager().registerEvents(blockListener, this); + getServer().getPluginManager().registerEvents(serverListener, this); - postEnable(); - this.loadSuccessful = true; - } - - @Override - public GsonBuilder getGsonBuilder() - { - Type mapFLocToStringSetType = new TypeToken>>(){}.getType(); + // since some other plugins execute commands directly through this command interface, provide it + this.getCommand(this.refCommand).setExecutor(this); - return new GsonBuilder() - .setPrettyPrinting() - .disableHtmlEscaping() - .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) - .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) - .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()); - } + postEnable(); + this.loadSuccessful = true; + } - @Override - public void onDisable() - { - // only save data if plugin actually completely loaded successfully - if (this.loadSuccessful) - { - Board.save(); - Conf.save(); - } - EssentialsFeatures.unhookChat(); - if (AutoLeaveTask != null) - { - this.getServer().getScheduler().cancelTask(AutoLeaveTask); - AutoLeaveTask = null; - } - super.onDisable(); - } + @Override + public GsonBuilder getGsonBuilder() { + Type mapFLocToStringSetType = new TypeToken>>() { + }.getType(); - public void startAutoLeaveTask(boolean restartIfRunning) - { - if (AutoLeaveTask != null) - { - if ( ! restartIfRunning) return; - this.getServer().getScheduler().cancelTask(AutoLeaveTask); - } + return new GsonBuilder() + .setPrettyPrinting() + .disableHtmlEscaping() + .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) + .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) + .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()); + } - if (Conf.autoLeaveRoutineRunsEveryXMinutes > 0.0) - { - long ticks = (long)(20 * 60 * Conf.autoLeaveRoutineRunsEveryXMinutes); - AutoLeaveTask = getServer().getScheduler().scheduleSyncRepeatingTask(this, new AutoLeaveTask(), ticks, ticks); - } - } + @Override + public void onDisable() { + // only save data if plugin actually completely loaded successfully + if (this.loadSuccessful) { + Board.save(); + Conf.save(); + } + EssentialsFeatures.unhookChat(); + if (AutoLeaveTask != null) { + this.getServer().getScheduler().cancelTask(AutoLeaveTask); + AutoLeaveTask = null; + } + super.onDisable(); + } - @Override - public void postAutoSave() - { - Board.save(); - Conf.save(); - } + public void startAutoLeaveTask(boolean restartIfRunning) { + if (AutoLeaveTask != null) { + if (!restartIfRunning) return; + this.getServer().getScheduler().cancelTask(AutoLeaveTask); + } - @Override - public boolean logPlayerCommands() - { - return Conf.logPlayerCommands; - } + if (Conf.autoLeaveRoutineRunsEveryXMinutes > 0.0) { + long ticks = (long) (20 * 60 * Conf.autoLeaveRoutineRunsEveryXMinutes); + AutoLeaveTask = getServer().getScheduler().scheduleSyncRepeatingTask(this, new AutoLeaveTask(), ticks, ticks); + } + } - @Override - public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) - { - if (sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player)sender)) return true; + @Override + public void postAutoSave() { + Board.save(); + Conf.save(); + } - return super.handleCommand(sender, commandString, testOnly); - } + @Override + public boolean logPlayerCommands() { + return Conf.logPlayerCommands; + } - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] split) - { - // if bare command at this point, it has already been handled by MPlugin's command listeners - if (split == null || split.length == 0) return true; + @Override + public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { + if (sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender)) + return true; - // otherwise, needs to be handled; presumably another plugin directly ran the command - String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); - return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false); - } + return super.handleCommand(sender, commandString, testOnly); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { + // if bare command at this point, it has already been handled by MPlugin's command listeners + if (split == null || split.length == 0) return true; + + // otherwise, needs to be handled; presumably another plugin directly ran the command + String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); + return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false); + } + // -------------------------------------------- // + // Functions for other plugins to hook into + // -------------------------------------------- // - // -------------------------------------------- // - // Functions for other plugins to hook into - // -------------------------------------------- // + // This value will be updated whenever new hooks are added + public int hookSupportVersion() { + return 3; + } - // This value will be updated whenever new hooks are added - public int hookSupportVersion() - { - return 3; - } + // If another plugin is handling insertion of chat tags, this should be used to notify Factions + public void handleFactionTagExternally(boolean notByFactions) { + Conf.chatTagHandledByAnotherPlugin = notByFactions; + } - // If another plugin is handling insertion of chat tags, this should be used to notify Factions - public void handleFactionTagExternally(boolean notByFactions) - { - Conf.chatTagHandledByAnotherPlugin = notByFactions; - } + // Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat + // enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand() - // Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat - // enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand() - - public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) - { - if (event == null) return false; - return (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); - } + public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { + if (event == null) return false; + return (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); + } - // Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels, - // local chat, or anything else which targets individual recipients, so Faction Chat can be done - public boolean isPlayerFactionChatting(Player player) - { - if (player == null) return false; - FPlayer me = FPlayers.i.get(player); - - if (me == null)return false; - return me.getChatMode().isAtLeast(ChatMode.ALLIANCE); - } + // Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels, + // local chat, or anything else which targets individual recipients, so Faction Chat can be done + public boolean isPlayerFactionChatting(Player player) { + if (player == null) return false; + FPlayer me = FPlayers.i.get(player); - // Is this chat message actually a Factions command, and thus should be left alone by other plugins? - - // TODO: GET THIS BACK AND WORKING - - public boolean isFactionsCommand(String check) - { - if (check == null || check.isEmpty()) return false; - return this.handleCommand(null, check, true); - } + if (me == null) return false; + return me.getChatMode().isAtLeast(ChatMode.ALLIANCE); + } - // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat - public String getPlayerFactionTag(Player player) - { - return getPlayerFactionTagRelation(player, null); - } + // Is this chat message actually a Factions command, and thus should be left alone by other plugins? - // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag - public String getPlayerFactionTagRelation(Player speaker, Player listener) - { - String tag = "~"; + // TODO: GET THIS BACK AND WORKING - if (speaker == null) - return tag; + public boolean isFactionsCommand(String check) { + if (check == null || check.isEmpty()) return false; + return this.handleCommand(null, check, true); + } - FPlayer me = FPlayers.i.get(speaker); - if (me == null) - return tag; + // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat + public String getPlayerFactionTag(Player player) { + return getPlayerFactionTagRelation(player, null); + } - // if listener isn't set, or config option is disabled, give back uncolored tag - if (listener == null || !Conf.chatTagRelationColored) { - tag = me.getChatTag().trim(); - } else { - FPlayer you = FPlayers.i.get(listener); - if (you == null) - tag = me.getChatTag().trim(); - else // everything checks out, give the colored tag - tag = me.getChatTag(you).trim(); - } - if (tag.isEmpty()) - tag = "~"; + // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag + public String getPlayerFactionTagRelation(Player speaker, Player listener) { + String tag = "~"; - return tag; - } + if (speaker == null) + return tag; - // Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat - public String getPlayerTitle(Player player) - { - if (player == null) - return ""; + FPlayer me = FPlayers.i.get(speaker); + if (me == null) + return tag; - FPlayer me = FPlayers.i.get(player); - if (me == null) - return ""; + // if listener isn't set, or config option is disabled, give back uncolored tag + if (listener == null || !Conf.chatTagRelationColored) { + tag = me.getChatTag().trim(); + } else { + FPlayer you = FPlayers.i.get(listener); + if (you == null) + tag = me.getChatTag().trim(); + else // everything checks out, give the colored tag + tag = me.getChatTag(you).trim(); + } + if (tag.isEmpty()) + tag = "~"; - return me.getTitle().trim(); - } + return tag; + } - // Get a list of all faction tags (names) - public Set getFactionTags() - { - Set tags = new HashSet(); - for (Faction faction : Factions.i.get()) - { - tags.add(faction.getTag()); - } - return tags; - } + // Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat + public String getPlayerTitle(Player player) { + if (player == null) + return ""; - // Get a list of all players in the specified faction - public Set getPlayersInFaction(String factionTag) - { - Set players = new HashSet(); - Faction faction = Factions.i.getByTag(factionTag); - if (faction != null) - { - for (FPlayer fplayer : faction.getFPlayers()) - { - players.add(fplayer.getName()); - } - } - return players; - } + FPlayer me = FPlayers.i.get(player); + if (me == null) + return ""; - // Get a list of all online players in the specified faction - public Set getOnlinePlayersInFaction(String factionTag) - { - Set players = new HashSet(); - Faction faction = Factions.i.getByTag(factionTag); - if (faction != null) - { - for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) - { - players.add(fplayer.getName()); - } - } - return players; - } + return me.getTitle().trim(); + } - // check if player is allowed to build/destroy in a particular location - public boolean isPlayerAllowedToBuildHere(Player player, Location location) - { - return FactionsBlockListener.playerCanBuildDestroyBlock(player, location, "", true); - } + // Get a list of all faction tags (names) + public Set getFactionTags() { + Set tags = new HashSet(); + for (Faction faction : Factions.i.get()) { + tags.add(faction.getTag()); + } + return tags; + } - // check if player is allowed to interact with the specified block (doors/chests/whatever) - public boolean isPlayerAllowedToInteractWith(Player player, Block block) - { - return FactionsPlayerListener.canPlayerUseBlock(player, block, true); - } + // Get a list of all players in the specified faction + public Set getPlayersInFaction(String factionTag) { + Set players = new HashSet(); + Faction faction = Factions.i.getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayers()) { + players.add(fplayer.getName()); + } + } + return players; + } - // check if player is allowed to use a specified item (flint&steel, buckets, etc) in a particular location - public boolean isPlayerAllowedToUseThisHere(Player player, Location location, Material material) - { - return FactionsPlayerListener.playerCanUseItemHere(player, location, material, true); - } + // Get a list of all online players in the specified faction + public Set getOnlinePlayersInFaction(String factionTag) { + Set players = new HashSet(); + Faction faction = Factions.i.getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) { + players.add(fplayer.getName()); + } + } + return players; + } + + // check if player is allowed to build/destroy in a particular location + public boolean isPlayerAllowedToBuildHere(Player player, Location location) { + return FactionsBlockListener.playerCanBuildDestroyBlock(player, location, "", true); + } + + // check if player is allowed to interact with the specified block (doors/chests/whatever) + public boolean isPlayerAllowedToInteractWith(Player player, Block block) { + return FactionsPlayerListener.canPlayerUseBlock(player, block, true); + } + + // check if player is allowed to use a specified item (flint&steel, buckets, etc) in a particular location + public boolean isPlayerAllowedToUseThisHere(Player player, Location location, Material material) { + return FactionsPlayerListener.playerCanUseItemHere(player, location, material, true); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java index 769a71c7..d184a6fa 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -1,90 +1,80 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - -import com.massivecraft.factions.Faction; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.event.FPlayerJoinEvent; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; -public class CmdAdmin extends FCommand -{ - public CmdAdmin() - { - super(); - this.aliases.add("admin"); - - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.ADMIN.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer fyou = this.argAsBestFPlayerMatch(0); - if (fyou == null) return; +public class CmdAdmin extends FCommand { + public CmdAdmin() { + super(); + this.aliases.add("admin"); - boolean permAny = Permission.ADMIN_ANY.has(sender, false); - Faction targetFaction = fyou.getFaction(); + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); - if (targetFaction != myFaction && !permAny) - { - msg("%s is not a member in your faction.", fyou.describeTo(fme, true)); - return; - } + this.permission = Permission.ADMIN.node; + this.disableOnLock = true; - if (fme != null && fme.getRole() != Role.ADMIN && !permAny) - { - msg("You are not the faction admin."); - return; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - if (fyou == fme && !permAny) - { - msg("The target player musn't be yourself."); - return; - } + @Override + public void perform() { + FPlayer fyou = this.argAsBestFPlayerMatch(0); + if (fyou == null) return; - // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction - if (fyou.getFaction() != targetFaction) - { - FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.i.get(me),targetFaction,FPlayerJoinEvent.PlayerJoinReason.LEADER); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) return; - } + boolean permAny = Permission.ADMIN_ANY.has(sender, false); + Faction targetFaction = fyou.getFaction(); - FPlayer admin = targetFaction.getFPlayerAdmin(); + if (targetFaction != myFaction && !permAny) { + msg("%s is not a member in your faction.", fyou.describeTo(fme, true)); + return; + } - // if target player is currently admin, demote and replace him - if (fyou == admin) - { - targetFaction.promoteNewLeader(); - msg("You have demoted %s from the position of faction admin.", fyou.describeTo(fme, true)); - fyou.msg("You have been demoted from the position of faction admin by %s.", senderIsConsole ? "a server admin" : fme.describeTo(fyou, true)); - return; - } + if (fme != null && fme.getRole() != Role.ADMIN && !permAny) { + msg("You are not the faction admin."); + return; + } - // promote target player, and demote existing admin if one exists - if (admin != null) - admin.setRole(Role.MODERATOR); - fyou.setRole(Role.ADMIN); - msg("You have promoted %s to the position of faction admin.", fyou.describeTo(fme, true)); + if (fyou == fme && !permAny) { + msg("The target player musn't be yourself."); + return; + } + + // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction + if (fyou.getFaction() != targetFaction) { + FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.i.get(me), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) return; + } + + FPlayer admin = targetFaction.getFPlayerAdmin(); + + // if target player is currently admin, demote and replace him + if (fyou == admin) { + targetFaction.promoteNewLeader(); + msg("You have demoted %s from the position of faction admin.", fyou.describeTo(fme, true)); + fyou.msg("You have been demoted from the position of faction admin by %s.", senderIsConsole ? "a server admin" : fme.describeTo(fyou, true)); + return; + } + + // promote target player, and demote existing admin if one exists + if (admin != null) + admin.setRole(Role.MODERATOR); + fyou.setRole(Role.ADMIN); + msg("You have promoted %s to the position of faction admin.", fyou.describeTo(fme, true)); + + // Inform all players + for (FPlayer fplayer : FPlayers.i.getOnline()) { + fplayer.msg("%s gave %s the leadership of %s.", senderIsConsole ? "A server admin" : fme.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); + } + } - // Inform all players - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - fplayer.msg("%s gave %s the leadership of %s.", senderIsConsole ? "A server admin" : fme.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java index a8bdd40a..e192d83f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java @@ -4,50 +4,45 @@ import com.massivecraft.factions.Faction; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; -public class CmdAutoClaim extends FCommand -{ - public CmdAutoClaim() - { - super(); - this.aliases.add("autoclaim"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "your"); - - this.permission = Permission.AUTOCLAIM.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } +public class CmdAutoClaim extends FCommand { + public CmdAutoClaim() { + super(); + this.aliases.add("autoclaim"); - @Override - public void perform() - { - Faction forFaction = this.argAsFaction(0, myFaction); - if (forFaction == null || forFaction == fme.getAutoClaimFor()) - { - fme.setAutoClaimFor(null); - msg("Auto-claiming of land disabled."); - return; - } + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "your"); - if (! fme.canClaimForFaction(forFaction)) - { - if (myFaction == forFaction) - msg("You must be %s to claim land.", Role.MODERATOR.toString()); - else - msg("You can't claim land for %s.", forFaction.describeTo(fme)); + this.permission = Permission.AUTOCLAIM.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction forFaction = this.argAsFaction(0, myFaction); + if (forFaction == null || forFaction == fme.getAutoClaimFor()) { + fme.setAutoClaimFor(null); + msg("Auto-claiming of land disabled."); + return; + } + + if (!fme.canClaimForFaction(forFaction)) { + if (myFaction == forFaction) + msg("You must be %s to claim land.", Role.MODERATOR.toString()); + else + msg("You can't claim land for %s.", forFaction.describeTo(fme)); + + return; + } + + fme.setAutoClaimFor(forFaction); + + msg("Now auto-claiming land for %s.", forFaction.describeTo(fme)); + fme.attemptClaim(forFaction, me.getLocation(), true); + } - return; - } - - fme.setAutoClaimFor(forFaction); - - msg("Now auto-claiming land for %s.", forFaction.describeTo(fme)); - fme.attemptClaim(forFaction, me.getLocation(), true); - } - } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java index 193a5cad..16be3fc2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java @@ -1,48 +1,43 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; - import com.massivecraft.factions.P; import com.massivecraft.factions.zcore.CommandVisibility; import com.massivecraft.factions.zcore.MCommand; -public class CmdAutoHelp extends MCommand

-{ - public CmdAutoHelp() - { - super(P.p); - this.aliases.add("?"); - this.aliases.add("h"); - this.aliases.add("help"); - - this.setHelpShort(""); - - this.optionalArgs.put("page","1"); - } - - @Override - public void perform() - { - if (this.commandChain.size() == 0) return; - MCommand pcmd = this.commandChain.get(this.commandChain.size()-1); - - ArrayList lines = new ArrayList(); - - lines.addAll(pcmd.helpLong); - - for(MCommand scmd : pcmd.subCommands) - { - if - ( - scmd.visibility == CommandVisibility.VISIBLE - || - (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false)) - ) - { - lines.add(scmd.getUseageTemplate(this.commandChain, true)); - } - } - - sendMessage(p.txt.getPage(lines, this.argAsInt(0, 1), "Help for command \""+pcmd.aliases.get(0)+"\"")); - } +import java.util.ArrayList; + +public class CmdAutoHelp extends MCommand

{ + public CmdAutoHelp() { + super(P.p); + this.aliases.add("?"); + this.aliases.add("h"); + this.aliases.add("help"); + + this.setHelpShort(""); + + this.optionalArgs.put("page", "1"); + } + + @Override + public void perform() { + if (this.commandChain.size() == 0) return; + MCommand pcmd = this.commandChain.get(this.commandChain.size() - 1); + + ArrayList lines = new ArrayList(); + + lines.addAll(pcmd.helpLong); + + for (MCommand scmd : pcmd.subCommands) { + if + ( + scmd.visibility == CommandVisibility.VISIBLE + || + (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false)) + ) { + lines.add(scmd.getUseageTemplate(this.commandChain, true)); + } + } + + sendMessage(p.txt.getPage(lines, this.argAsInt(0, 1), "Help for command \"" + pcmd.aliases.get(0) + "\"")); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java index 7c54ea7f..60cdd571 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java @@ -3,42 +3,38 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; import com.massivecraft.factions.struct.Permission; -public class CmdBoom extends FCommand -{ - public CmdBoom() - { - super(); - this.aliases.add("noboom"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); - - this.permission = Permission.NO_BOOM.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } +public class CmdBoom extends FCommand { + public CmdBoom() { + super(); + this.aliases.add("noboom"); - @Override - public void perform() - { - if ( ! myFaction.isPeaceful()) - { - fme.msg("This command is only usable by factions which are specially designated as peaceful."); - return; - } + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostNoBoom, "to toggle explosions", "for toggling explosions")) return; + this.permission = Permission.NO_BOOM.node; + this.disableOnLock = true; - myFaction.setPeacefulExplosionsEnabled(this.argAsBool(0, ! myFaction.getPeacefulExplosionsEnabled())); + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } - String enabled = myFaction.noExplosionsInTerritory() ? "disabled" : "enabled"; + @Override + public void perform() { + if (!myFaction.isPeaceful()) { + fme.msg("This command is only usable by factions which are specially designated as peaceful."); + return; + } - // Inform - myFaction.msg("%s has "+enabled+" explosions in your faction's territory.", fme.describeTo(myFaction)); - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostNoBoom, "to toggle explosions", "for toggling explosions")) return; + + myFaction.setPeacefulExplosionsEnabled(this.argAsBool(0, !myFaction.getPeacefulExplosionsEnabled())); + + String enabled = myFaction.noExplosionsInTerritory() ? "disabled" : "enabled"; + + // Inform + myFaction.msg("%s has " + enabled + " explosions in your faction's territory.", fme.describeTo(myFaction)); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java index 5e626d60..1955501f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java @@ -3,40 +3,34 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdBypass extends FCommand -{ - public CmdBypass() - { - super(); - this.aliases.add("bypass"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); - - this.permission = Permission.BYPASS.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - fme.setIsAdminBypassing(this.argAsBool(0, ! fme.isAdminBypassing())); - - // TODO: Move this to a transient field in the model?? - if ( fme.isAdminBypassing()) - { - fme.msg("You have enabled admin bypass mode. You will be able to build or destroy anywhere."); - P.p.log(fme.getName() + " has ENABLED admin bypass mode."); - } - else - { - fme.msg("You have disabled admin bypass mode."); - P.p.log(fme.getName() + " DISABLED admin bypass mode."); - } - } +public class CmdBypass extends FCommand { + public CmdBypass() { + super(); + this.aliases.add("bypass"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); + + this.permission = Permission.BYPASS.node; + this.disableOnLock = false; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + fme.setIsAdminBypassing(this.argAsBool(0, !fme.isAdminBypassing())); + + // TODO: Move this to a transient field in the model?? + if (fme.isAdminBypassing()) { + fme.msg("You have enabled admin bypass mode. You will be able to build or destroy anywhere."); + P.p.log(fme.getName() + " has ENABLED admin bypass mode."); + } else { + fme.msg("You have disabled admin bypass mode."); + P.p.log(fme.getName() + " DISABLED admin bypass mode."); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java index 645fb26e..637d21b4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java @@ -4,74 +4,57 @@ import com.massivecraft.factions.Conf; import com.massivecraft.factions.struct.ChatMode; import com.massivecraft.factions.struct.Permission; -public class CmdChat extends FCommand -{ - - public CmdChat() - { - super(); - this.aliases.add("c"); - this.aliases.add("chat"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("mode", "next"); - - this.permission = Permission.CHAT.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - if ( ! Conf.factionOnlyChat ) - { - msg("The built in chat chat channels are disabled on this server."); - return; - } - - String modeString = this.argAsString(0); - ChatMode modeTarget = fme.getChatMode().getNext(); - - if (modeString != null) - { - modeString.toLowerCase(); - if(modeString.startsWith("p")) - { - modeTarget = ChatMode.PUBLIC; - } - else if (modeString.startsWith("a")) - { - modeTarget = ChatMode.ALLIANCE; - } - else if(modeString.startsWith("f")) - { - modeTarget = ChatMode.FACTION; - } - else - { - msg("Unrecognised chat mode. Please enter either 'a','f' or 'p'"); - return; - } - } - - fme.setChatMode(modeTarget); - - if(fme.getChatMode() == ChatMode.PUBLIC) - { - msg("Public chat mode."); - } - else if (fme.getChatMode() == ChatMode.ALLIANCE ) - { - msg("Alliance only chat mode."); - } - else - { - msg("Faction only chat mode."); - } - } +public class CmdChat extends FCommand { + + public CmdChat() { + super(); + this.aliases.add("c"); + this.aliases.add("chat"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("mode", "next"); + + this.permission = Permission.CHAT.node; + this.disableOnLock = false; + + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + if (!Conf.factionOnlyChat) { + msg("The built in chat chat channels are disabled on this server."); + return; + } + + String modeString = this.argAsString(0); + ChatMode modeTarget = fme.getChatMode().getNext(); + + if (modeString != null) { + modeString.toLowerCase(); + if (modeString.startsWith("p")) { + modeTarget = ChatMode.PUBLIC; + } else if (modeString.startsWith("a")) { + modeTarget = ChatMode.ALLIANCE; + } else if (modeString.startsWith("f")) { + modeTarget = ChatMode.FACTION; + } else { + msg("Unrecognised chat mode. Please enter either 'a','f' or 'p'"); + return; + } + } + + fme.setChatMode(modeTarget); + + if (fme.getChatMode() == ChatMode.PUBLIC) { + msg("Public chat mode."); + } else if (fme.getChatMode() == ChatMode.ALLIANCE) { + msg("Alliance only chat mode."); + } else { + msg("Faction only chat mode."); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java index b05c1aa7..2c1f8dc8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java @@ -3,38 +3,32 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdChatSpy extends FCommand -{ - public CmdChatSpy() - { - super(); - this.aliases.add("chatspy"); +public class CmdChatSpy extends FCommand { + public CmdChatSpy() { + super(); + this.aliases.add("chatspy"); - this.optionalArgs.put("on/off", "flip"); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.CHATSPY.node; - this.disableOnLock = false; + this.permission = Permission.CHATSPY.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() - { - fme.setSpyingChat(this.argAsBool(0, ! fme.isSpyingChat())); + @Override + public void perform() { + fme.setSpyingChat(this.argAsBool(0, !fme.isSpyingChat())); - if ( fme.isSpyingChat()) - { - fme.msg("You have enabled chat spying mode."); - P.p.log(fme.getName() + " has ENABLED chat spying mode."); - } - else - { - fme.msg("You have disabled chat spying mode."); - P.p.log(fme.getName() + " DISABLED chat spying mode."); - } - } + if (fme.isSpyingChat()) { + fme.msg("You have enabled chat spying mode."); + P.p.log(fme.getName() + " has ENABLED chat spying mode."); + } else { + fme.msg("You have disabled chat spying mode."); + P.p.log(fme.getName() + " DISABLED chat spying mode."); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java index 0faa068a..14112681 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java @@ -1,81 +1,70 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; -import com.massivecraft.factions.Faction; import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.util.SpiralTask; -public class CmdClaim extends FCommand -{ - - public CmdClaim() - { - super(); - this.aliases.add("claim"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "your"); - this.optionalArgs.put("radius", "1"); - - this.permission = Permission.CLAIM.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - // Read and validate input - final Faction forFaction = this.argAsFaction(0, myFaction); - int radius = this.argAsInt(1, 1); +public class CmdClaim extends FCommand { - if (radius < 1) - { - msg("If you specify a radius, it must be at least 1."); - return; - } + public CmdClaim() { + super(); + this.aliases.add("claim"); - if (radius < 2) - { - // single chunk - fme.attemptClaim(forFaction, me.getLocation(), true); - } - else - { - // radius claim - if (! Permission.CLAIM_RADIUS.has(sender, false)) - { - msg("You do not have permission to claim in a radius."); - return; - } + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "your"); + this.optionalArgs.put("radius", "1"); - new SpiralTask(new FLocation(me), radius) - { - private int failCount = 0; - private final int limit = Conf.radiusClaimFailureLimit - 1; + this.permission = Permission.CLAIM.node; + this.disableOnLock = true; - @Override - public boolean work() - { - boolean success = fme.attemptClaim(forFaction, this.currentLocation(), true); - if (success) - failCount = 0; - else if ( ! success && failCount++ >= limit) - { - this.stop(); - return false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + // Read and validate input + final Faction forFaction = this.argAsFaction(0, myFaction); + int radius = this.argAsInt(1, 1); + + if (radius < 1) { + msg("If you specify a radius, it must be at least 1."); + return; + } + + if (radius < 2) { + // single chunk + fme.attemptClaim(forFaction, me.getLocation(), true); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(sender, false)) { + msg("You do not have permission to claim in a radius."); + return; + } + + new SpiralTask(new FLocation(me), radius) { + private int failCount = 0; + private final int limit = Conf.radiusClaimFailureLimit - 1; + + @Override + public boolean work() { + boolean success = fme.attemptClaim(forFaction, this.currentLocation(), true); + if (success) + failCount = 0; + else if (!success && failCount++ >= limit) { + this.stop(); + return false; + } + + return true; + } + }; + } + } - return true; - } - }; - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java index f3b0a032..8b5eb9ba 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java @@ -1,302 +1,245 @@ package com.massivecraft.factions.cmd; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Set; -import java.util.HashMap; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.P; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; -public class CmdConfig extends FCommand -{ - private static HashMap properFieldNames = new HashMap(); +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Set; - public CmdConfig() - { - super(); - this.aliases.add("config"); - - this.requiredArgs.add("setting"); - this.requiredArgs.add("value"); - this.errorOnToManyArgs = false; - - this.permission = Permission.CONFIG.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } +public class CmdConfig extends FCommand { + private static HashMap properFieldNames = new HashMap(); - @Override - public void perform() - { - // store a lookup map of lowercase field names paired with proper capitalization field names - // that way, if the person using this command messes up the capitalization, we can fix that - if (properFieldNames.isEmpty()) - { - Field[] fields = Conf.class.getDeclaredFields(); - for(int i = 0; i < fields.length; i++) - { - properFieldNames.put(fields[i].getName().toLowerCase(), fields[i].getName()); - } - } + public CmdConfig() { + super(); + this.aliases.add("config"); - String field = this.argAsString(0).toLowerCase(); - if (field.startsWith("\"") && field.endsWith("\"")) - { - field = field.substring(1, field.length() - 1); - } - String fieldName = properFieldNames.get(field); + this.requiredArgs.add("setting"); + this.requiredArgs.add("value"); + this.errorOnToManyArgs = false; - if (fieldName == null || fieldName.isEmpty()) - { - msg("No configuration setting \"%s\" exists.", field); - return; - } + this.permission = Permission.CONFIG.node; + this.disableOnLock = true; - String success = ""; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - String value = args.get(1); - for(int i = 2; i < args.size(); i++) - { - value += ' ' + args.get(i); - } + @Override + public void perform() { + // store a lookup map of lowercase field names paired with proper capitalization field names + // that way, if the person using this command messes up the capitalization, we can fix that + if (properFieldNames.isEmpty()) { + Field[] fields = Conf.class.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + properFieldNames.put(fields[i].getName().toLowerCase(), fields[i].getName()); + } + } - try - { - Field target = Conf.class.getField(fieldName); + String field = this.argAsString(0).toLowerCase(); + if (field.startsWith("\"") && field.endsWith("\"")) { + field = field.substring(1, field.length() - 1); + } + String fieldName = properFieldNames.get(field); - // boolean - if (target.getType() == boolean.class) - { - boolean targetValue = this.strAsBool(value); - target.setBoolean(null, targetValue); - - if (targetValue) - { - success = "\""+fieldName+"\" option set to true (enabled)."; - } - else - { - success = "\""+fieldName+"\" option set to false (disabled)."; - } - } + if (fieldName == null || fieldName.isEmpty()) { + msg("No configuration setting \"%s\" exists.", field); + return; + } - // int - else if (target.getType() == int.class) - { - try - { - int intVal = Integer.parseInt(value); - target.setInt(null, intVal); - success = "\""+fieldName+"\" option set to "+intVal+"."; - } - catch(NumberFormatException ex) - { - sendMessage("Cannot set \""+fieldName+"\": integer (whole number) value required."); - return; - } - } + String success = ""; - // long - else if (target.getType() == long.class) - { - try - { - long longVal = Long.parseLong(value); - target.setLong(null, longVal); - success = "\""+fieldName+"\" option set to "+longVal+"."; - } - catch(NumberFormatException ex) - { - sendMessage("Cannot set \""+fieldName+"\": long integer (whole number) value required."); - return; - } - } + String value = args.get(1); + for (int i = 2; i < args.size(); i++) { + value += ' ' + args.get(i); + } - // double - else if (target.getType() == double.class) - { - try - { - double doubleVal = Double.parseDouble(value); - target.setDouble(null, doubleVal); - success = "\""+fieldName+"\" option set to "+doubleVal+"."; - } - catch(NumberFormatException ex) - { - sendMessage("Cannot set \""+fieldName+"\": double (numeric) value required."); - return; - } - } + try { + Field target = Conf.class.getField(fieldName); - // float - else if (target.getType() == float.class) - { - try - { - float floatVal = Float.parseFloat(value); - target.setFloat(null, floatVal); - success = "\""+fieldName+"\" option set to "+floatVal+"."; - } - catch(NumberFormatException ex) - { - sendMessage("Cannot set \""+fieldName+"\": float (numeric) value required."); - return; - } - } + // boolean + if (target.getType() == boolean.class) { + boolean targetValue = this.strAsBool(value); + target.setBoolean(null, targetValue); - // String - else if (target.getType() == String.class) - { - target.set(null, value); - success = "\""+fieldName+"\" option set to \""+value+"\"."; - } + if (targetValue) { + success = "\"" + fieldName + "\" option set to true (enabled)."; + } else { + success = "\"" + fieldName + "\" option set to false (disabled)."; + } + } - // ChatColor - else if (target.getType() == ChatColor.class) - { - ChatColor newColor = null; - try - { - newColor = ChatColor.valueOf(value.toUpperCase()); - } - catch (IllegalArgumentException ex) - { - - } - if (newColor == null) - { - sendMessage("Cannot set \""+fieldName+"\": \""+value.toUpperCase()+"\" is not a valid color."); - return; - } - target.set(null, newColor); - success = "\""+fieldName+"\" color option set to \""+value.toUpperCase()+"\"."; - } + // int + else if (target.getType() == int.class) { + try { + int intVal = Integer.parseInt(value); + target.setInt(null, intVal); + success = "\"" + fieldName + "\" option set to " + intVal + "."; + } catch (NumberFormatException ex) { + sendMessage("Cannot set \"" + fieldName + "\": integer (whole number) value required."); + return; + } + } - // Set or other parameterized collection - else if (target.getGenericType() instanceof ParameterizedType) - { - ParameterizedType targSet = (ParameterizedType)target.getGenericType(); - Type innerType = targSet.getActualTypeArguments()[0]; + // long + else if (target.getType() == long.class) { + try { + long longVal = Long.parseLong(value); + target.setLong(null, longVal); + success = "\"" + fieldName + "\" option set to " + longVal + "."; + } catch (NumberFormatException ex) { + sendMessage("Cannot set \"" + fieldName + "\": long integer (whole number) value required."); + return; + } + } - // not a Set, somehow, and that should be the only collection we're using in Conf.java - if (targSet.getRawType() != Set.class) - { - sendMessage("\""+fieldName+"\" is not a data collection type which can be modified with this command."); - return; - } + // double + else if (target.getType() == double.class) { + try { + double doubleVal = Double.parseDouble(value); + target.setDouble(null, doubleVal); + success = "\"" + fieldName + "\" option set to " + doubleVal + "."; + } catch (NumberFormatException ex) { + sendMessage("Cannot set \"" + fieldName + "\": double (numeric) value required."); + return; + } + } - // Set - else if (innerType == Material.class) - { - Material newMat = null; - try - { - newMat = Material.valueOf(value.toUpperCase()); - } - catch (IllegalArgumentException ex) - { - - } - if (newMat == null) - { - sendMessage("Cannot change \""+fieldName+"\" set: \""+value.toUpperCase()+"\" is not a valid material."); - return; - } + // float + else if (target.getType() == float.class) { + try { + float floatVal = Float.parseFloat(value); + target.setFloat(null, floatVal); + success = "\"" + fieldName + "\" option set to " + floatVal + "."; + } catch (NumberFormatException ex) { + sendMessage("Cannot set \"" + fieldName + "\": float (numeric) value required."); + return; + } + } - @SuppressWarnings("unchecked") - Set matSet = (Set)target.get(null); + // String + else if (target.getType() == String.class) { + target.set(null, value); + success = "\"" + fieldName + "\" option set to \"" + value + "\"."; + } - // Material already present, so remove it - if (matSet.contains(newMat)) - { - matSet.remove(newMat); - target.set(null, matSet); - success = "\""+fieldName+"\" set: Material \""+value.toUpperCase()+"\" removed."; - } - // Material not present yet, add it - else - { - matSet.add(newMat); - target.set(null, matSet); - success = "\""+fieldName+"\" set: Material \""+value.toUpperCase()+"\" added."; - } - } + // ChatColor + else if (target.getType() == ChatColor.class) { + ChatColor newColor = null; + try { + newColor = ChatColor.valueOf(value.toUpperCase()); + } catch (IllegalArgumentException ex) { - // Set - else if (innerType == String.class) - { - @SuppressWarnings("unchecked") - Set stringSet = (Set)target.get(null); + } + if (newColor == null) { + sendMessage("Cannot set \"" + fieldName + "\": \"" + value.toUpperCase() + "\" is not a valid color."); + return; + } + target.set(null, newColor); + success = "\"" + fieldName + "\" color option set to \"" + value.toUpperCase() + "\"."; + } - // String already present, so remove it - if (stringSet.contains(value)) - { - stringSet.remove(value); - target.set(null, stringSet); - success = "\""+fieldName+"\" set: \""+value+"\" removed."; - } - // String not present yet, add it - else - { - stringSet.add(value); - target.set(null, stringSet); - success = "\""+fieldName+"\" set: \""+value+"\" added."; - } - } + // Set or other parameterized collection + else if (target.getGenericType() instanceof ParameterizedType) { + ParameterizedType targSet = (ParameterizedType) target.getGenericType(); + Type innerType = targSet.getActualTypeArguments()[0]; - // Set of unknown type - else - { - sendMessage("\""+fieldName+"\" is not a data type set which can be modified with this command."); - return; - } - } + // not a Set, somehow, and that should be the only collection we're using in Conf.java + if (targSet.getRawType() != Set.class) { + sendMessage("\"" + fieldName + "\" is not a data collection type which can be modified with this command."); + return; + } - // unknown type - else - { - sendMessage("\""+fieldName+"\" is not a data type which can be modified with this command."); - return; - } - } - catch (NoSuchFieldException ex) - { - sendMessage("Configuration setting \""+fieldName+"\" couldn't be matched, though it should be... please report this error."); - return; - } - catch (IllegalAccessException ex) - { - sendMessage("Error setting configuration setting \""+fieldName+"\" to \""+value+"\"."); - return; - } + // Set + else if (innerType == Material.class) { + Material newMat = null; + try { + newMat = Material.valueOf(value.toUpperCase()); + } catch (IllegalArgumentException ex) { - if (!success.isEmpty()) - { - if (sender instanceof Player) - { - sendMessage(success); - P.p.log(success + " Command was run by "+fme.getName()+"."); - } - else // using P.p.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log - P.p.log(success); - } - // save change to disk - Conf.save(); + } + if (newMat == null) { + sendMessage("Cannot change \"" + fieldName + "\" set: \"" + value.toUpperCase() + "\" is not a valid material."); + return; + } + + @SuppressWarnings("unchecked") + Set matSet = (Set) target.get(null); + + // Material already present, so remove it + if (matSet.contains(newMat)) { + matSet.remove(newMat); + target.set(null, matSet); + success = "\"" + fieldName + "\" set: Material \"" + value.toUpperCase() + "\" removed."; + } + // Material not present yet, add it + else { + matSet.add(newMat); + target.set(null, matSet); + success = "\"" + fieldName + "\" set: Material \"" + value.toUpperCase() + "\" added."; + } + } + + // Set + else if (innerType == String.class) { + @SuppressWarnings("unchecked") + Set stringSet = (Set) target.get(null); + + // String already present, so remove it + if (stringSet.contains(value)) { + stringSet.remove(value); + target.set(null, stringSet); + success = "\"" + fieldName + "\" set: \"" + value + "\" removed."; + } + // String not present yet, add it + else { + stringSet.add(value); + target.set(null, stringSet); + success = "\"" + fieldName + "\" set: \"" + value + "\" added."; + } + } + + // Set of unknown type + else { + sendMessage("\"" + fieldName + "\" is not a data type set which can be modified with this command."); + return; + } + } + + // unknown type + else { + sendMessage("\"" + fieldName + "\" is not a data type which can be modified with this command."); + return; + } + } catch (NoSuchFieldException ex) { + sendMessage("Configuration setting \"" + fieldName + "\" couldn't be matched, though it should be... please report this error."); + return; + } catch (IllegalAccessException ex) { + sendMessage("Error setting configuration setting \"" + fieldName + "\" to \"" + value + "\"."); + return; + } + + if (!success.isEmpty()) { + if (sender instanceof Player) { + sendMessage(success); + P.p.log(success + " Command was run by " + fme.getName() + "."); + } else // using P.p.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log + P.p.log(success); + } + // save change to disk + Conf.save(); + + // in case some Spout related setting was changed + SpoutFeatures.updateAppearances(); + } - // in case some Spout related setting was changed - SpoutFeatures.updateAppearances(); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java index e8f687c5..6d65498a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -1,105 +1,91 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; - -import org.bukkit.Bukkit; - -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.P; +import com.massivecraft.factions.*; import com.massivecraft.factions.event.FPlayerJoinEvent; import com.massivecraft.factions.event.FactionCreateEvent; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; + +import java.util.ArrayList; -public class CmdCreate extends FCommand -{ - public CmdCreate() - { - super(); - this.aliases.add("create"); - - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.CREATE.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - String tag = this.argAsString(0); - - if (fme.hasFaction()) - { - msg("You must leave your current faction first."); - return; - } - - if (Factions.i.isTagTaken(tag)) - { - msg("That tag is already in use."); - return; - } - - ArrayList tagValidationErrors = Factions.validateTag(tag); - if (tagValidationErrors.size() > 0) - { - sendMessage(tagValidationErrors); - return; - } +public class CmdCreate extends FCommand { + public CmdCreate() { + super(); + this.aliases.add("create"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if ( ! canAffordCommand(Conf.econCostCreate, "to create a new faction")) return; + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); - // trigger the faction creation event (cancellable) - FactionCreateEvent createEvent = new FactionCreateEvent(me, tag); - Bukkit.getServer().getPluginManager().callEvent(createEvent); - if(createEvent.isCancelled()) return; + this.permission = Permission.CREATE.node; + this.disableOnLock = true; - // then make 'em pay (if applicable) - if ( ! payForCommand(Conf.econCostCreate, "to create a new faction", "for creating a new faction")) return; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - Faction faction = Factions.i.create(); + @Override + public void perform() { + String tag = this.argAsString(0); - // TODO: Why would this even happen??? Auto increment clash?? - if (faction == null) - { - msg("There was an internal error while trying to create your faction. Please try again."); - return; - } + if (fme.hasFaction()) { + msg("You must leave your current faction first."); + return; + } - // finish setting up the Faction - faction.setTag(tag); + if (Factions.i.isTagTaken(tag)) { + msg("That tag is already in use."); + return; + } - // trigger the faction join event for the creator - FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.i.get(me),faction,FPlayerJoinEvent.PlayerJoinReason.CREATE); - Bukkit.getServer().getPluginManager().callEvent(joinEvent); - // join event cannot be cancelled or you'll have an empty faction + ArrayList tagValidationErrors = Factions.validateTag(tag); + if (tagValidationErrors.size() > 0) { + sendMessage(tagValidationErrors); + return; + } - // finish setting up the FPlayer - fme.setRole(Role.ADMIN); - fme.setFaction(faction); + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostCreate, "to create a new faction")) return; - for (FPlayer follower : FPlayers.i.getOnline()) - { - follower.msg("%s created a new faction %s", fme.describeTo(follower, true), faction.getTag(follower)); - } - - msg("You should now: %s", p.cmdBase.cmdDescription.getUseageTemplate()); + // trigger the faction creation event (cancellable) + FactionCreateEvent createEvent = new FactionCreateEvent(me, tag); + Bukkit.getServer().getPluginManager().callEvent(createEvent); + if (createEvent.isCancelled()) return; + + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostCreate, "to create a new faction", "for creating a new faction")) return; + + Faction faction = Factions.i.create(); + + // TODO: Why would this even happen??? Auto increment clash?? + if (faction == null) { + msg("There was an internal error while trying to create your faction. Please try again."); + return; + } + + // finish setting up the Faction + faction.setTag(tag); + + // trigger the faction join event for the creator + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.i.get(me), faction, FPlayerJoinEvent.PlayerJoinReason.CREATE); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + // join event cannot be cancelled or you'll have an empty faction + + // finish setting up the FPlayer + fme.setRole(Role.ADMIN); + fme.setFaction(faction); + + for (FPlayer follower : FPlayers.i.getOnline()) { + follower.msg("%s created a new faction %s", fme.describeTo(follower, true), faction.getTag(follower)); + } + + msg("You should now: %s", p.cmdBase.cmdDescription.getUseageTemplate()); + + if (Conf.logFactionCreate) + P.p.log(fme.getName() + " created a new faction: " + tag); + } - if (Conf.logFactionCreate) - P.p.log(fme.getName()+" created a new faction: "+tag); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java index 1f41f088..2dc46d97 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -3,45 +3,41 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.struct.Permission; -public class CmdDeinvite extends FCommand -{ - - public CmdDeinvite() - { - super(); - this.aliases.add("deinvite"); - this.aliases.add("deinv"); - - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.DEINVITE.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) return; - - if (you.getFaction() == myFaction) - { - msg("%s is already a member of %s", you.getName(), myFaction.getTag()); - msg("You might want to: %s", p.cmdBase.cmdKick.getUseageTemplate(false)); - return; - } - - myFaction.deinvite(you); - - you.msg("%s revoked your invitation to %s.", fme.describeTo(you), myFaction.describeTo(you)); - - myFaction.msg("%s revoked %s's invitation.", fme.describeTo(myFaction), you.describeTo(myFaction)); - } - +public class CmdDeinvite extends FCommand { + + public CmdDeinvite() { + super(); + this.aliases.add("deinvite"); + this.aliases.add("deinv"); + + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); + + this.permission = Permission.DEINVITE.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) return; + + if (you.getFaction() == myFaction) { + msg("%s is already a member of %s", you.getName(), myFaction.getTag()); + msg("You might want to: %s", p.cmdBase.cmdKick.getUseageTemplate(false)); + return; + } + + myFaction.deinvite(you); + + you.msg("%s revoked your invitation to %s.", fme.describeTo(you), myFaction.describeTo(you)); + + myFaction.msg("%s revoked %s's invitation.", fme.describeTo(myFaction), you.describeTo(myFaction)); + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java index 5ba8cdd9..8135f185 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java @@ -6,47 +6,43 @@ import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TextUtil; -public class CmdDescription extends FCommand -{ - public CmdDescription() - { - super(); - this.aliases.add("desc"); - - this.requiredArgs.add("desc"); - this.errorOnToManyArgs = false; - //this.optionalArgs - - this.permission = Permission.DESCRIPTION.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostDesc, "to change faction description", "for changing faction description")) return; +public class CmdDescription extends FCommand { + public CmdDescription() { + super(); + this.aliases.add("desc"); - myFaction.setDescription(TextUtil.implode(args, " ").replaceAll("(&([a-f0-9]))", "& $2")); // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up + this.requiredArgs.add("desc"); + this.errorOnToManyArgs = false; + //this.optionalArgs - if ( ! Conf.broadcastDescriptionChanges) - { - fme.msg("You have changed the description for %s to:", myFaction.describeTo(fme)); - fme.sendMessage(myFaction.getDescription()); - return; - } + this.permission = Permission.DESCRIPTION.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostDesc, "to change faction description", "for changing faction description")) + return; + + myFaction.setDescription(TextUtil.implode(args, " ").replaceAll("(&([a-f0-9]))", "& $2")); // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up + + if (!Conf.broadcastDescriptionChanges) { + fme.msg("You have changed the description for %s to:", myFaction.describeTo(fme)); + fme.sendMessage(myFaction.getDescription()); + return; + } + + // Broadcast the description to everyone + for (FPlayer fplayer : FPlayers.i.getOnline()) { + fplayer.msg("The faction %s changed their description to:", myFaction.describeTo(fplayer)); + fplayer.sendMessage(myFaction.getDescription()); // players can inject "&" or "`" or "" or whatever in their description; &k is particularly interesting looking + } + } - // Broadcast the description to everyone - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - fplayer.msg("The faction %s changed their description to:", myFaction.describeTo(fplayer)); - fplayer.sendMessage(myFaction.getDescription()); // players can inject "&" or "`" or "" or whatever in their description; &k is particularly interesting looking - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index c9e63a32..babd5453 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -1,113 +1,92 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - -import com.massivecraft.factions.Conf; +import com.massivecraft.factions.*; import com.massivecraft.factions.event.FPlayerLeaveEvent; import com.massivecraft.factions.event.FactionDisbandEvent; import com.massivecraft.factions.integration.Econ; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; -import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; -public class CmdDisband extends FCommand -{ - public CmdDisband() - { - super(); - this.aliases.add("disband"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "yours"); - - this.permission = Permission.DISBAND.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - // The faction, default to your own.. but null if console sender. - Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); - if (faction == null) return; - - boolean isMyFaction = fme == null ? false : faction == myFaction; - - if (isMyFaction) - { - if ( ! assertMinRole(Role.ADMIN)) return; - } - else - { - if ( ! Permission.DISBAND_ANY.has(sender, true)) - { - return; - } - } +public class CmdDisband extends FCommand { + public CmdDisband() { + super(); + this.aliases.add("disband"); - if (! faction.isNormal()) - { - msg("You cannot disband the Wilderness, SafeZone, or WarZone."); - return; - } - if (faction.isPermanent()) - { - msg("This faction is designated as permanent, so you cannot disband it."); - return; - } + //this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "yours"); - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(me, faction.getId()); - Bukkit.getServer().getPluginManager().callEvent(disbandEvent); - if(disbandEvent.isCancelled()) return; + this.permission = Permission.DISBAND.node; + this.disableOnLock = true; - // Send FPlayerLeaveEvent for each player in the faction - for ( FPlayer fplayer : faction.getFPlayers() ) - { - Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, faction, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND)); - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - // Inform all players - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - String who = senderIsConsole ? "A server admin" : fme.describeTo(fplayer); - if (fplayer.getFaction() == faction) - { - fplayer.msg("%s disbanded your faction.", who); - } - else - { - fplayer.msg("%s disbanded the faction %s.", who, faction.getTag(fplayer)); - } - } - if (Conf.logFactionDisband) - P.p.log("The faction "+faction.getTag()+" ("+faction.getId()+") was disbanded by "+(senderIsConsole ? "console command" : fme.getName())+"."); + @Override + public void perform() { + // The faction, default to your own.. but null if console sender. + Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); + if (faction == null) return; - if (Econ.shouldBeUsed() && ! senderIsConsole) - { - //Give all the faction's money to the disbander - double amount = Econ.getBalance(faction.getAccountId()); - Econ.transferMoney(fme, faction, fme, amount, false); - - if (amount > 0.0) - { - String amountString = Econ.moneyString(amount); - msg("You have been given the disbanded faction's bank, totaling %s.", amountString); - P.p.log(fme.getName() + " has been given bank holdings of "+amountString+" from disbanding "+faction.getTag()+"."); - } - } - - faction.detach(); + boolean isMyFaction = fme == null ? false : faction == myFaction; - SpoutFeatures.updateAppearances(); - } + if (isMyFaction) { + if (!assertMinRole(Role.ADMIN)) return; + } else { + if (!Permission.DISBAND_ANY.has(sender, true)) { + return; + } + } + + if (!faction.isNormal()) { + msg("You cannot disband the Wilderness, SafeZone, or WarZone."); + return; + } + if (faction.isPermanent()) { + msg("This faction is designated as permanent, so you cannot disband it."); + return; + } + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(me, faction.getId()); + Bukkit.getServer().getPluginManager().callEvent(disbandEvent); + if (disbandEvent.isCancelled()) return; + + // Send FPlayerLeaveEvent for each player in the faction + for (FPlayer fplayer : faction.getFPlayers()) { + Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, faction, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND)); + } + + // Inform all players + for (FPlayer fplayer : FPlayers.i.getOnline()) { + String who = senderIsConsole ? "A server admin" : fme.describeTo(fplayer); + if (fplayer.getFaction() == faction) { + fplayer.msg("%s disbanded your faction.", who); + } else { + fplayer.msg("%s disbanded the faction %s.", who, faction.getTag(fplayer)); + } + } + if (Conf.logFactionDisband) + P.p.log("The faction " + faction.getTag() + " (" + faction.getId() + ") was disbanded by " + (senderIsConsole ? "console command" : fme.getName()) + "."); + + if (Econ.shouldBeUsed() && !senderIsConsole) { + //Give all the faction's money to the disbander + double amount = Econ.getBalance(faction.getAccountId()); + Econ.transferMoney(fme, faction, fme, amount, false); + + if (amount > 0.0) { + String amountString = Econ.moneyString(amount); + msg("You have been given the disbanded faction's bank, totaling %s.", amountString); + P.p.log(fme.getName() + " has been given bank holdings of " + amountString + " from disbanding " + faction.getTag() + "."); + } + } + + faction.detach(); + + SpoutFeatures.updateAppearances(); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java index 39875de8..cccac5bb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java @@ -1,190 +1,184 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.P; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; +import java.util.ArrayList; -public class CmdHelp extends FCommand -{ - - public CmdHelp() - { - super(); - this.aliases.add("help"); - this.aliases.add("h"); - this.aliases.add("?"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("page", "1"); - - this.permission = Permission.HELP.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - if (helpPages == null) updateHelp(); - - int page = this.argAsInt(0, 1); - - sendMessage(p.txt.titleize("Factions Help ("+page+"/"+helpPages.size()+")")); - - page -= 1; - - if (page < 0 || page >= helpPages.size()) - { - msg("This page does not exist"); - return; - } - sendMessage(helpPages.get(page)); - } - - //----------------------------------------------// - // Build the help pages - //----------------------------------------------// - - public ArrayList> helpPages; - - public void updateHelp() - { - helpPages = new ArrayList>(); - ArrayList pageLines; - pageLines = new ArrayList(); - pageLines.add( p.cmdBase.cmdHelp.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdList.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdShow.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdPower.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdJoin.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdLeave.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdChat.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdHome.getUseageTemplate(true) ); - pageLines.add( p.txt.parse("Learn how to create a faction on the next page.") ); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add( p.cmdBase.cmdCreate.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdDescription.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdTag.getUseageTemplate(true) ); - pageLines.add( p.txt.parse("You might want to close it and use invitations:" )); - pageLines.add( p.cmdBase.cmdOpen.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdInvite.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdDeinvite.getUseageTemplate(true) ); - pageLines.add( p.txt.parse("And don't forget to set your home:" )); - pageLines.add( p.cmdBase.cmdSethome.getUseageTemplate(true) ); - helpPages.add(pageLines); - - if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) - { - pageLines = new ArrayList(); - pageLines.add( "" ); - pageLines.add( p.txt.parse("Your faction has a bank which is used to pay for certain" )); - pageLines.add( p.txt.parse("things, so it will need to have money deposited into it." )); - pageLines.add( p.txt.parse("To learn more, use the money command." )); - pageLines.add( "" ); - pageLines.add( p.cmdBase.cmdMoney.getUseageTemplate(true) ); - pageLines.add( "" ); - pageLines.add( "" ); - pageLines.add( "" ); - helpPages.add(pageLines); - } - - pageLines = new ArrayList(); - pageLines.add( p.cmdBase.cmdClaim.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdAutoClaim.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdUnclaim.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdUnclaimall.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdKick.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdMod.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdAdmin.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdTitle.getUseageTemplate(true) ); - pageLines.add( p.txt.parse("Player titles are just for fun. No rules connected to them." )); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add( p.cmdBase.cmdMap.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdBoom.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdOwner.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdOwnerList.getUseageTemplate(true) ); - pageLines.add(p.txt.parse("Claimed land with ownership set is further protected so")); - pageLines.add(p.txt.parse("that only the owner(s), faction admin, and possibly the")); - pageLines.add(p.txt.parse("faction moderators have full access.")); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add( p.cmdBase.cmdDisband.getUseageTemplate(true) ); - pageLines.add(""); - pageLines.add( p.cmdBase.cmdRelationAlly.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdRelationNeutral.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdRelationEnemy.getUseageTemplate(true) ); - pageLines.add(p.txt.parse("Set the relation you WISH to have with another faction.")); - pageLines.add(p.txt.parse("Your default relation with other factions will be neutral.")); - pageLines.add(p.txt.parse("If BOTH factions choose \"ally\" you will be allies.")); - pageLines.add(p.txt.parse("If ONE faction chooses \"enemy\" you will be enemies.")); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("You can never hurt members or allies.")); - pageLines.add(p.txt.parse("You can not hurt neutrals in their own territory.")); - pageLines.add(p.txt.parse("You can always hurt enemies and players without faction.")); - pageLines.add(""); - pageLines.add(p.txt.parse("Damage from enemies is reduced in your own territory.")); - pageLines.add(p.txt.parse("When you die you lose power. It is restored over time.")); - pageLines.add(p.txt.parse("The power of a faction is the sum of all member power.")); - pageLines.add(p.txt.parse("The power of a faction determines how much land it can hold.")); - pageLines.add(p.txt.parse("You can claim land from factions with too little power.")); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("Only faction members can build and destroy in their own")); - pageLines.add(p.txt.parse("territory. Usage of the following items is also restricted:")); - pageLines.add(p.txt.parse("Door, Chest, Furnace, Dispenser, Diode.")); - pageLines.add(""); - pageLines.add(p.txt.parse("Make sure to put pressure plates in front of doors for your")); - pageLines.add(p.txt.parse("guest visitors. Otherwise they can't get through. You can")); - pageLines.add(p.txt.parse("also use this to create member only areas.")); - pageLines.add(p.txt.parse("As dispensers are protected, you can create traps without")); - pageLines.add(p.txt.parse("worrying about those arrows getting stolen.")); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add("Finally some commands for the server admins:"); - pageLines.add( p.cmdBase.cmdBypass.getUseageTemplate(true) ); - pageLines.add(p.txt.parse("/f claim safezone claim land for the Safe Zone")); - pageLines.add(p.txt.parse("/f claim warzone claim land for the War Zone")); - pageLines.add(p.txt.parse("/f autoclaim [safezone|warzone] take a guess")); - pageLines.add( p.cmdBase.cmdSafeunclaimall.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdWarunclaimall.getUseageTemplate(true) ); - pageLines.add(p.txt.parse("Note: " + p.cmdBase.cmdUnclaim.getUseageTemplate(false) + P.p.txt.parse("") + " works on safe/war zones as well.")); - pageLines.add( p.cmdBase.cmdPeaceful.getUseageTemplate(true) ); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("More commands for server admins:")); - pageLines.add( p.cmdBase.cmdChatSpy.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdPermanent.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdPermanentPower.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdPowerBoost.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdConfig.getUseageTemplate(true) ); - helpPages.add(pageLines); - - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("Even more commands for server admins:")); - pageLines.add( p.cmdBase.cmdLock.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdReload.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdSaveAll.getUseageTemplate(true) ); - pageLines.add( p.cmdBase.cmdVersion.getUseageTemplate(true) ); - helpPages.add(pageLines); - } +public class CmdHelp extends FCommand { + + public CmdHelp() { + super(); + this.aliases.add("help"); + this.aliases.add("h"); + this.aliases.add("?"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("page", "1"); + + this.permission = Permission.HELP.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + if (helpPages == null) updateHelp(); + + int page = this.argAsInt(0, 1); + + sendMessage(p.txt.titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); + + page -= 1; + + if (page < 0 || page >= helpPages.size()) { + msg("This page does not exist"); + return; + } + sendMessage(helpPages.get(page)); + } + + //----------------------------------------------// + // Build the help pages + //----------------------------------------------// + + public ArrayList> helpPages; + + public void updateHelp() { + helpPages = new ArrayList>(); + ArrayList pageLines; + + pageLines = new ArrayList(); + pageLines.add(p.cmdBase.cmdHelp.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdList.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdShow.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPower.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdJoin.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdLeave.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdChat.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdHome.getUseageTemplate(true)); + pageLines.add(p.txt.parse("Learn how to create a faction on the next page.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.cmdBase.cmdCreate.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdDescription.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdTag.getUseageTemplate(true)); + pageLines.add(p.txt.parse("You might want to close it and use invitations:")); + pageLines.add(p.cmdBase.cmdOpen.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdInvite.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdDeinvite.getUseageTemplate(true)); + pageLines.add(p.txt.parse("And don't forget to set your home:")); + pageLines.add(p.cmdBase.cmdSethome.getUseageTemplate(true)); + helpPages.add(pageLines); + + if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { + pageLines = new ArrayList(); + pageLines.add(""); + pageLines.add(p.txt.parse("Your faction has a bank which is used to pay for certain")); + pageLines.add(p.txt.parse("things, so it will need to have money deposited into it.")); + pageLines.add(p.txt.parse("To learn more, use the money command.")); + pageLines.add(""); + pageLines.add(p.cmdBase.cmdMoney.getUseageTemplate(true)); + pageLines.add(""); + pageLines.add(""); + pageLines.add(""); + helpPages.add(pageLines); + } + + pageLines = new ArrayList(); + pageLines.add(p.cmdBase.cmdClaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdAutoClaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdUnclaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdUnclaimall.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdKick.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdMod.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdAdmin.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdTitle.getUseageTemplate(true)); + pageLines.add(p.txt.parse("Player titles are just for fun. No rules connected to them.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.cmdBase.cmdMap.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdBoom.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdOwner.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdOwnerList.getUseageTemplate(true)); + pageLines.add(p.txt.parse("Claimed land with ownership set is further protected so")); + pageLines.add(p.txt.parse("that only the owner(s), faction admin, and possibly the")); + pageLines.add(p.txt.parse("faction moderators have full access.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.cmdBase.cmdDisband.getUseageTemplate(true)); + pageLines.add(""); + pageLines.add(p.cmdBase.cmdRelationAlly.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdRelationNeutral.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdRelationEnemy.getUseageTemplate(true)); + pageLines.add(p.txt.parse("Set the relation you WISH to have with another faction.")); + pageLines.add(p.txt.parse("Your default relation with other factions will be neutral.")); + pageLines.add(p.txt.parse("If BOTH factions choose \"ally\" you will be allies.")); + pageLines.add(p.txt.parse("If ONE faction chooses \"enemy\" you will be enemies.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.txt.parse("You can never hurt members or allies.")); + pageLines.add(p.txt.parse("You can not hurt neutrals in their own territory.")); + pageLines.add(p.txt.parse("You can always hurt enemies and players without faction.")); + pageLines.add(""); + pageLines.add(p.txt.parse("Damage from enemies is reduced in your own territory.")); + pageLines.add(p.txt.parse("When you die you lose power. It is restored over time.")); + pageLines.add(p.txt.parse("The power of a faction is the sum of all member power.")); + pageLines.add(p.txt.parse("The power of a faction determines how much land it can hold.")); + pageLines.add(p.txt.parse("You can claim land from factions with too little power.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.txt.parse("Only faction members can build and destroy in their own")); + pageLines.add(p.txt.parse("territory. Usage of the following items is also restricted:")); + pageLines.add(p.txt.parse("Door, Chest, Furnace, Dispenser, Diode.")); + pageLines.add(""); + pageLines.add(p.txt.parse("Make sure to put pressure plates in front of doors for your")); + pageLines.add(p.txt.parse("guest visitors. Otherwise they can't get through. You can")); + pageLines.add(p.txt.parse("also use this to create member only areas.")); + pageLines.add(p.txt.parse("As dispensers are protected, you can create traps without")); + pageLines.add(p.txt.parse("worrying about those arrows getting stolen.")); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add("Finally some commands for the server admins:"); + pageLines.add(p.cmdBase.cmdBypass.getUseageTemplate(true)); + pageLines.add(p.txt.parse("/f claim safezone claim land for the Safe Zone")); + pageLines.add(p.txt.parse("/f claim warzone claim land for the War Zone")); + pageLines.add(p.txt.parse("/f autoclaim [safezone|warzone] take a guess")); + pageLines.add(p.cmdBase.cmdSafeunclaimall.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdWarunclaimall.getUseageTemplate(true)); + pageLines.add(p.txt.parse("Note: " + p.cmdBase.cmdUnclaim.getUseageTemplate(false) + P.p.txt.parse("") + " works on safe/war zones as well.")); + pageLines.add(p.cmdBase.cmdPeaceful.getUseageTemplate(true)); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.txt.parse("More commands for server admins:")); + pageLines.add(p.cmdBase.cmdChatSpy.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPermanent.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPermanentPower.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPowerBoost.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdConfig.getUseageTemplate(true)); + helpPages.add(pageLines); + + pageLines = new ArrayList(); + pageLines.add(p.txt.parse("Even more commands for server admins:")); + pageLines.add(p.cmdBase.cmdLock.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdReload.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdSaveAll.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdVersion.getUseageTemplate(true)); + helpPages.add(pageLines); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java index 213bb075..42d1db71 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java @@ -1,148 +1,132 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; +import com.massivecraft.factions.*; import com.massivecraft.factions.integration.EssentialsFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.zcore.util.SmokeUtil; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; -public class CmdHome extends FCommand -{ - - public CmdHome() - { - super(); - this.aliases.add("home"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.HOME.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - // TODO: Hide this command on help also. - if ( ! Conf.homesEnabled) - { - fme.msg("Sorry, Faction homes are disabled on this server."); - return; - } +public class CmdHome extends FCommand { - if ( ! Conf.homesTeleportCommandEnabled) - { - fme.msg("Sorry, the ability to teleport to Faction homes is disabled on this server."); - return; - } - - if ( ! myFaction.hasHome()) - { - fme.msg("Your faction does not have a home. " + (fme.getRole().value < Role.MODERATOR.value ? " Ask your leader to:" : "You should:")); - fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); - return; - } - - if ( ! Conf.homesTeleportAllowedFromEnemyTerritory && fme.isInEnemyTerritory()) - { - fme.msg("You cannot teleport to your faction home while in the territory of an enemy faction."); - return; - } - - if ( ! Conf.homesTeleportAllowedFromDifferentWorld && me.getWorld().getUID() != myFaction.getHome().getWorld().getUID()) - { - fme.msg("You cannot teleport to your faction home while in a different world."); - return; - } - - Faction faction = Board.getFactionAt(new FLocation(me.getLocation())); - Location loc = me.getLocation().clone(); - - // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby - if - ( - Conf.homesTeleportAllowedEnemyDistance > 0 - && - ! faction.isSafeZone() - && - ( - ! fme.isInOwnTerritory() - || - ( - fme.isInOwnTerritory() - && - ! Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory - ) - ) - ) - { - World w = loc.getWorld(); - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); + public CmdHome() { + super(); + this.aliases.add("home"); - for (Player p : me.getServer().getOnlinePlayers()) - { - if (p == null || !p.isOnline() || p.isDead() || p == me || p.getWorld() != w) - continue; + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - FPlayer fp = FPlayers.i.get(p); - if (fme.getRelationTo(fp) != Relation.ENEMY) - continue; + this.permission = Permission.HOME.node; + this.disableOnLock = false; - Location l = p.getLocation(); - double dx = Math.abs(x - l.getX()); - double dy = Math.abs(y - l.getY()); - double dz = Math.abs(z - l.getZ()); - double max = Conf.homesTeleportAllowedEnemyDistance; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - // box-shaped distance check - if (dx > max || dy > max || dz > max) - continue; + @Override + public void perform() { + // TODO: Hide this command on help also. + if (!Conf.homesEnabled) { + fme.msg("Sorry, Faction homes are disabled on this server."); + return; + } - fme.msg("You cannot teleport to your faction home while an enemy is within " + Conf.homesTeleportAllowedEnemyDistance + " blocks of you."); - return; - } - } + if (!Conf.homesTeleportCommandEnabled) { + fme.msg("Sorry, the ability to teleport to Faction homes is disabled on this server."); + return; + } - // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) - if (EssentialsFeatures.handleTeleport(me, myFaction.getHome())) return; + if (!myFaction.hasHome()) { + fme.msg("Your faction does not have a home. " + (fme.getRole().value < Role.MODERATOR.value ? " Ask your leader to:" : "You should:")); + fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostHome, "to teleport to your faction home", "for teleporting to your faction home")) return; + if (!Conf.homesTeleportAllowedFromEnemyTerritory && fme.isInEnemyTerritory()) { + fme.msg("You cannot teleport to your faction home while in the territory of an enemy faction."); + return; + } + + if (!Conf.homesTeleportAllowedFromDifferentWorld && me.getWorld().getUID() != myFaction.getHome().getWorld().getUID()) { + fme.msg("You cannot teleport to your faction home while in a different world."); + return; + } + + Faction faction = Board.getFactionAt(new FLocation(me.getLocation())); + Location loc = me.getLocation().clone(); + + // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby + if + ( + Conf.homesTeleportAllowedEnemyDistance > 0 + && + !faction.isSafeZone() + && + ( + !fme.isInOwnTerritory() + || + ( + fme.isInOwnTerritory() + && + !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory + ) + ) + ) { + World w = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + for (Player p : me.getServer().getOnlinePlayers()) { + if (p == null || !p.isOnline() || p.isDead() || p == me || p.getWorld() != w) + continue; + + FPlayer fp = FPlayers.i.get(p); + if (fme.getRelationTo(fp) != Relation.ENEMY) + continue; + + Location l = p.getLocation(); + double dx = Math.abs(x - l.getX()); + double dy = Math.abs(y - l.getY()); + double dz = Math.abs(z - l.getZ()); + double max = Conf.homesTeleportAllowedEnemyDistance; + + // box-shaped distance check + if (dx > max || dy > max || dz > max) + continue; + + fme.msg("You cannot teleport to your faction home while an enemy is within " + Conf.homesTeleportAllowedEnemyDistance + " blocks of you."); + return; + } + } + + // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) + if (EssentialsFeatures.handleTeleport(me, myFaction.getHome())) return; + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostHome, "to teleport to your faction home", "for teleporting to your faction home")) + return; + + // Create a smoke effect + if (Conf.homesTeleportCommandSmokeEffectEnabled) { + List smokeLocations = new ArrayList(); + smokeLocations.add(loc); + smokeLocations.add(loc.add(0, 1, 0)); + smokeLocations.add(myFaction.getHome()); + smokeLocations.add(myFaction.getHome().clone().add(0, 1, 0)); + SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); + } + + me.teleport(myFaction.getHome()); + } - // Create a smoke effect - if (Conf.homesTeleportCommandSmokeEffectEnabled) - { - List smokeLocations = new ArrayList(); - smokeLocations.add(loc); - smokeLocations.add(loc.add(0, 1, 0)); - smokeLocations.add(myFaction.getHome()); - smokeLocations.add(myFaction.getHome().clone().add(0, 1, 0)); - SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); - } - - me.teleport(myFaction.getHome()); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java index 9a1f187c..c4abccdd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -4,46 +4,42 @@ import com.massivecraft.factions.Conf; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.struct.Permission; -public class CmdInvite extends FCommand -{ - public CmdInvite() - { - super(); - this.aliases.add("invite"); - this.aliases.add("inv"); - - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.INVITE.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) return; - - if (you.getFaction() == myFaction) - { - msg("%s is already a member of %s", you.getName(), myFaction.getTag()); - msg("You might want to: " + p.cmdBase.cmdKick.getUseageTemplate(false)); - return; - } +public class CmdInvite extends FCommand { + public CmdInvite() { + super(); + this.aliases.add("invite"); + this.aliases.add("inv"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostInvite, "to invite someone", "for inviting someone")) return; + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); + + this.permission = Permission.INVITE.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) return; + + if (you.getFaction() == myFaction) { + msg("%s is already a member of %s", you.getName(), myFaction.getTag()); + msg("You might want to: " + p.cmdBase.cmdKick.getUseageTemplate(false)); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostInvite, "to invite someone", "for inviting someone")) return; + + myFaction.invite(you); + + you.msg("%s invited you to %s", fme.describeTo(you, true), myFaction.describeTo(you)); + myFaction.msg("%s invited %s to your faction.", fme.describeTo(myFaction, true), you.describeTo(myFaction)); + } - myFaction.invite(you); - - you.msg("%s invited you to %s", fme.describeTo(you, true), myFaction.describeTo(you)); - myFaction.msg("%s invited %s to your faction.", fme.describeTo(myFaction, true), you.describeTo(myFaction)); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java index 19ea779d..7ca01ce0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -1,114 +1,98 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.P; +import com.massivecraft.factions.*; import com.massivecraft.factions.event.FPlayerJoinEvent; import com.massivecraft.factions.struct.Permission; +import org.bukkit.Bukkit; -public class CmdJoin extends FCommand -{ - public CmdJoin() - { - super(); - this.aliases.add("join"); - - this.requiredArgs.add("faction name"); - this.optionalArgs.put("player", "you"); - - this.permission = Permission.JOIN.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction faction = this.argAsFaction(0); - if (faction == null) return; +public class CmdJoin extends FCommand { + public CmdJoin() { + super(); + this.aliases.add("join"); - FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); - boolean samePlayer = fplayer == fme; + this.requiredArgs.add("faction name"); + this.optionalArgs.put("player", "you"); - if (!samePlayer && ! Permission.JOIN_OTHERS.has(sender, false)) - { - msg("You do not have permission to move other players into a faction."); - return; - } + this.permission = Permission.JOIN.node; + this.disableOnLock = true; - if ( ! faction.isNormal()) - { - msg("Players may only join normal factions. This is a system faction."); - return; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - if (faction == fplayer.getFaction()) - { - msg("%s %s already a member of %s", fplayer.describeTo(fme, true), (samePlayer ? "are" : "is"), faction.getTag(fme)); - return; - } + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) return; - if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= Conf.factionMemberLimit) - { - msg(" ! The faction %s is at the limit of %d members, so %s cannot currently join.", faction.getTag(fme), Conf.factionMemberLimit, fplayer.describeTo(fme, false)); - return; - } + FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); + boolean samePlayer = fplayer == fme; - if (fplayer.hasFaction()) - { - msg("%s must leave %s current faction first.", fplayer.describeTo(fme, true), (samePlayer ? "your" : "their")); - return; - } + if (!samePlayer && !Permission.JOIN_OTHERS.has(sender, false)) { + msg("You do not have permission to move other players into a faction."); + return; + } - if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) - { - msg("%s cannot join a faction with a negative power level.", fplayer.describeTo(fme, true)); - return; - } + if (!faction.isNormal()) { + msg("Players may only join normal factions. This is a system faction."); + return; + } - if( ! (faction.getOpen() || faction.isInvited(fplayer) || fme.isAdminBypassing() || Permission.JOIN_ANY.has(sender, false))) - { - msg("This faction requires invitation."); - if (samePlayer) - faction.msg("%s tried to join your faction.", fplayer.describeTo(faction, true)); - return; - } + if (faction == fplayer.getFaction()) { + msg("%s %s already a member of %s", fplayer.describeTo(fme, true), (samePlayer ? "are" : "is"), faction.getTag(fme)); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if (samePlayer && ! canAffordCommand(Conf.econCostJoin, "to join a faction")) return; + if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= Conf.factionMemberLimit) { + msg(" ! The faction %s is at the limit of %d members, so %s cannot currently join.", faction.getTag(fme), Conf.factionMemberLimit, fplayer.describeTo(fme, false)); + return; + } - // trigger the join event (cancellable) - FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.i.get(me),faction,FPlayerJoinEvent.PlayerJoinReason.COMMAND); - Bukkit.getServer().getPluginManager().callEvent(joinEvent); - if (joinEvent.isCancelled()) return; + if (fplayer.hasFaction()) { + msg("%s must leave %s current faction first.", fplayer.describeTo(fme, true), (samePlayer ? "your" : "their")); + return; + } - // then make 'em pay (if applicable) - if (samePlayer && ! payForCommand(Conf.econCostJoin, "to join a faction", "for joining a faction")) return; + if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { + msg("%s cannot join a faction with a negative power level.", fplayer.describeTo(fme, true)); + return; + } - fme.msg("%s successfully joined %s.", fplayer.describeTo(fme, true), faction.getTag(fme)); + if (!(faction.getOpen() || faction.isInvited(fplayer) || fme.isAdminBypassing() || Permission.JOIN_ANY.has(sender, false))) { + msg("This faction requires invitation."); + if (samePlayer) + faction.msg("%s tried to join your faction.", fplayer.describeTo(faction, true)); + return; + } - if (!samePlayer) - fplayer.msg("%s moved you into the faction %s.", fme.describeTo(fplayer, true), faction.getTag(fplayer)); - faction.msg("%s joined your faction.", fplayer.describeTo(faction, true)); + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (samePlayer && !canAffordCommand(Conf.econCostJoin, "to join a faction")) return; - fplayer.resetFactionData(); - fplayer.setFaction(faction); - faction.deinvite(fplayer); + // trigger the join event (cancellable) + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.i.get(me), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + if (joinEvent.isCancelled()) return; - if (Conf.logFactionJoin) - { - if (samePlayer) - P.p.log("%s joined the faction %s.", fplayer.getName(), faction.getTag()); - else - P.p.log("%s moved the player %s into the faction %s.", fme.getName(), fplayer.getName(), faction.getTag()); - } - } + // then make 'em pay (if applicable) + if (samePlayer && !payForCommand(Conf.econCostJoin, "to join a faction", "for joining a faction")) return; + + fme.msg("%s successfully joined %s.", fplayer.describeTo(fme, true), faction.getTag(fme)); + + if (!samePlayer) + fplayer.msg("%s moved you into the faction %s.", fme.describeTo(fplayer, true), faction.getTag(fplayer)); + faction.msg("%s joined your faction.", fplayer.describeTo(faction, true)); + + fplayer.resetFactionData(); + fplayer.setFaction(faction); + faction.deinvite(fplayer); + + if (Conf.logFactionJoin) { + if (samePlayer) + P.p.log("%s joined the faction %s.", fplayer.getName(), faction.getTag()); + else + P.p.log("%s moved the player %s into the faction %s.", fme.getName(), fplayer.getName(), faction.getTag()); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java index e3646af4..bb7fc512 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -1,7 +1,5 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.Faction; @@ -9,91 +7,84 @@ import com.massivecraft.factions.P; import com.massivecraft.factions.event.FPlayerLeaveEvent; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; -public class CmdKick extends FCommand -{ - - public CmdKick() - { - super(); - this.aliases.add("kick"); - - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.KICK.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) return; - - if (fme == you) - { - msg("You cannot kick yourself."); - msg("You might want to: %s", p.cmdBase.cmdLeave.getUseageTemplate(false)); - return; - } +public class CmdKick extends FCommand { - Faction yourFaction = you.getFaction(); + public CmdKick() { + super(); + this.aliases.add("kick"); - // players with admin-level "disband" permission can bypass these requirements - if ( ! Permission.KICK_ANY.has(sender)) - { - if (yourFaction != myFaction) - { - msg("%s is not a member of %s", you.describeTo(fme, true), myFaction.describeTo(fme)); - return; - } + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); - if (you.getRole().value >= fme.getRole().value) - { - // TODO add more informative messages. - msg("Your rank is too low to kick this player."); - return; - } + this.permission = Permission.KICK.node; + this.disableOnLock = false; - if ( ! Conf.canLeaveWithNegativePower && you.getPower() < 0) - { - msg("You cannot kick that member until their power is positive."); - return; - } - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if ( ! canAffordCommand(Conf.econCostKick, "to kick someone from the faction")) return; + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) return; - // trigger the leave event (cancellable) [reason:kicked] - FPlayerLeaveEvent event = new FPlayerLeaveEvent(you, you.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) return; + if (fme == you) { + msg("You cannot kick yourself."); + msg("You might want to: %s", p.cmdBase.cmdLeave.getUseageTemplate(false)); + return; + } - // then make 'em pay (if applicable) - if ( ! payForCommand(Conf.econCostKick, "to kick someone from the faction", "for kicking someone from the faction")) return; + Faction yourFaction = you.getFaction(); - yourFaction.msg("%s kicked %s from the faction! :O", fme.describeTo(yourFaction, true), you.describeTo(yourFaction, true)); - you.msg("%s kicked you from %s! :O", fme.describeTo(you, true), yourFaction.describeTo(you)); - if (yourFaction != myFaction) - { - fme.msg("You kicked %s from the faction %s!", you.describeTo(fme), yourFaction.describeTo(fme)); - } + // players with admin-level "disband" permission can bypass these requirements + if (!Permission.KICK_ANY.has(sender)) { + if (yourFaction != myFaction) { + msg("%s is not a member of %s", you.describeTo(fme, true), myFaction.describeTo(fme)); + return; + } - if (Conf.logFactionKick) - P.p.log((senderIsConsole ? "A console command" : fme.getName())+" kicked "+you.getName()+" from the faction: "+yourFaction.getTag()); + if (you.getRole().value >= fme.getRole().value) { + // TODO add more informative messages. + msg("Your rank is too low to kick this player."); + return; + } - if (you.getRole() == Role.ADMIN) - yourFaction.promoteNewLeader(); + if (!Conf.canLeaveWithNegativePower && you.getPower() < 0) { + msg("You cannot kick that member until their power is positive."); + return; + } + } - yourFaction.deinvite(you); - you.resetFactionData(); - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostKick, "to kick someone from the faction")) return; + + // trigger the leave event (cancellable) [reason:kicked] + FPlayerLeaveEvent event = new FPlayerLeaveEvent(you, you.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) return; + + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostKick, "to kick someone from the faction", "for kicking someone from the faction")) + return; + + yourFaction.msg("%s kicked %s from the faction! :O", fme.describeTo(yourFaction, true), you.describeTo(yourFaction, true)); + you.msg("%s kicked you from %s! :O", fme.describeTo(you, true), yourFaction.describeTo(you)); + if (yourFaction != myFaction) { + fme.msg("You kicked %s from the faction %s!", you.describeTo(fme), yourFaction.describeTo(fme)); + } + + if (Conf.logFactionKick) + P.p.log((senderIsConsole ? "A console command" : fme.getName()) + " kicked " + you.getName() + " from the faction: " + yourFaction.getTag()); + + if (you.getRole() == Role.ADMIN) + yourFaction.promoteNewLeader(); + + yourFaction.deinvite(you); + you.resetFactionData(); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java index 7cb11c17..b5e4273c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java @@ -3,28 +3,26 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.struct.Permission; public class CmdLeave extends FCommand { - - public CmdLeave() - { - super(); - this.aliases.add("leave"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.LEAVE.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - fme.leave(true); - } - + + public CmdLeave() { + super(); + this.aliases.add("leave"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); + + this.permission = Permission.LEAVE.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + fme.leave(true); + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/src/main/java/com/massivecraft/factions/cmd/CmdList.java index eed64c06..56b45f42 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -1,79 +1,76 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; import com.massivecraft.factions.struct.Permission; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; -public class CmdList extends FCommand -{ - - public CmdList() - { - super(); - this.aliases.add("list"); - this.aliases.add("ls"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("page", "1"); - - this.permission = Permission.LIST.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - @Override - public void perform() - { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) return; - - ArrayList factionList = new ArrayList(Factions.i.get()); - factionList.remove(Factions.i.getNone()); - factionList.remove(Factions.i.getSafeZone()); - factionList.remove(Factions.i.getWarZone()); - - // Sort by total followers first - Collections.sort(factionList, new Comparator(){ - @Override - public int compare(Faction f1, Faction f2) { - int f1Size = f1.getFPlayers().size(); - int f2Size = f2.getFPlayers().size(); - if (f1Size < f2Size) - return 1; - else if (f1Size > f2Size) - return -1; - return 0; - } - }); +public class CmdList extends FCommand { - // Then sort by how many members are online now - Collections.sort(factionList, new Comparator(){ - @Override - public int compare(Faction f1, Faction f2) { - int f1Size = f1.getFPlayersWhereOnline(true).size(); - int f2Size = f2.getFPlayersWhereOnline(true).size(); - if (f1Size < f2Size) - return 1; - else if (f1Size > f2Size) - return -1; - return 0; - } - }); - - ArrayList lines = new ArrayList(); + public CmdList() { + super(); + this.aliases.add("list"); + this.aliases.add("ls"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("page", "1"); + + this.permission = Permission.LIST.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) return; + + ArrayList factionList = new ArrayList(Factions.i.get()); + factionList.remove(Factions.i.getNone()); + factionList.remove(Factions.i.getSafeZone()); + factionList.remove(Factions.i.getWarZone()); + + // Sort by total followers first + Collections.sort(factionList, new Comparator() { + @Override + public int compare(Faction f1, Faction f2) { + int f1Size = f1.getFPlayers().size(); + int f2Size = f2.getFPlayers().size(); + if (f1Size < f2Size) + return 1; + else if (f1Size > f2Size) + return -1; + return 0; + } + }); + + // Then sort by how many members are online now + Collections.sort(factionList, new Comparator() { + @Override + public int compare(Faction f1, Faction f2) { + int f1Size = f1.getFPlayersWhereOnline(true).size(); + int f2Size = f2.getFPlayersWhereOnline(true).size(); + if (f1Size < f2Size) + return 1; + else if (f1Size > f2Size) + return -1; + return 0; + } + }); + + ArrayList lines = new ArrayList(); /* // this code was really slow on large servers, getting full info for every faction and then only showing 9 of them; rewritten below - lines.add(p.txt.parse("Factionless %d online", Factions.i.getNone().getFPlayersWhereOnline(true).size())); + lines.add(p.txt.parse("Factionless %d online", Factions.i.getNone().getFPlayersWhereOnline(true).size())); for (Faction faction : factionList) { lines.add(p.txt.parse("%s %d/%d online, %d/%d/%d", @@ -89,39 +86,37 @@ public class CmdList extends FCommand sendMessage(p.txt.getPage(lines, this.argAsInt(0, 1), "Faction List")); */ - factionList.add(0, Factions.i.getNone()); + factionList.add(0, Factions.i.getNone()); - final int pageheight = 9; - int pagenumber = this.argAsInt(0, 1); - int pagecount = (factionList.size() / pageheight) + 1; - if (pagenumber > pagecount) - pagenumber = pagecount; - else if (pagenumber < 1) - pagenumber = 1; - int start = (pagenumber - 1) * pageheight; - int end = start + pageheight; - if (end > factionList.size()) - end = factionList.size(); + final int pageheight = 9; + int pagenumber = this.argAsInt(0, 1); + int pagecount = (factionList.size() / pageheight) + 1; + if (pagenumber > pagecount) + pagenumber = pagecount; + else if (pagenumber < 1) + pagenumber = 1; + int start = (pagenumber - 1) * pageheight; + int end = start + pageheight; + if (end > factionList.size()) + end = factionList.size(); - lines.add(p.txt.titleize("Faction List "+pagenumber+"/"+pagecount)); + lines.add(p.txt.titleize("Faction List " + pagenumber + "/" + pagecount)); - for (Faction faction : factionList.subList(start, end)) - { - if (faction.isNone()) - { - lines.add(p.txt.parse("Factionless %d online", Factions.i.getNone().getFPlayersWhereOnline(true).size())); - continue; - } - lines.add(p.txt.parse("%s %d/%d online, %d/%d/%d", - faction.getTag(fme), - faction.getFPlayersWhereOnline(true).size(), - faction.getFPlayers().size(), - faction.getLandRounded(), - faction.getPowerRounded(), - faction.getPowerMaxRounded()) - ); - } + for (Faction faction : factionList.subList(start, end)) { + if (faction.isNone()) { + lines.add(p.txt.parse("Factionless %d online", Factions.i.getNone().getFPlayersWhereOnline(true).size())); + continue; + } + lines.add(p.txt.parse("%s %d/%d online, %d/%d/%d", + faction.getTag(fme), + faction.getFPlayersWhereOnline(true).size(), + faction.getFPlayers().size(), + faction.getLandRounded(), + faction.getPowerRounded(), + faction.getPowerMaxRounded()) + ); + } - sendMessage(lines); - } + sendMessage(lines); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java index 4983af6d..aadf09c9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java @@ -3,44 +3,39 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.struct.Permission; public class CmdLock extends FCommand { - - // TODO: This solution needs refactoring. - /* + + // TODO: This solution needs refactoring. + /* factions.lock: description: use the /f lock [on/off] command to temporarily lock the data files from being overwritten default: op */ - - public CmdLock() - { - super(); - this.aliases.add("lock"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); - - this.permission = Permission.LOCK.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - p.setLocked(this.argAsBool(0, ! p.getLocked())); - - if( p.getLocked()) - { - msg("Factions is now locked"); - } - else - { - msg("Factions in now unlocked"); - } - } - + + public CmdLock() { + super(); + this.aliases.add("lock"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); + + this.permission = Permission.LOCK.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + p.setLocked(this.argAsBool(0, !p.getLocked())); + + if (p.getLocked()) { + msg("Factions is now locked"); + } else { + msg("Factions in now unlocked"); + } + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java index aac8ac11..76448efc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java @@ -6,62 +6,52 @@ import com.massivecraft.factions.FLocation; import com.massivecraft.factions.struct.Permission; -public class CmdMap extends FCommand -{ - public CmdMap() - { - super(); - this.aliases.add("map"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "once"); - - this.permission = Permission.MAP.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - if (this.argIsSet(0)) - { - if (this.argAsBool(0, ! fme.isMapAutoUpdating())) - { - // Turn on +public class CmdMap extends FCommand { + public CmdMap() { + super(); + this.aliases.add("map"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) return; + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "once"); - fme.setMapAutoUpdating(true); - msg("Map auto update ENABLED."); - - // And show the map once - showMap(); - } - else - { - // Turn off - fme.setMapAutoUpdating(false); - msg("Map auto update DISABLED."); - } - } - else - { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) return; + this.permission = Permission.MAP.node; + this.disableOnLock = false; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + if (this.argIsSet(0)) { + if (this.argAsBool(0, !fme.isMapAutoUpdating())) { + // Turn on + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) return; + + fme.setMapAutoUpdating(true); + msg("Map auto update ENABLED."); + + // And show the map once + showMap(); + } else { + // Turn off + fme.setMapAutoUpdating(false); + msg("Map auto update DISABLED."); + } + } else { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) return; + + showMap(); + } + } + + public void showMap() { + sendMessage(Board.getMap(myFaction, new FLocation(fme), fme.getPlayer().getLocation().getYaw())); + } - showMap(); - } - } - - public void showMap() - { - sendMessage(Board.getMap(myFaction, new FLocation(fme), fme.getPlayer().getLocation().getYaw())); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java index 48f08c38..3185cbca 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -1,77 +1,67 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.Faction; import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; -public class CmdMod extends FCommand -{ - - public CmdMod() - { - super(); - this.aliases.add("mod"); - - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.MOD.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) return; +public class CmdMod extends FCommand { - boolean permAny = Permission.MOD_ANY.has(sender, false); - Faction targetFaction = you.getFaction(); + public CmdMod() { + super(); + this.aliases.add("mod"); - if (targetFaction != myFaction && !permAny) - { - msg("%s is not a member in your faction.", you.describeTo(fme, true)); - return; - } + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); - if (fme != null && fme.getRole() != Role.ADMIN && !permAny) - { - msg("You are not the faction admin."); - return; - } + this.permission = Permission.MOD.node; + this.disableOnLock = true; - if (you == fme && !permAny) - { - msg("The target player musn't be yourself."); - return; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - if (you.getRole() == Role.ADMIN) - { - msg("The target player is a faction admin. Demote them first."); - return; - } + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) return; + + boolean permAny = Permission.MOD_ANY.has(sender, false); + Faction targetFaction = you.getFaction(); + + if (targetFaction != myFaction && !permAny) { + msg("%s is not a member in your faction.", you.describeTo(fme, true)); + return; + } + + if (fme != null && fme.getRole() != Role.ADMIN && !permAny) { + msg("You are not the faction admin."); + return; + } + + if (you == fme && !permAny) { + msg("The target player musn't be yourself."); + return; + } + + if (you.getRole() == Role.ADMIN) { + msg("The target player is a faction admin. Demote them first."); + return; + } + + if (you.getRole() == Role.MODERATOR) { + // Revoke + you.setRole(Role.NORMAL); + targetFaction.msg("%s is no longer moderator in your faction.", you.describeTo(targetFaction, true)); + msg("You have removed moderator status from %s.", you.describeTo(fme, true)); + } else { + // Give + you.setRole(Role.MODERATOR); + targetFaction.msg("%s was promoted to moderator in your faction.", you.describeTo(targetFaction, true)); + msg("You have promoted %s to moderator.", you.describeTo(fme, true)); + } + } - if (you.getRole() == Role.MODERATOR) - { - // Revoke - you.setRole(Role.NORMAL); - targetFaction.msg("%s is no longer moderator in your faction.", you.describeTo(targetFaction, true)); - msg("You have removed moderator status from %s.", you.describeTo(fme, true)); - } - else - { - // Give - you.setRole(Role.MODERATOR); - targetFaction.msg("%s was promoted to moderator in your faction.", you.describeTo(targetFaction, true)); - msg("You have promoted %s to moderator.", you.describeTo(fme, true)); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java index d7762079..ea7f81c3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java @@ -2,46 +2,43 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.P; -public class CmdMoney extends FCommand -{ - public CmdMoneyBalance cmdMoneyBalance = new CmdMoneyBalance(); - public CmdMoneyDeposit cmdMoneyDeposit = new CmdMoneyDeposit(); - public CmdMoneyWithdraw cmdMoneyWithdraw = new CmdMoneyWithdraw(); - public CmdMoneyTransferFf cmdMoneyTransferFf = new CmdMoneyTransferFf(); - public CmdMoneyTransferFp cmdMoneyTransferFp = new CmdMoneyTransferFp(); - public CmdMoneyTransferPf cmdMoneyTransferPf = new CmdMoneyTransferPf(); - - public CmdMoney() - { - super(); - this.aliases.add("money"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("","") - - this.isMoneyCommand = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - - this.setHelpShort("faction money commands"); - this.helpLong.add(p.txt.parseTags("The faction money commands.")); - - this.addSubCommand(this.cmdMoneyBalance); - this.addSubCommand(this.cmdMoneyDeposit); - this.addSubCommand(this.cmdMoneyWithdraw); - this.addSubCommand(this.cmdMoneyTransferFf); - this.addSubCommand(this.cmdMoneyTransferFp); - this.addSubCommand(this.cmdMoneyTransferPf); - } - - @Override - public void perform() - { - this.commandChain.add(this); - P.p.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); - } - +public class CmdMoney extends FCommand { + public CmdMoneyBalance cmdMoneyBalance = new CmdMoneyBalance(); + public CmdMoneyDeposit cmdMoneyDeposit = new CmdMoneyDeposit(); + public CmdMoneyWithdraw cmdMoneyWithdraw = new CmdMoneyWithdraw(); + public CmdMoneyTransferFf cmdMoneyTransferFf = new CmdMoneyTransferFf(); + public CmdMoneyTransferFp cmdMoneyTransferFp = new CmdMoneyTransferFp(); + public CmdMoneyTransferPf cmdMoneyTransferPf = new CmdMoneyTransferPf(); + + public CmdMoney() { + super(); + this.aliases.add("money"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("","") + + this.isMoneyCommand = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + + this.setHelpShort("faction money commands"); + this.helpLong.add(p.txt.parseTags("The faction money commands.")); + + this.addSubCommand(this.cmdMoneyBalance); + this.addSubCommand(this.cmdMoneyDeposit); + this.addSubCommand(this.cmdMoneyWithdraw); + this.addSubCommand(this.cmdMoneyTransferFf); + this.addSubCommand(this.cmdMoneyTransferFp); + this.addSubCommand(this.cmdMoneyTransferPf); + } + + @Override + public void perform() { + this.commandChain.add(this); + P.p.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java index cbbbad09..c12f09d2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java @@ -1,42 +1,38 @@ package com.massivecraft.factions.cmd; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.Faction; -public class CmdMoneyBalance extends FCommand -{ - public CmdMoneyBalance() - { - super(); - this.aliases.add("b"); - this.aliases.add("balance"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "yours"); - - this.permission = Permission.MONEY_BALANCE.node; - this.setHelpShort("show faction balance"); - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction faction = myFaction; - if (this.argIsSet(0)) - { - faction = this.argAsFaction(0); - } - - if (faction == null) return; - if (faction != myFaction && ! Permission.MONEY_BALANCE_ANY.has(sender, true)) return; - - Econ.sendBalanceInfo(fme, faction); - } - +public class CmdMoneyBalance extends FCommand { + public CmdMoneyBalance() { + super(); + this.aliases.add("b"); + this.aliases.add("balance"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "yours"); + + this.permission = Permission.MONEY_BALANCE.node; + this.setHelpShort("show faction balance"); + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction faction = myFaction; + if (this.argIsSet(0)) { + faction = this.argAsFaction(0); + } + + if (faction == null) return; + if (faction != myFaction && !Permission.MONEY_BALANCE_ANY.has(sender, true)) return; + + Econ.sendBalanceInfo(fme, faction); + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java index a31cf6db..c5d48383 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java @@ -5,41 +5,37 @@ import com.massivecraft.factions.P; import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; - import org.bukkit.ChatColor; -public class CmdMoneyDeposit extends FCommand -{ - - public CmdMoneyDeposit() - { - super(); - this.aliases.add("d"); - this.aliases.add("deposit"); - - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); - - this.permission = Permission.MONEY_DEPOSIT.node; - this.setHelpShort("deposit money"); - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) return; - boolean success = Econ.transferMoney(fme, fme, faction, amount); +public class CmdMoneyDeposit extends FCommand { + + public CmdMoneyDeposit() { + super(); + this.aliases.add("d"); + this.aliases.add("deposit"); + + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); + + this.permission = Permission.MONEY_DEPOSIT.node; + this.setHelpShort("deposit money"); + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) return; + boolean success = Econ.transferMoney(fme, fme, faction, amount); + + if (success && Conf.logMoneyTransactions) + P.p.log(ChatColor.stripColor(P.p.txt.parse("%s deposited %s in the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } - if (success && Conf.logMoneyTransactions) - P.p.log(ChatColor.stripColor(P.p.txt.parse("%s deposited %s in the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java index 987061c5..1bd147a7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java @@ -1,47 +1,43 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; -import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.P; +import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; - import org.bukkit.ChatColor; -public class CmdMoneyTransferFf extends FCommand -{ - public CmdMoneyTransferFf() - { - this.aliases.add("ff"); - - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("faction"); - - //this.optionalArgs.put("", ""); - - this.permission = Permission.MONEY_F2F.node; - this.setHelpShort("transfer f -> f"); - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) return; - EconomyParticipator to = this.argAsFaction(2); - if (to == null) return; - - boolean success = Econ.transferMoney(fme, from, to, amount); +public class CmdMoneyTransferFf extends FCommand { + public CmdMoneyTransferFf() { + this.aliases.add("ff"); - if (success && Conf.logMoneyTransactions) - P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the faction \"%s\" to the faction \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("faction"); + + //this.optionalArgs.put("", ""); + + this.permission = Permission.MONEY_F2F.node; + this.setHelpShort("transfer f -> f"); + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsFaction(1); + if (from == null) return; + EconomyParticipator to = this.argAsFaction(2); + if (to == null) return; + + boolean success = Econ.transferMoney(fme, from, to, amount); + + if (success && Conf.logMoneyTransactions) + P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the faction \"%s\" to the faction \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java index 97ad8336..cbe84701 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java @@ -1,47 +1,43 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; -import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.P; +import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; - import org.bukkit.ChatColor; -public class CmdMoneyTransferFp extends FCommand -{ - public CmdMoneyTransferFp() - { - this.aliases.add("fp"); - - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("player"); - - //this.optionalArgs.put("", ""); - - this.permission = Permission.MONEY_F2P.node; - this.setHelpShort("transfer f -> p"); - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) return; - EconomyParticipator to = this.argAsBestFPlayerMatch(2); - if (to == null) return; - - boolean success = Econ.transferMoney(fme, from, to, amount); +public class CmdMoneyTransferFp extends FCommand { + public CmdMoneyTransferFp() { + this.aliases.add("fp"); - if (success && Conf.logMoneyTransactions) - P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the faction \"%s\" to the player \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("player"); + + //this.optionalArgs.put("", ""); + + this.permission = Permission.MONEY_F2P.node; + this.setHelpShort("transfer f -> p"); + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsFaction(1); + if (from == null) return; + EconomyParticipator to = this.argAsBestFPlayerMatch(2); + if (to == null) return; + + boolean success = Econ.transferMoney(fme, from, to, amount); + + if (success && Conf.logMoneyTransactions) + P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the faction \"%s\" to the player \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java index bcc65538..704bb5b9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java @@ -1,47 +1,43 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; -import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.P; +import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; - import org.bukkit.ChatColor; -public class CmdMoneyTransferPf extends FCommand -{ - public CmdMoneyTransferPf() - { - this.aliases.add("pf"); - - this.requiredArgs.add("amount"); - this.requiredArgs.add("player"); - this.requiredArgs.add("faction"); - - //this.optionalArgs.put("", ""); - - this.permission = Permission.MONEY_P2F.node; - this.setHelpShort("transfer p -> f"); - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsBestFPlayerMatch(1); - if (from == null) return; - EconomyParticipator to = this.argAsFaction(2); - if (to == null) return; - - boolean success = Econ.transferMoney(fme, from, to, amount); +public class CmdMoneyTransferPf extends FCommand { + public CmdMoneyTransferPf() { + this.aliases.add("pf"); - if (success && Conf.logMoneyTransactions) - P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the player \"%s\" to the faction \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } + this.requiredArgs.add("amount"); + this.requiredArgs.add("player"); + this.requiredArgs.add("faction"); + + //this.optionalArgs.put("", ""); + + this.permission = Permission.MONEY_P2F.node; + this.setHelpShort("transfer p -> f"); + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsBestFPlayerMatch(1); + if (from == null) return; + EconomyParticipator to = this.argAsFaction(2); + if (to == null) return; + + boolean success = Econ.transferMoney(fme, from, to, amount); + + if (success && Conf.logMoneyTransactions) + P.p.log(ChatColor.stripColor(P.p.txt.parse("%s transferred %s from the player \"%s\" to the faction \"%s\"", fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java index 65aab653..daf7f21c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java @@ -1,42 +1,38 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.Conf; -import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.P; +import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; - import org.bukkit.ChatColor; -public class CmdMoneyWithdraw extends FCommand -{ - public CmdMoneyWithdraw() - { - this.aliases.add("w"); - this.aliases.add("withdraw"); - - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); - - this.permission = Permission.MONEY_WITHDRAW.node; - this.setHelpShort("withdraw money"); - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) return; - boolean success = Econ.transferMoney(fme, faction, fme, amount); +public class CmdMoneyWithdraw extends FCommand { + public CmdMoneyWithdraw() { + this.aliases.add("w"); + this.aliases.add("withdraw"); - if (success && Conf.logMoneyTransactions) - P.p.log(ChatColor.stripColor(P.p.txt.parse("%s withdrew %s from the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); + + this.permission = Permission.MONEY_WITHDRAW.node; + this.setHelpShort("withdraw money"); + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) return; + boolean success = Econ.transferMoney(fme, faction, fme, amount); + + if (success && Conf.logMoneyTransactions) + P.p.log(ChatColor.stripColor(P.p.txt.parse("%s withdrew %s from the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java index fac92821..e052f371 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -5,45 +5,41 @@ import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; import com.massivecraft.factions.struct.Permission; -public class CmdOpen extends FCommand -{ - public CmdOpen() - { - super(); - this.aliases.add("open"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("yes/no", "flip"); - - this.permission = Permission.OPEN.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostOpen, "to open or close the faction", "for opening or closing the faction")) return; +public class CmdOpen extends FCommand { + public CmdOpen() { + super(); + this.aliases.add("open"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("yes/no", "flip"); + + this.permission = Permission.OPEN.node; + this.disableOnLock = false; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostOpen, "to open or close the faction", "for opening or closing the faction")) + return; + + myFaction.setOpen(this.argAsBool(0, !myFaction.getOpen())); + + String open = myFaction.getOpen() ? "open" : "closed"; + + // Inform + myFaction.msg("%s changed the faction to %s.", fme.describeTo(myFaction, true), open); + for (Faction faction : Factions.i.get()) { + if (faction == myFaction) { + continue; + } + faction.msg("The faction %s is now %s", myFaction.getTag(faction), open); + } + } - myFaction.setOpen(this.argAsBool(0, ! myFaction.getOpen())); - - String open = myFaction.getOpen() ? "open" : "closed"; - - // Inform - myFaction.msg("%s changed the faction to %s.", fme.describeTo(myFaction, true), open); - for (Faction faction : Factions.i.get()) - { - if (faction == myFaction) - { - continue; - } - faction.msg("The faction %s is now %s", myFaction.getTag(faction), open); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java index 4b8636d5..bfedaade 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java @@ -1,115 +1,100 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.*; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; -public class CmdOwner extends FCommand -{ - - public CmdOwner() - { - super(); - this.aliases.add("owner"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("player name", "you"); - - this.permission = Permission.OWNER.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - // TODO: Fix colors! - - @Override - public void perform() - { - boolean hasBypass = fme.isAdminBypassing(); - - if ( ! hasBypass && ! assertHasFaction()) { - return; - } +public class CmdOwner extends FCommand { - if ( ! Conf.ownedAreasEnabled) - { - fme.msg("Sorry, but owned areas are disabled on this server."); - return; - } + public CmdOwner() { + super(); + this.aliases.add("owner"); - if ( ! hasBypass && Conf.ownedAreasLimitPerFaction > 0 && myFaction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) - { - fme.msg("Sorry, but you have reached the server's limit of %d owned areas per faction.", Conf.ownedAreasLimitPerFaction); - return; - } + //this.requiredArgs.add(""); + this.optionalArgs.put("player name", "you"); - if ( ! hasBypass && !assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.ADMIN)) - { - return; - } + this.permission = Permission.OWNER.node; + this.disableOnLock = true; - FLocation flocation = new FLocation(fme); + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - Faction factionHere = Board.getFactionAt(flocation); - if (factionHere != myFaction) - { - if ( ! hasBypass) - { - fme.msg("This land is not claimed by your faction, so you can't set ownership of it."); - return; - } + // TODO: Fix colors! - if ( ! factionHere.isNormal()) - { - fme.msg("This land is not claimed by a faction. Ownership is not possible."); - return; - } - } + @Override + public void perform() { + boolean hasBypass = fme.isAdminBypassing(); - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) return; + if (!hasBypass && !assertHasFaction()) { + return; + } - String playerName = target.getName(); + if (!Conf.ownedAreasEnabled) { + fme.msg("Sorry, but owned areas are disabled on this server."); + return; + } - if (target.getFaction() != myFaction) - { - fme.msg("%s is not a member of this faction.", playerName); - return; - } + if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && myFaction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { + fme.msg("Sorry, but you have reached the server's limit of %d owned areas per faction.", Conf.ownedAreasLimitPerFaction); + return; + } - // if no player name was passed, and this claim does already have owners set, clear them - if (args.isEmpty() && myFaction.doesLocationHaveOwnersSet(flocation)) - { - myFaction.clearClaimOwnership(flocation); - SpoutFeatures.updateOwnerListLoc(flocation); - fme.msg("You have cleared ownership for this claimed area."); - return; - } + if (!hasBypass && !assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.ADMIN)) { + return; + } - if (myFaction.isPlayerInOwnerList(playerName, flocation)) - { - myFaction.removePlayerAsOwner(playerName, flocation); - SpoutFeatures.updateOwnerListLoc(flocation); - fme.msg("You have removed ownership of this claimed land from %s.", playerName); - return; - } + FLocation flocation = new FLocation(fme); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostOwner, "to set ownership of claimed land", "for setting ownership of claimed land")) return; + Faction factionHere = Board.getFactionAt(flocation); + if (factionHere != myFaction) { + if (!hasBypass) { + fme.msg("This land is not claimed by your faction, so you can't set ownership of it."); + return; + } - myFaction.setPlayerAsOwner(playerName, flocation); - SpoutFeatures.updateOwnerListLoc(flocation); + if (!factionHere.isNormal()) { + fme.msg("This land is not claimed by a faction. Ownership is not possible."); + return; + } + } - fme.msg("You have added %s to the owner list for this claimed land.", playerName); - } + FPlayer target = this.argAsBestFPlayerMatch(0, fme); + if (target == null) return; + + String playerName = target.getName(); + + if (target.getFaction() != myFaction) { + fme.msg("%s is not a member of this faction.", playerName); + return; + } + + // if no player name was passed, and this claim does already have owners set, clear them + if (args.isEmpty() && myFaction.doesLocationHaveOwnersSet(flocation)) { + myFaction.clearClaimOwnership(flocation); + SpoutFeatures.updateOwnerListLoc(flocation); + fme.msg("You have cleared ownership for this claimed area."); + return; + } + + if (myFaction.isPlayerInOwnerList(playerName, flocation)) { + myFaction.removePlayerAsOwner(playerName, flocation); + SpoutFeatures.updateOwnerListLoc(flocation); + fme.msg("You have removed ownership of this claimed land from %s.", playerName); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostOwner, "to set ownership of claimed land", "for setting ownership of claimed land")) + return; + + myFaction.setPlayerAsOwner(playerName, flocation); + SpoutFeatures.updateOwnerListLoc(flocation); + + fme.msg("You have added %s to the owner list for this claimed land.", playerName); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java index f7c39efc..a749453b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java @@ -6,68 +6,59 @@ import com.massivecraft.factions.FLocation; import com.massivecraft.factions.struct.Permission; -public class CmdOwnerList extends FCommand -{ - - public CmdOwnerList() - { - super(); - this.aliases.add("ownerlist"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.OWNERLIST.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - boolean hasBypass = fme.isAdminBypassing(); +public class CmdOwnerList extends FCommand { - if ( ! hasBypass && ! assertHasFaction()) - { - return; - } + public CmdOwnerList() { + super(); + this.aliases.add("ownerlist"); - if ( ! Conf.ownedAreasEnabled) - { - fme.msg("Owned areas are disabled on this server."); - return; - } + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - FLocation flocation = new FLocation(fme); + this.permission = Permission.OWNERLIST.node; + this.disableOnLock = false; - if (Board.getFactionAt(flocation) != myFaction) - { - if (!hasBypass) - { - fme.msg("This land is not claimed by your faction."); - return; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - myFaction = Board.getFactionAt(flocation); - if (!myFaction.isNormal()) - { - fme.msg("This land is not claimed by any faction, thus no owners."); - return; - } - } + @Override + public void perform() { + boolean hasBypass = fme.isAdminBypassing(); - String owners = myFaction.getOwnerListString(flocation); + if (!hasBypass && !assertHasFaction()) { + return; + } - if (owners == null || owners.isEmpty()) - { - fme.msg("No owners are set here; everyone in the faction has access."); - return; - } + if (!Conf.ownedAreasEnabled) { + fme.msg("Owned areas are disabled on this server."); + return; + } - fme.msg("Current owner(s) of this land: %s", owners); - } + FLocation flocation = new FLocation(fme); + + if (Board.getFactionAt(flocation) != myFaction) { + if (!hasBypass) { + fme.msg("This land is not claimed by your faction."); + return; + } + + myFaction = Board.getFactionAt(flocation); + if (!myFaction.isNormal()) { + fme.msg("This land is not claimed by any faction, thus no owners."); + return; + } + } + + String owners = myFaction.getOwnerListString(flocation); + + if (owners == null || owners.isEmpty()) { + fme.msg("No owners are set here; everyone in the faction has access."); + return; + } + + fme.msg("Current owner(s) of this land: %s", owners); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java index 0750996f..3ad738f1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java @@ -1,63 +1,53 @@ package com.massivecraft.factions.cmd; +import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; -public class CmdPeaceful extends FCommand -{ - - public CmdPeaceful() - { - super(); - this.aliases.add("peaceful"); - - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.SET_PEACEFUL.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction faction = this.argAsFaction(0); - if (faction == null) return; +public class CmdPeaceful extends FCommand { - String change; - if (faction.isPeaceful()) - { - change = "removed peaceful status from"; - faction.setPeaceful(false); - } - else - { - change = "granted peaceful status to"; - faction.setPeaceful(true); - } - - // Inform all players - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - if (fplayer.getFaction() == faction) - { - fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true))+" has "+change+" your faction."); - } - else - { - fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true))+" has "+change+" the faction \"" + faction.getTag(fplayer) + "\"."); - } - } + public CmdPeaceful() { + super(); + this.aliases.add("peaceful"); + + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); + + this.permission = Permission.SET_PEACEFUL.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) return; + + String change; + if (faction.isPeaceful()) { + change = "removed peaceful status from"; + faction.setPeaceful(false); + } else { + change = "granted peaceful status to"; + faction.setPeaceful(true); + } + + // Inform all players + for (FPlayer fplayer : FPlayers.i.getOnline()) { + if (fplayer.getFaction() == faction) { + fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " has " + change + " your faction."); + } else { + fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " has " + change + " the faction \"" + faction.getTag(fplayer) + "\"."); + } + } + + SpoutFeatures.updateAppearances(faction); + } - SpoutFeatures.updateAppearances(faction); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java index fd6efcc2..d341a619 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java @@ -1,62 +1,52 @@ package com.massivecraft.factions.cmd; +import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdPermanent extends FCommand -{ - public CmdPermanent() - { - super(); - this.aliases.add("permanent"); - - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.SET_PERMANENT.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction faction = this.argAsFaction(0); - if (faction == null) return; - - String change; - if(faction.isPermanent()) - { - change = "removed permanent status from"; - faction.setPermanent(false); - } - else - { - change = "added permanent status to"; - faction.setPermanent(true); - } +public class CmdPermanent extends FCommand { + public CmdPermanent() { + super(); + this.aliases.add("permanent"); - P.p.log((fme == null ? "A server admin" : fme.getName())+" "+change+" the faction \"" + faction.getTag() + "\"."); - - // Inform all players - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - if (fplayer.getFaction() == faction) - { - fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true))+" "+change+" your faction."); - } - else - { - fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true))+" "+change+" the faction \"" + faction.getTag(fplayer) + "\"."); - } - } - } + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); + + this.permission = Permission.SET_PERMANENT.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) return; + + String change; + if (faction.isPermanent()) { + change = "removed permanent status from"; + faction.setPermanent(false); + } else { + change = "added permanent status to"; + faction.setPermanent(true); + } + + P.p.log((fme == null ? "A server admin" : fme.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); + + // Inform all players + for (FPlayer fplayer : FPlayers.i.getOnline()) { + if (fplayer.getFaction() == faction) { + fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " " + change + " your faction."); + } else { + fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " " + change + " the faction \"" + faction.getTag(fplayer) + "\"."); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java index ff275c26..4d3543d2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java @@ -1,50 +1,45 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.Faction; import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.struct.Permission; -public class CmdPermanentPower extends FCommand -{ - public CmdPermanentPower() - { - super(); - this.aliases.add("permanentpower"); - - this.requiredArgs.add("faction"); - this.optionalArgs.put("power", "reset"); - - this.permission = Permission.SET_PERMANENTPOWER.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction targetFaction = this.argAsFaction(0); - if (targetFaction == null) return; - - Integer targetPower = this.argAsInt(1); - - targetFaction.setPermanentPower(targetPower); - - String change = "removed permanentpower status from"; - if(targetFaction.hasPermanentPower()) - { - change = "added permanentpower status to"; - } - - msg("You %s %s.", change, targetFaction.describeTo(fme)); - - // Inform all players - for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) - { - fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true))+" "+change+" your faction."); - } - } +public class CmdPermanentPower extends FCommand { + public CmdPermanentPower() { + super(); + this.aliases.add("permanentpower"); + + this.requiredArgs.add("faction"); + this.optionalArgs.put("power", "reset"); + + this.permission = Permission.SET_PERMANENTPOWER.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction targetFaction = this.argAsFaction(0); + if (targetFaction == null) return; + + Integer targetPower = this.argAsInt(1); + + targetFaction.setPermanentPower(targetPower); + + String change = "removed permanentpower status from"; + if (targetFaction.hasPermanentPower()) { + change = "added permanentpower status to"; + } + + msg("You %s %s.", change, targetFaction.describeTo(fme)); + + // Inform all players + for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { + fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " " + change + " your faction."); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java index c4c2998b..71af37fb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java @@ -4,41 +4,38 @@ import com.massivecraft.factions.Conf; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.struct.Permission; -public class CmdPower extends FCommand -{ - - public CmdPower() - { - super(); - this.aliases.add("power"); - this.aliases.add("pow"); - - //this.requiredArgs.add("faction tag"); - this.optionalArgs.put("player name", "you"); - - this.permission = Permission.POWER.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) return; - - if (target != fme && ! Permission.POWER_ANY.has(sender, true)) return; +public class CmdPower extends FCommand { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostPower, "to show player power info", "for showing player power info")) return; + public CmdPower() { + super(); + this.aliases.add("power"); + this.aliases.add("pow"); + + //this.requiredArgs.add("faction tag"); + this.optionalArgs.put("player name", "you"); + + this.permission = Permission.POWER.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayer target = this.argAsBestFPlayerMatch(0, fme); + if (target == null) return; + + if (target != fme && !Permission.POWER_ANY.has(sender, true)) return; + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostPower, "to show player power info", "for showing player power info")) return; + + double powerBoost = target.getPowerBoost(); + String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? " (bonus: " : " (penalty: ") + powerBoost + ")"; + msg("%s - Power / Maxpower: %d / %d %s", target.describeTo(fme, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); + } - double powerBoost = target.getPowerBoost(); - String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? " (bonus: " : " (penalty: ") + powerBoost + ")"; - msg("%s - Power / Maxpower: %d / %d %s", target.describeTo(fme, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java index 7ec50e28..d0a06d5d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java @@ -1,72 +1,62 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.Faction; import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdPowerBoost extends FCommand -{ - public CmdPowerBoost() - { - super(); - this.aliases.add("powerboost"); - - this.requiredArgs.add("p|f|player|faction"); - this.requiredArgs.add("name"); - this.requiredArgs.add("#"); - - this.permission = Permission.POWERBOOST.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - String type = this.argAsString(0).toLowerCase(); - boolean doPlayer = true; - if (type.equals("f") || type.equals("faction")) - { - doPlayer = false; - } - else if (!type.equals("p") && !type.equals("player")) - { - msg("You must specify \"p\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."); - msg("ex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"); - return; - } - - Double targetPower = this.argAsDouble(2); - if (targetPower == null) - { - msg("You must specify a valid numeric value for the power bonus/penalty amount."); - return; - } +public class CmdPowerBoost extends FCommand { + public CmdPowerBoost() { + super(); + this.aliases.add("powerboost"); - String target; + this.requiredArgs.add("p|f|player|faction"); + this.requiredArgs.add("name"); + this.requiredArgs.add("#"); - if (doPlayer) - { - FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); - if (targetPlayer == null) return; - targetPlayer.setPowerBoost(targetPower); - target = "Player \""+targetPlayer.getName()+"\""; - } - else - { - Faction targetFaction = this.argAsFaction(1); - if (targetFaction == null) return; - targetFaction.setPowerBoost(targetPower); - target = "Faction \""+targetFaction.getTag()+"\""; - } + this.permission = Permission.POWERBOOST.node; + this.disableOnLock = true; - msg(""+target+" now has a power bonus/penalty of "+targetPower+" to min and max power levels."); - if (!senderIsConsole) - P.p.log(fme.getName()+" has set the power bonus/penalty for "+target+" to "+targetPower+"."); - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + String type = this.argAsString(0).toLowerCase(); + boolean doPlayer = true; + if (type.equals("f") || type.equals("faction")) { + doPlayer = false; + } else if (!type.equals("p") && !type.equals("player")) { + msg("You must specify \"p\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."); + msg("ex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"); + return; + } + + Double targetPower = this.argAsDouble(2); + if (targetPower == null) { + msg("You must specify a valid numeric value for the power bonus/penalty amount."); + return; + } + + String target; + + if (doPlayer) { + FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); + if (targetPlayer == null) return; + targetPlayer.setPowerBoost(targetPower); + target = "Player \"" + targetPlayer.getName() + "\""; + } else { + Faction targetFaction = this.argAsFaction(1); + if (targetFaction == null) return; + targetFaction.setPowerBoost(targetPower); + target = "Faction \"" + targetFaction.getTag() + "\""; + } + + msg("" + target + " now has a power bonus/penalty of " + targetPower + " to min and max power levels."); + if (!senderIsConsole) + P.p.log(fme.getName() + " has set the power bonus/penalty for " + target + " to " + targetPower + "."); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java index c8814fa8..fa597730 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java @@ -2,11 +2,9 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.struct.Relation; -public class CmdRelationAlly extends FRelationCommand -{ - public CmdRelationAlly() - { - aliases.add("ally"); - targetRelation = Relation.ALLY; - } +public class CmdRelationAlly extends FRelationCommand { + public CmdRelationAlly() { + aliases.add("ally"); + targetRelation = Relation.ALLY; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java index 11882bf0..4a22aa00 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java @@ -2,11 +2,9 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.struct.Relation; -public class CmdRelationEnemy extends FRelationCommand -{ - public CmdRelationEnemy() - { - aliases.add("enemy"); - targetRelation = Relation.ENEMY; - } +public class CmdRelationEnemy extends FRelationCommand { + public CmdRelationEnemy() { + aliases.add("enemy"); + targetRelation = Relation.ENEMY; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java index 03b40e19..db340ed6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java @@ -2,11 +2,9 @@ package com.massivecraft.factions.cmd; import com.massivecraft.factions.struct.Relation; -public class CmdRelationNeutral extends FRelationCommand -{ - public CmdRelationNeutral() - { - aliases.add("neutral"); - targetRelation = Relation.NEUTRAL; - } +public class CmdRelationNeutral extends FRelationCommand { + public CmdRelationNeutral() { + aliases.add("neutral"); + targetRelation = Relation.NEUTRAL; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java index 2aae4132..a6bca27e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java @@ -1,78 +1,60 @@ package com.massivecraft.factions.cmd; -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.P; +import com.massivecraft.factions.*; import com.massivecraft.factions.struct.Permission; -public class CmdReload extends FCommand -{ - - public CmdReload() - { - super(); - this.aliases.add("reload"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("file", "all"); - - this.permission = Permission.RELOAD.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - long timeInitStart = System.currentTimeMillis(); - String file = this.argAsString(0, "all").toLowerCase(); - - String fileName; - - if (file.startsWith("c")) - { - Conf.load(); - fileName = "conf.json"; - } - else if (file.startsWith("b")) - { - Board.load(); - fileName = "board.json"; - } - else if (file.startsWith("f")) - { - Factions.i.loadFromDisc(); - fileName = "factions.json"; - } - else if (file.startsWith("p")) - { - FPlayers.i.loadFromDisc(); - fileName = "players.json"; - } - else if (file.startsWith("a")) - { - fileName = "all"; - Conf.load(); - FPlayers.i.loadFromDisc(); - Factions.i.loadFromDisc(); - Board.load(); - } - else - { - P.p.log("RELOAD CANCELLED - SPECIFIED FILE INVALID"); - msg("Invalid file specified. Valid files: all, conf, board, factions, players"); - return; - } - - long timeReload = (System.currentTimeMillis()-timeInitStart); - - msg("Reloaded %s from disk, took %dms.", fileName, timeReload); - } - +public class CmdReload extends FCommand { + + public CmdReload() { + super(); + this.aliases.add("reload"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("file", "all"); + + this.permission = Permission.RELOAD.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + long timeInitStart = System.currentTimeMillis(); + String file = this.argAsString(0, "all").toLowerCase(); + + String fileName; + + if (file.startsWith("c")) { + Conf.load(); + fileName = "conf.json"; + } else if (file.startsWith("b")) { + Board.load(); + fileName = "board.json"; + } else if (file.startsWith("f")) { + Factions.i.loadFromDisc(); + fileName = "factions.json"; + } else if (file.startsWith("p")) { + FPlayers.i.loadFromDisc(); + fileName = "players.json"; + } else if (file.startsWith("a")) { + fileName = "all"; + Conf.load(); + FPlayers.i.loadFromDisc(); + Factions.i.loadFromDisc(); + Board.load(); + } else { + P.p.log("RELOAD CANCELLED - SPECIFIED FILE INVALID"); + msg("Invalid file specified. Valid files: all, conf, board, factions, players"); + return; + } + + long timeReload = (System.currentTimeMillis() - timeInitStart); + + msg("Reloaded %s from disk, took %dms.", fileName, timeReload); + } + } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java index 08a90c8f..002b329f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java @@ -6,36 +6,33 @@ import com.massivecraft.factions.Factions; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdSafeunclaimall extends FCommand -{ - - public CmdSafeunclaimall() - { - this.aliases.add("safeunclaimall"); - this.aliases.add("safedeclaimall"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("radius", "0"); - - this.permission = Permission.MANAGE_SAFE_ZONE.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - - this.setHelpShort("Unclaim all safezone land"); - } - - @Override - public void perform() - { - Board.unclaimAll(Factions.i.getSafeZone().getId()); - msg("You unclaimed ALL safe zone land."); +public class CmdSafeunclaimall extends FCommand { + + public CmdSafeunclaimall() { + this.aliases.add("safeunclaimall"); + this.aliases.add("safedeclaimall"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("radius", "0"); + + this.permission = Permission.MANAGE_SAFE_ZONE.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + + this.setHelpShort("Unclaim all safezone land"); + } + + @Override + public void perform() { + Board.unclaimAll(Factions.i.getSafeZone().getId()); + msg("You unclaimed ALL safe zone land."); + + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed all safe zones."); + } - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed all safe zones."); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java index bf0e85bd..1316f969 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java @@ -6,35 +6,32 @@ import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Factions; import com.massivecraft.factions.struct.Permission; -public class CmdSaveAll extends FCommand -{ - - public CmdSaveAll() - { - super(); - this.aliases.add("saveall"); - this.aliases.add("save"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.SAVE.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayers.i.saveToDisc(); - Factions.i.saveToDisc(); - Board.save(); - Conf.save(); - msg("Factions saved to disk!"); - } - +public class CmdSaveAll extends FCommand { + + public CmdSaveAll() { + super(); + this.aliases.add("saveall"); + this.aliases.add("save"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); + + this.permission = Permission.SAVE.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayers.i.saveToDisc(); + Factions.i.saveToDisc(); + Board.save(); + Conf.save(); + msg("Factions saved to disk!"); + } + } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java index 123ff36d..2b9f889f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java @@ -7,71 +7,62 @@ import com.massivecraft.factions.Faction; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; -public class CmdSethome extends FCommand -{ - public CmdSethome() - { - this.aliases.add("sethome"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "mine"); - - this.permission = Permission.SETHOME.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - if ( ! Conf.homesEnabled) - { - fme.msg("Sorry, Faction homes are disabled on this server."); - return; - } - - Faction faction = this.argAsFaction(0, myFaction); - if (faction == null) return; - - // Can the player set the home for this faction? - if (faction == myFaction) - { - if ( ! Permission.SETHOME_ANY.has(sender) && ! assertMinRole(Role.MODERATOR)) return; - } - else - { - if ( ! Permission.SETHOME_ANY.has(sender, true)) return; - } - - // Can the player set the faction home HERE? - if - ( - ! Permission.BYPASS.has(me) - && - Conf.homesMustBeInClaimedTerritory - && - Board.getFactionAt(new FLocation(me)) != faction - ) - { - fme.msg("Sorry, your faction home can only be set inside your own claimed territory."); - return; - } +public class CmdSethome extends FCommand { + public CmdSethome() { + this.aliases.add("sethome"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostSethome, "to set the faction home", "for setting the faction home")) return; + //this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "mine"); + + this.permission = Permission.SETHOME.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + if (!Conf.homesEnabled) { + fme.msg("Sorry, Faction homes are disabled on this server."); + return; + } + + Faction faction = this.argAsFaction(0, myFaction); + if (faction == null) return; + + // Can the player set the home for this faction? + if (faction == myFaction) { + if (!Permission.SETHOME_ANY.has(sender) && !assertMinRole(Role.MODERATOR)) return; + } else { + if (!Permission.SETHOME_ANY.has(sender, true)) return; + } + + // Can the player set the faction home HERE? + if + ( + !Permission.BYPASS.has(me) + && + Conf.homesMustBeInClaimedTerritory + && + Board.getFactionAt(new FLocation(me)) != faction + ) { + fme.msg("Sorry, your faction home can only be set inside your own claimed territory."); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostSethome, "to set the faction home", "for setting the faction home")) return; + + faction.setHome(me.getLocation()); + + faction.msg("%s set the home for your faction. You can now use:", fme.describeTo(myFaction, true)); + faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); + if (faction != myFaction) { + fme.msg("You have set the home for the " + faction.getTag(fme) + " faction."); + } + } - faction.setHome(me.getLocation()); - - faction.msg("%s set the home for your faction. You can now use:", fme.describeTo(myFaction, true)); - faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); - if (faction != myFaction) - { - fme.msg("You have set the home for the "+faction.getTag(fme)+" faction."); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java index 2cfaeab7..9fc7ccee 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java @@ -1,165 +1,150 @@ package com.massivecraft.factions.cmd; -import java.util.Collection; - import com.massivecraft.factions.Conf; -import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; +import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Relation; +import com.massivecraft.factions.struct.Role; -public class CmdShow extends FCommand -{ - - public CmdShow() - { - this.aliases.add("show"); - this.aliases.add("who"); - - //this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "yours"); - - this.permission = Permission.SHOW.node; - this.disableOnLock = false; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } +import java.util.Collection; - @Override - public void perform() - { - Faction faction = myFaction; - if (this.argIsSet(0)) - { - faction = this.argAsFaction(0); - if (faction == null) return; - } +public class CmdShow extends FCommand { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostShow, "to show faction information", "for showing faction information")) return; + public CmdShow() { + this.aliases.add("show"); + this.aliases.add("who"); - Collection admins = faction.getFPlayersWhereRole(Role.ADMIN); - Collection mods = faction.getFPlayersWhereRole(Role.MODERATOR); - Collection normals = faction.getFPlayersWhereRole(Role.NORMAL); - - msg(p.txt.titleize(faction.getTag(fme))); - msg("Description: %s", faction.getDescription()); - if ( ! faction.isNormal()) - { - return; - } - - String peaceStatus = ""; - if (faction.isPeaceful()) - { - peaceStatus = " "+Conf.colorNeutral+"This faction is Peaceful"; - } - - msg("Joining: "+(faction.getOpen() ? "no invitation is needed" : "invitation is required")+peaceStatus); + //this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "yours"); - double powerBoost = faction.getPowerBoost(); - String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? " (bonus: " : " (penalty: ") + powerBoost + ")"; - msg("Land / Power / Maxpower: %d/%d/%d %s", faction.getLandRounded(), faction.getPowerRounded(), faction.getPowerMaxRounded(), boost); + this.permission = Permission.SHOW.node; + this.disableOnLock = false; - if (faction.isPermanent()) - { - msg("This faction is permanent, remaining even with no members."); - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - // show the land value - if (Econ.shouldBeUsed()) - { - double value = Econ.calculateTotalLandValue(faction.getLandRounded()); - double refund = value * Conf.econClaimRefundMultiplier; - if (value > 0) - { - String stringValue = Econ.moneyString(value); - String stringRefund = (refund > 0.0) ? (" ("+Econ.moneyString(refund)+" depreciated)") : ""; - msg("Total land value: " + stringValue + stringRefund); - } - - //Show bank contents - if(Conf.bankEnabled) { - msg("Bank contains: "+Econ.moneyString(Econ.getBalance(faction.getAccountId()))); - } - } + @Override + public void perform() { + Faction faction = myFaction; + if (this.argIsSet(0)) { + faction = this.argAsFaction(0); + if (faction == null) return; + } - String listpart; - - // List relation - String allyList = p.txt.parse("Allies: "); - String enemyList = p.txt.parse("Enemies: "); - for (Faction otherFaction : Factions.i.get()) - { - if (otherFaction == faction) continue; + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostShow, "to show faction information", "for showing faction information")) return; - Relation rel = otherFaction.getRelationTo(faction); - if ( ! rel.isAlly() && ! rel.isEnemy()) continue; // if not ally or enemy, drop out now so we're not wasting time on it; good performance boost + Collection admins = faction.getFPlayersWhereRole(Role.ADMIN); + Collection mods = faction.getFPlayersWhereRole(Role.MODERATOR); + Collection normals = faction.getFPlayersWhereRole(Role.NORMAL); + + msg(p.txt.titleize(faction.getTag(fme))); + msg("Description: %s", faction.getDescription()); + if (!faction.isNormal()) { + return; + } + + String peaceStatus = ""; + if (faction.isPeaceful()) { + peaceStatus = " " + Conf.colorNeutral + "This faction is Peaceful"; + } + + msg("Joining: " + (faction.getOpen() ? "no invitation is needed" : "invitation is required") + peaceStatus); + + double powerBoost = faction.getPowerBoost(); + String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? " (bonus: " : " (penalty: ") + powerBoost + ")"; + msg("Land / Power / Maxpower: %d/%d/%d %s", faction.getLandRounded(), faction.getPowerRounded(), faction.getPowerMaxRounded(), boost); + + if (faction.isPermanent()) { + msg("This faction is permanent, remaining even with no members."); + } + + // show the land value + if (Econ.shouldBeUsed()) { + double value = Econ.calculateTotalLandValue(faction.getLandRounded()); + double refund = value * Conf.econClaimRefundMultiplier; + if (value > 0) { + String stringValue = Econ.moneyString(value); + String stringRefund = (refund > 0.0) ? (" (" + Econ.moneyString(refund) + " depreciated)") : ""; + msg("Total land value: " + stringValue + stringRefund); + } + + //Show bank contents + if (Conf.bankEnabled) { + msg("Bank contains: " + Econ.moneyString(Econ.getBalance(faction.getAccountId()))); + } + } + + String listpart; + + // List relation + String allyList = p.txt.parse("Allies: "); + String enemyList = p.txt.parse("Enemies: "); + for (Faction otherFaction : Factions.i.get()) { + if (otherFaction == faction) continue; + + Relation rel = otherFaction.getRelationTo(faction); + if (!rel.isAlly() && !rel.isEnemy()) + continue; // if not ally or enemy, drop out now so we're not wasting time on it; good performance boost + + listpart = otherFaction.getTag(fme) + p.txt.parse("") + ", "; + if (rel.isAlly()) + allyList += listpart; + else if (rel.isEnemy()) + enemyList += listpart; + } + if (allyList.endsWith(", ")) + allyList = allyList.substring(0, allyList.length() - 2); + if (enemyList.endsWith(", ")) + enemyList = enemyList.substring(0, enemyList.length() - 2); + + sendMessage(allyList); + sendMessage(enemyList); + + // List the members... + String onlineList = p.txt.parse("") + "Members online: "; + String offlineList = p.txt.parse("") + "Members offline: "; + for (FPlayer follower : admins) { + listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; + if (follower.isOnlineAndVisibleTo(me)) { + onlineList += listpart; + } else { + offlineList += listpart; + } + } + for (FPlayer follower : mods) { + listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; + if + (follower.isOnlineAndVisibleTo(me)) { + onlineList += listpart; + } else { + offlineList += listpart; + } + } + for (FPlayer follower : normals) { + listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; + if (follower.isOnlineAndVisibleTo(me)) { + onlineList += listpart; + } else { + offlineList += listpart; + } + } + + if (onlineList.endsWith(", ")) { + onlineList = onlineList.substring(0, onlineList.length() - 2); + } + if (offlineList.endsWith(", ")) { + offlineList = offlineList.substring(0, offlineList.length() - 2); + } + + sendMessage(onlineList); + sendMessage(offlineList); + } - listpart = otherFaction.getTag(fme)+p.txt.parse("")+", "; - if (rel.isAlly()) - allyList += listpart; - else if (rel.isEnemy()) - enemyList += listpart; - } - if (allyList.endsWith(", ")) - allyList = allyList.substring(0, allyList.length()-2); - if (enemyList.endsWith(", ")) - enemyList = enemyList.substring(0, enemyList.length()-2); - - sendMessage(allyList); - sendMessage(enemyList); - - // List the members... - String onlineList = p.txt.parse("")+"Members online: "; - String offlineList = p.txt.parse("")+"Members offline: "; - for (FPlayer follower : admins) - { - listpart = follower.getNameAndTitle(fme)+p.txt.parse("")+", "; - if (follower.isOnlineAndVisibleTo(me)) - { - onlineList += listpart; - } - else - { - offlineList += listpart; - } - } - for (FPlayer follower : mods) - { - listpart = follower.getNameAndTitle(fme)+p.txt.parse("")+", "; - if - (follower.isOnlineAndVisibleTo(me)) - { - onlineList += listpart; - } else { - offlineList += listpart; - } - } - for (FPlayer follower : normals) { - listpart = follower.getNameAndTitle(fme)+p.txt.parse("")+", "; - if (follower.isOnlineAndVisibleTo(me)) { - onlineList += listpart; - } else { - offlineList += listpart; - } - } - - if (onlineList.endsWith(", ")) { - onlineList = onlineList.substring(0, onlineList.length()-2); - } - if (offlineList.endsWith(", ")) { - offlineList = offlineList.substring(0, offlineList.length()-2); - } - - sendMessage(onlineList); - sendMessage(offlineList); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java index d9132ff6..05446432 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -1,9 +1,5 @@ package com.massivecraft.factions.cmd; -import java.util.ArrayList; - -import org.bukkit.Bukkit; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; @@ -11,75 +7,70 @@ import com.massivecraft.factions.event.FactionRenameEvent; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.util.MiscUtil; +import org.bukkit.Bukkit; -public class CmdTag extends FCommand -{ - - public CmdTag() - { - this.aliases.add("tag"); - - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.TAG.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - String tag = this.argAsString(0); - - // TODO does not first test cover selfcase? - if (Factions.i.isTagTaken(tag) && ! MiscUtil.getComparisonString(tag).equals(myFaction.getComparisonTag())) - { - msg("That tag is already taken"); - return; - } - - ArrayList errors = new ArrayList(); - errors.addAll(Factions.validateTag(tag)); - if (errors.size() > 0) - { - sendMessage(errors); - return; - } +import java.util.ArrayList; - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if ( ! canAffordCommand(Conf.econCostTag, "to change the faction tag")) return; +public class CmdTag extends FCommand { - // trigger the faction rename event (cancellable) - FactionRenameEvent renameEvent = new FactionRenameEvent(fme, tag); - Bukkit.getServer().getPluginManager().callEvent(renameEvent); - if(renameEvent.isCancelled()) return; + public CmdTag() { + this.aliases.add("tag"); - // then make 'em pay (if applicable) - if ( ! payForCommand(Conf.econCostTag, "to change the faction tag", "for changing the faction tag")) return; + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); - String oldtag = myFaction.getTag(); - myFaction.setTag(tag); - - // Inform - myFaction.msg("%s changed your faction tag to %s", fme.describeTo(myFaction, true), myFaction.getTag(myFaction)); - for (Faction faction : Factions.i.get()) - { - if (faction == myFaction) - { - continue; - } - faction.msg("The faction %s changed their name to %s.", fme.getColorTo(faction)+oldtag, myFaction.getTag(faction)); - } + this.permission = Permission.TAG.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + String tag = this.argAsString(0); + + // TODO does not first test cover selfcase? + if (Factions.i.isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(myFaction.getComparisonTag())) { + msg("That tag is already taken"); + return; + } + + ArrayList errors = new ArrayList(); + errors.addAll(Factions.validateTag(tag)); + if (errors.size() > 0) { + sendMessage(errors); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostTag, "to change the faction tag")) return; + + // trigger the faction rename event (cancellable) + FactionRenameEvent renameEvent = new FactionRenameEvent(fme, tag); + Bukkit.getServer().getPluginManager().callEvent(renameEvent); + if (renameEvent.isCancelled()) return; + + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostTag, "to change the faction tag", "for changing the faction tag")) return; + + String oldtag = myFaction.getTag(); + myFaction.setTag(tag); + + // Inform + myFaction.msg("%s changed your faction tag to %s", fme.describeTo(myFaction, true), myFaction.getTag(myFaction)); + for (Faction faction : Factions.i.get()) { + if (faction == myFaction) { + continue; + } + faction.msg("The faction %s changed their name to %s.", fme.getColorTo(faction) + oldtag, myFaction.getTag(faction)); + } + + if (Conf.spoutFactionTagsOverNames) { + SpoutFeatures.updateAppearances(myFaction); + } + } - if (Conf.spoutFactionTagsOverNames) - { - SpoutFeatures.updateAppearances(myFaction); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java index 5cbade02..2541e64f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java @@ -6,47 +6,43 @@ import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TextUtil; -public class CmdTitle extends FCommand -{ - public CmdTitle() - { - this.aliases.add("title"); - - this.requiredArgs.add("player name"); - this.optionalArgs.put("title", ""); - - this.permission = Permission.TITLE.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) return; - - args.remove(0); - String title = TextUtil.implode(args, " "); - - if ( ! canIAdministerYou(fme, you)) return; +public class CmdTitle extends FCommand { + public CmdTitle() { + this.aliases.add("title"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(Conf.econCostTitle, "to change a players title", "for changing a players title")) return; + this.requiredArgs.add("player name"); + this.optionalArgs.put("title", ""); - you.setTitle(title); - - // Inform - myFaction.msg("%s changed a title: %s", fme.describeTo(myFaction, true), you.describeTo(myFaction, true)); + this.permission = Permission.TITLE.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) return; + + args.remove(0); + String title = TextUtil.implode(args, " "); + + if (!canIAdministerYou(fme, you)) return; + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostTitle, "to change a players title", "for changing a players title")) return; + + you.setTitle(title); + + // Inform + myFaction.msg("%s changed a title: %s", fme.describeTo(myFaction, true), you.describeTo(myFaction, true)); + + if (Conf.spoutFactionTitlesOverNames) { + SpoutFeatures.updateAppearances(me); + } + } - if (Conf.spoutFactionTitlesOverNames) - { - SpoutFeatures.updateAppearances(me); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java index 7e3dd65b..73f55bd8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java @@ -1,133 +1,108 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; +import com.massivecraft.factions.*; import com.massivecraft.factions.event.LandUnclaimEvent; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.SpoutFeatures; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; -public class CmdUnclaim extends FCommand -{ - public CmdUnclaim() - { - this.aliases.add("unclaim"); - this.aliases.add("declaim"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.UNCLAIM.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - FLocation flocation = new FLocation(fme); - Faction otherFaction = Board.getFactionAt(flocation); - - if (otherFaction.isSafeZone()) - { - if (Permission.MANAGE_SAFE_ZONE.has(sender)) - { - Board.removeAt(flocation); - SpoutFeatures.updateTerritoryDisplayLoc(flocation); - msg("Safe zone was unclaimed."); +public class CmdUnclaim extends FCommand { + public CmdUnclaim() { + this.aliases.add("unclaim"); + this.aliases.add("declaim"); - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed land at ("+flocation.getCoordString()+") from the faction: "+otherFaction.getTag()); - } - else - { - msg("This is a safe zone. You lack permissions to unclaim."); - } - return; - } - else if (otherFaction.isWarZone()) - { - if (Permission.MANAGE_WAR_ZONE.has(sender)) - { - Board.removeAt(flocation); - SpoutFeatures.updateTerritoryDisplayLoc(flocation); - msg("War zone was unclaimed."); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed land at ("+flocation.getCoordString()+") from the faction: "+otherFaction.getTag()); - } - else - { - msg("This is a war zone. You lack permissions to unclaim."); - } - return; - } - - if (fme.isAdminBypassing()) - { - Board.removeAt(flocation); - SpoutFeatures.updateTerritoryDisplayLoc(flocation); + this.permission = Permission.UNCLAIM.node; + this.disableOnLock = true; - otherFaction.msg("%s unclaimed some of your land.", fme.describeTo(otherFaction, true)); - msg("You unclaimed this land."); + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed land at ("+flocation.getCoordString()+") from the faction: "+otherFaction.getTag()); + @Override + public void perform() { + FLocation flocation = new FLocation(fme); + Faction otherFaction = Board.getFactionAt(flocation); - return; - } - - if ( ! assertHasFaction()) - { - return; - } - - if ( ! assertMinRole(Role.MODERATOR)) - { - return; - } - - - if ( myFaction != otherFaction) - { - msg("You don't own this land."); - return; - } + if (otherFaction.isSafeZone()) { + if (Permission.MANAGE_SAFE_ZONE.has(sender)) { + Board.removeAt(flocation); + SpoutFeatures.updateTerritoryDisplayLoc(flocation); + msg("Safe zone was unclaimed."); - LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(flocation, otherFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); - if(unclaimEvent.isCancelled()) return; + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); + } else { + msg("This is a safe zone. You lack permissions to unclaim."); + } + return; + } else if (otherFaction.isWarZone()) { + if (Permission.MANAGE_WAR_ZONE.has(sender)) { + Board.removeAt(flocation); + SpoutFeatures.updateTerritoryDisplayLoc(flocation); + msg("War zone was unclaimed."); - if (Econ.shouldBeUsed()) - { - double refund = Econ.calculateClaimRefund(myFaction.getLandRounded()); - - if(Conf.bankEnabled && Conf.bankFactionPaysLandCosts) - { - if ( ! Econ.modifyMoney(myFaction, refund, "to unclaim this land", "for unclaiming this land")) return; - } - else - { - if ( ! Econ.modifyMoney(fme , refund, "to unclaim this land", "for unclaiming this land")) return; - } - } + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); + } else { + msg("This is a war zone. You lack permissions to unclaim."); + } + return; + } - Board.removeAt(flocation); - SpoutFeatures.updateTerritoryDisplayLoc(flocation); - myFaction.msg("%s unclaimed some land.", fme.describeTo(myFaction, true)); + if (fme.isAdminBypassing()) { + Board.removeAt(flocation); + SpoutFeatures.updateTerritoryDisplayLoc(flocation); + + otherFaction.msg("%s unclaimed some of your land.", fme.describeTo(otherFaction, true)); + msg("You unclaimed this land."); + + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); + + return; + } + + if (!assertHasFaction()) { + return; + } + + if (!assertMinRole(Role.MODERATOR)) { + return; + } + + + if (myFaction != otherFaction) { + msg("You don't own this land."); + return; + } + + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(flocation, otherFaction, fme); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) return; + + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateClaimRefund(myFaction.getLandRounded()); + + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(myFaction, refund, "to unclaim this land", "for unclaiming this land")) return; + } else { + if (!Econ.modifyMoney(fme, refund, "to unclaim this land", "for unclaiming this land")) return; + } + } + + Board.removeAt(flocation); + SpoutFeatures.updateTerritoryDisplayLoc(flocation); + myFaction.msg("%s unclaimed some land.", fme.describeTo(myFaction, true)); + + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); + } - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed land at ("+flocation.getCoordString()+") from the faction: "+otherFaction.getTag()); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java index 21370219..f1fbae66 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java @@ -1,7 +1,5 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; - import com.massivecraft.factions.Board; import com.massivecraft.factions.Conf; import com.massivecraft.factions.P; @@ -9,52 +7,48 @@ import com.massivecraft.factions.event.LandUnclaimAllEvent; import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; +import org.bukkit.Bukkit; -public class CmdUnclaimall extends FCommand -{ - public CmdUnclaimall() - { - this.aliases.add("unclaimall"); - this.aliases.add("declaimall"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.UNCLAIM_ALL.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - if (Econ.shouldBeUsed()) - { - double refund = Econ.calculateTotalLandRefund(myFaction.getLandRounded()); - if(Conf.bankEnabled && Conf.bankFactionPaysLandCosts) - { - if ( ! Econ.modifyMoney(myFaction, refund, "to unclaim all faction land", "for unclaiming all faction land")) return; - } - else - { - if ( ! Econ.modifyMoney(fme , refund, "to unclaim all faction land", "for unclaiming all faction land")) return; - } - } +public class CmdUnclaimall extends FCommand { + public CmdUnclaimall() { + this.aliases.add("unclaimall"); + this.aliases.add("declaimall"); - LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(myFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent); - // this event cannot be cancelled + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - Board.unclaimAll(myFaction.getId()); - myFaction.msg("%s unclaimed ALL of your faction's land.", fme.describeTo(myFaction, true)); - SpoutFeatures.updateTerritoryDisplayLoc(null); + this.permission = Permission.UNCLAIM_ALL.node; + this.disableOnLock = true; + + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateTotalLandRefund(myFaction.getLandRounded()); + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(myFaction, refund, "to unclaim all faction land", "for unclaiming all faction land")) + return; + } else { + if (!Econ.modifyMoney(fme, refund, "to unclaim all faction land", "for unclaiming all faction land")) + return; + } + } + + LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(myFaction, fme); + Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent); + // this event cannot be cancelled + + Board.unclaimAll(myFaction.getId()); + myFaction.msg("%s unclaimed ALL of your faction's land.", fme.describeTo(myFaction, true)); + SpoutFeatures.updateTerritoryDisplayLoc(null); + + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed everything for the faction: " + myFaction.getTag()); + } - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed everything for the faction: "+myFaction.getTag()); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java index 8614cf51..c1cdc8e6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java @@ -4,27 +4,24 @@ import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdVersion extends FCommand -{ - public CmdVersion() - { - this.aliases.add("version"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.VERSION.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } +public class CmdVersion extends FCommand { + public CmdVersion() { + this.aliases.add("version"); - @Override - public void perform() - { - msg("You are running "+P.p.getDescription().getFullName()); - } + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); + + this.permission = Permission.VERSION.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + msg("You are running " + P.p.getDescription().getFullName()); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java index 4e3c10f7..a2153048 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java @@ -6,36 +6,33 @@ import com.massivecraft.factions.Factions; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Permission; -public class CmdWarunclaimall extends FCommand -{ - - public CmdWarunclaimall() - { - this.aliases.add("warunclaimall"); - this.aliases.add("wardeclaimall"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.MANAGE_WAR_ZONE.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - - this.setHelpShort("unclaim all warzone land"); - } - - @Override - public void perform() - { - Board.unclaimAll(Factions.i.getWarZone().getId()); - msg("You unclaimed ALL war zone land."); +public class CmdWarunclaimall extends FCommand { + + public CmdWarunclaimall() { + this.aliases.add("warunclaimall"); + this.aliases.add("wardeclaimall"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); + + this.permission = Permission.MANAGE_WAR_ZONE.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + + this.setHelpShort("unclaim all warzone land"); + } + + @Override + public void perform() { + Board.unclaimAll(Factions.i.getWarZone().getId()); + msg("You unclaimed ALL war zone land."); + + if (Conf.logLandUnclaims) + P.p.log(fme.getName() + " unclaimed all war zones."); + } - if (Conf.logLandUnclaims) - P.p.log(fme.getName()+" unclaimed all war zones."); - } - } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java index ac9db002..a26c06a8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java @@ -1,131 +1,128 @@ package com.massivecraft.factions.cmd; -import java.util.Collections; - import com.massivecraft.factions.Conf; -public class FCmdRoot extends FCommand -{ - public CmdAdmin cmdAdmin = new CmdAdmin(); - public CmdAutoClaim cmdAutoClaim = new CmdAutoClaim(); - public CmdBoom cmdBoom = new CmdBoom(); - public CmdBypass cmdBypass = new CmdBypass(); - public CmdChat cmdChat = new CmdChat(); - public CmdChatSpy cmdChatSpy = new CmdChatSpy(); - public CmdClaim cmdClaim = new CmdClaim(); - public CmdConfig cmdConfig = new CmdConfig(); - public CmdCreate cmdCreate = new CmdCreate(); - public CmdDeinvite cmdDeinvite = new CmdDeinvite(); - public CmdDescription cmdDescription = new CmdDescription(); - public CmdDisband cmdDisband = new CmdDisband(); - public CmdHelp cmdHelp = new CmdHelp(); - public CmdHome cmdHome = new CmdHome(); - public CmdInvite cmdInvite = new CmdInvite(); - public CmdJoin cmdJoin = new CmdJoin(); - public CmdKick cmdKick = new CmdKick(); - public CmdLeave cmdLeave = new CmdLeave(); - public CmdList cmdList = new CmdList(); - public CmdLock cmdLock = new CmdLock(); - public CmdMap cmdMap = new CmdMap(); - public CmdMod cmdMod = new CmdMod(); - public CmdMoney cmdMoney = new CmdMoney(); - public CmdOpen cmdOpen = new CmdOpen(); - public CmdOwner cmdOwner = new CmdOwner(); - public CmdOwnerList cmdOwnerList = new CmdOwnerList(); - public CmdPeaceful cmdPeaceful = new CmdPeaceful(); - public CmdPermanent cmdPermanent = new CmdPermanent(); - public CmdPermanentPower cmdPermanentPower = new CmdPermanentPower(); - public CmdPowerBoost cmdPowerBoost = new CmdPowerBoost(); - public CmdPower cmdPower = new CmdPower(); - public CmdRelationAlly cmdRelationAlly = new CmdRelationAlly(); - public CmdRelationEnemy cmdRelationEnemy = new CmdRelationEnemy(); - public CmdRelationNeutral cmdRelationNeutral = new CmdRelationNeutral(); - public CmdReload cmdReload = new CmdReload(); - public CmdSafeunclaimall cmdSafeunclaimall = new CmdSafeunclaimall(); - public CmdSaveAll cmdSaveAll = new CmdSaveAll(); - public CmdSethome cmdSethome = new CmdSethome(); - public CmdShow cmdShow = new CmdShow(); - public CmdTag cmdTag = new CmdTag(); - public CmdTitle cmdTitle = new CmdTitle(); - public CmdUnclaim cmdUnclaim = new CmdUnclaim(); - public CmdUnclaimall cmdUnclaimall = new CmdUnclaimall(); - public CmdVersion cmdVersion = new CmdVersion(); - public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); - - public FCmdRoot() - { - super(); - this.aliases.addAll(Conf.baseCommandAliases); - this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas - this.allowNoSlashAccess = Conf.allowNoSlashCommand; - - //this.requiredArgs.add(""); - //this.optionalArgs.put("","") - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - - this.disableOnLock = false; - - this.setHelpShort("The faction base command"); - this.helpLong.add(p.txt.parseTags("This command contains all faction stuff.")); - - //this.subCommands.add(p.cmdHelp); - - this.addSubCommand(this.cmdAdmin); - this.addSubCommand(this.cmdAutoClaim); - this.addSubCommand(this.cmdBoom); - this.addSubCommand(this.cmdBypass); - this.addSubCommand(this.cmdChat); - this.addSubCommand(this.cmdChatSpy); - this.addSubCommand(this.cmdClaim); - this.addSubCommand(this.cmdConfig); - this.addSubCommand(this.cmdCreate); - this.addSubCommand(this.cmdDeinvite); - this.addSubCommand(this.cmdDescription); - this.addSubCommand(this.cmdDisband); - this.addSubCommand(this.cmdHelp); - this.addSubCommand(this.cmdHome); - this.addSubCommand(this.cmdInvite); - this.addSubCommand(this.cmdJoin); - this.addSubCommand(this.cmdKick); - this.addSubCommand(this.cmdLeave); - this.addSubCommand(this.cmdList); - this.addSubCommand(this.cmdLock); - this.addSubCommand(this.cmdMap); - this.addSubCommand(this.cmdMod); - this.addSubCommand(this.cmdMoney); - this.addSubCommand(this.cmdOpen); - this.addSubCommand(this.cmdOwner); - this.addSubCommand(this.cmdOwnerList); - this.addSubCommand(this.cmdPeaceful); - this.addSubCommand(this.cmdPermanent); - this.addSubCommand(this.cmdPermanentPower); - this.addSubCommand(this.cmdPower); - this.addSubCommand(this.cmdPowerBoost); - this.addSubCommand(this.cmdRelationAlly); - this.addSubCommand(this.cmdRelationEnemy); - this.addSubCommand(this.cmdRelationNeutral); - this.addSubCommand(this.cmdReload); - this.addSubCommand(this.cmdSafeunclaimall); - this.addSubCommand(this.cmdSaveAll); - this.addSubCommand(this.cmdSethome); - this.addSubCommand(this.cmdShow); - this.addSubCommand(this.cmdTag); - this.addSubCommand(this.cmdTitle); - this.addSubCommand(this.cmdUnclaim); - this.addSubCommand(this.cmdUnclaimall); - this.addSubCommand(this.cmdVersion); - this.addSubCommand(this.cmdWarunclaimall); - } - - @Override - public void perform() - { - this.commandChain.add(this); - this.cmdHelp.execute(this.sender, this.args, this.commandChain); - } +import java.util.Collections; + +public class FCmdRoot extends FCommand { + public CmdAdmin cmdAdmin = new CmdAdmin(); + public CmdAutoClaim cmdAutoClaim = new CmdAutoClaim(); + public CmdBoom cmdBoom = new CmdBoom(); + public CmdBypass cmdBypass = new CmdBypass(); + public CmdChat cmdChat = new CmdChat(); + public CmdChatSpy cmdChatSpy = new CmdChatSpy(); + public CmdClaim cmdClaim = new CmdClaim(); + public CmdConfig cmdConfig = new CmdConfig(); + public CmdCreate cmdCreate = new CmdCreate(); + public CmdDeinvite cmdDeinvite = new CmdDeinvite(); + public CmdDescription cmdDescription = new CmdDescription(); + public CmdDisband cmdDisband = new CmdDisband(); + public CmdHelp cmdHelp = new CmdHelp(); + public CmdHome cmdHome = new CmdHome(); + public CmdInvite cmdInvite = new CmdInvite(); + public CmdJoin cmdJoin = new CmdJoin(); + public CmdKick cmdKick = new CmdKick(); + public CmdLeave cmdLeave = new CmdLeave(); + public CmdList cmdList = new CmdList(); + public CmdLock cmdLock = new CmdLock(); + public CmdMap cmdMap = new CmdMap(); + public CmdMod cmdMod = new CmdMod(); + public CmdMoney cmdMoney = new CmdMoney(); + public CmdOpen cmdOpen = new CmdOpen(); + public CmdOwner cmdOwner = new CmdOwner(); + public CmdOwnerList cmdOwnerList = new CmdOwnerList(); + public CmdPeaceful cmdPeaceful = new CmdPeaceful(); + public CmdPermanent cmdPermanent = new CmdPermanent(); + public CmdPermanentPower cmdPermanentPower = new CmdPermanentPower(); + public CmdPowerBoost cmdPowerBoost = new CmdPowerBoost(); + public CmdPower cmdPower = new CmdPower(); + public CmdRelationAlly cmdRelationAlly = new CmdRelationAlly(); + public CmdRelationEnemy cmdRelationEnemy = new CmdRelationEnemy(); + public CmdRelationNeutral cmdRelationNeutral = new CmdRelationNeutral(); + public CmdReload cmdReload = new CmdReload(); + public CmdSafeunclaimall cmdSafeunclaimall = new CmdSafeunclaimall(); + public CmdSaveAll cmdSaveAll = new CmdSaveAll(); + public CmdSethome cmdSethome = new CmdSethome(); + public CmdShow cmdShow = new CmdShow(); + public CmdTag cmdTag = new CmdTag(); + public CmdTitle cmdTitle = new CmdTitle(); + public CmdUnclaim cmdUnclaim = new CmdUnclaim(); + public CmdUnclaimall cmdUnclaimall = new CmdUnclaimall(); + public CmdVersion cmdVersion = new CmdVersion(); + public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); + + public FCmdRoot() { + super(); + this.aliases.addAll(Conf.baseCommandAliases); + this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas + this.allowNoSlashAccess = Conf.allowNoSlashCommand; + + //this.requiredArgs.add(""); + //this.optionalArgs.put("","") + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + + this.disableOnLock = false; + + this.setHelpShort("The faction base command"); + this.helpLong.add(p.txt.parseTags("This command contains all faction stuff.")); + + //this.subCommands.add(p.cmdHelp); + + this.addSubCommand(this.cmdAdmin); + this.addSubCommand(this.cmdAutoClaim); + this.addSubCommand(this.cmdBoom); + this.addSubCommand(this.cmdBypass); + this.addSubCommand(this.cmdChat); + this.addSubCommand(this.cmdChatSpy); + this.addSubCommand(this.cmdClaim); + this.addSubCommand(this.cmdConfig); + this.addSubCommand(this.cmdCreate); + this.addSubCommand(this.cmdDeinvite); + this.addSubCommand(this.cmdDescription); + this.addSubCommand(this.cmdDisband); + this.addSubCommand(this.cmdHelp); + this.addSubCommand(this.cmdHome); + this.addSubCommand(this.cmdInvite); + this.addSubCommand(this.cmdJoin); + this.addSubCommand(this.cmdKick); + this.addSubCommand(this.cmdLeave); + this.addSubCommand(this.cmdList); + this.addSubCommand(this.cmdLock); + this.addSubCommand(this.cmdMap); + this.addSubCommand(this.cmdMod); + this.addSubCommand(this.cmdMoney); + this.addSubCommand(this.cmdOpen); + this.addSubCommand(this.cmdOwner); + this.addSubCommand(this.cmdOwnerList); + this.addSubCommand(this.cmdPeaceful); + this.addSubCommand(this.cmdPermanent); + this.addSubCommand(this.cmdPermanentPower); + this.addSubCommand(this.cmdPower); + this.addSubCommand(this.cmdPowerBoost); + this.addSubCommand(this.cmdRelationAlly); + this.addSubCommand(this.cmdRelationEnemy); + this.addSubCommand(this.cmdRelationNeutral); + this.addSubCommand(this.cmdReload); + this.addSubCommand(this.cmdSafeunclaimall); + this.addSubCommand(this.cmdSaveAll); + this.addSubCommand(this.cmdSethome); + this.addSubCommand(this.cmdShow); + this.addSubCommand(this.cmdTag); + this.addSubCommand(this.cmdTitle); + this.addSubCommand(this.cmdUnclaim); + this.addSubCommand(this.cmdUnclaimall); + this.addSubCommand(this.cmdVersion); + this.addSubCommand(this.cmdWarunclaimall); + } + + @Override + public void perform() { + this.commandChain.add(this); + this.cmdHelp.execute(this.sender, this.args, this.commandChain); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCommand.java b/src/main/java/com/massivecraft/factions/cmd/FCommand.java index 328de733..72b8903b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -1,337 +1,284 @@ package com.massivecraft.factions.cmd; -import java.util.List; - +import com.massivecraft.factions.*; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Role; +import com.massivecraft.factions.zcore.MCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.integration.Econ; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.P; -import com.massivecraft.factions.struct.Role; -import com.massivecraft.factions.zcore.MCommand; +import java.util.List; -public abstract class FCommand extends MCommand

-{ - public boolean disableOnLock; - - public FPlayer fme; - public Faction myFaction; - public boolean senderMustBeMember; - public boolean senderMustBeModerator; - public boolean senderMustBeAdmin; - - public boolean isMoneyCommand; - - public FCommand() - { - super(P.p); - - // Due to safety reasons it defaults to disable on lock. - disableOnLock = true; - - // The money commands must be disabled if money should not be used. - isMoneyCommand = false; - - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } - - @Override - public void execute(CommandSender sender, List args, List> commandChain) - { - if (sender instanceof Player) - { - this.fme = FPlayers.i.get((Player)sender); - this.myFaction = this.fme.getFaction(); - } - else - { - this.fme = null; - this.myFaction = null; - } - super.execute(sender, args, commandChain); - } - - @Override - public boolean isEnabled() - { - if (p.getLocked() && this.disableOnLock) - { - msg("Factions was locked by an admin. Please try again later."); - return false; - } - - if (this.isMoneyCommand && ! Conf.econEnabled) - { - msg("Faction economy features are disabled on this server."); - return false; - } - - if (this.isMoneyCommand && ! Conf.bankEnabled) - { - msg("The faction bank system is disabled on this server."); - return false; - } - - return true; - } - - @Override - public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) - { - boolean superValid = super.validSenderType(sender, informSenderIfNot); - if ( ! superValid) return false; - - if ( ! (this.senderMustBeMember || this.senderMustBeModerator || this.senderMustBeAdmin)) return true; - - if ( ! (sender instanceof Player)) return false; - - FPlayer fplayer = FPlayers.i.get((Player)sender); - - if ( ! fplayer.hasFaction()) - { - sender.sendMessage(p.txt.parse("You are not member of any faction.")); - return false; - } - - if (this.senderMustBeModerator && ! fplayer.getRole().isAtLeast(Role.MODERATOR)) - { - sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); - return false; - } - - if (this.senderMustBeAdmin && ! fplayer.getRole().isAtLeast(Role.ADMIN)) - { - sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); - return false; - } - - return true; - } - - // -------------------------------------------- // - // Assertions - // -------------------------------------------- // +public abstract class FCommand extends MCommand

{ + public boolean disableOnLock; - public boolean assertHasFaction() - { - if (me == null) return true; - - if ( ! fme.hasFaction()) - { - sendMessage("You are not member of any faction."); - return false; - } - return true; - } + public FPlayer fme; + public Faction myFaction; + public boolean senderMustBeMember; + public boolean senderMustBeModerator; + public boolean senderMustBeAdmin; - public boolean assertMinRole(Role role) - { - if (me == null) return true; - - if (fme.getRole().value < role.value) - { - msg("You must be "+role+" to "+this.getHelpShort()+"."); - return false; - } - return true; - } - - // -------------------------------------------- // - // Argument Readers - // -------------------------------------------- // - - // FPLAYER ====================== - public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) - { - FPlayer ret = def; - - if (name != null) - { - FPlayer fplayer = FPlayers.i.get(name); - if (fplayer != null) - { - ret = fplayer; - } - } - - if (msg && ret == null) - { - this.msg("No player \"

%s\" could be found.", name); - } - - return ret; - } - public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) - { - return this.strAsFPlayer(this.argAsString(idx), def, msg); - } - public FPlayer argAsFPlayer(int idx, FPlayer def) - { - return this.argAsFPlayer(idx, def, true); - } - public FPlayer argAsFPlayer(int idx) - { - return this.argAsFPlayer(idx, null); - } - - // BEST FPLAYER MATCH ====================== - public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) - { - FPlayer ret = def; - - if (name != null) - { - FPlayer fplayer = FPlayers.i.getBestIdMatch(name); - if (fplayer != null) - { - ret = fplayer; - } - } - - if (msg && ret == null) - { - this.msg("No player match found for \"

%s\".", name); - } - - return ret; - } - public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) - { - return this.strAsBestFPlayerMatch(this.argAsString(idx), def, msg); - } - public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) - { - return this.argAsBestFPlayerMatch(idx, def, true); - } - public FPlayer argAsBestFPlayerMatch(int idx) - { - return this.argAsBestFPlayerMatch(idx, null); - } - - // FACTION ====================== - public Faction strAsFaction(String name, Faction def, boolean msg) - { - Faction ret = def; - - if (name != null) - { - Faction faction = null; - - // First we try an exact match - if (faction == null) - { - faction = Factions.i.getByTag(name); - } - - // Next we match faction tags - if (faction == null) - { - faction = Factions.i.getBestTagMatch(name); - } - - // Next we match player names - if (faction == null) - { - FPlayer fplayer = FPlayers.i.getBestIdMatch(name); - if (fplayer != null) - { - faction = fplayer.getFaction(); - } - } - - if (faction != null) - { - ret = faction; - } - } - - if (msg && ret == null) - { - this.msg("The faction or player \"

%s\" could not be found.", name); - } - - return ret; - } - public Faction argAsFaction(int idx, Faction def, boolean msg) - { - return this.strAsFaction(this.argAsString(idx), def, msg); - } - public Faction argAsFaction(int idx, Faction def) - { - return this.argAsFaction(idx, def, true); - } - public Faction argAsFaction(int idx) - { - return this.argAsFaction(idx, null); - } - - // -------------------------------------------- // - // Commonly used logic - // -------------------------------------------- // - - public boolean canIAdministerYou(FPlayer i, FPlayer you) - { - if ( ! i.getFaction().equals(you.getFaction())) - { - i.sendMessage(p.txt.parse("%s is not in the same faction as you.",you.describeTo(i, true))); - return false; - } - - if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.ADMIN) ) - { - return true; - } - - if (you.getRole().equals(Role.ADMIN)) - { - i.sendMessage(p.txt.parse("Only the faction admin can do that.")); - } - else if (i.getRole().equals(Role.MODERATOR)) - { - if ( i == you ) - { - return true; //Moderators can control themselves - } - else - { - i.sendMessage(p.txt.parse("Moderators can't control each other...")); - } - } - else - { - i.sendMessage(p.txt.parse("You must be a faction moderator to do that.")); - } - - return false; - } - - // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost - public boolean payForCommand(double cost, String toDoThis, String forDoingThis) - { - if ( ! Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) return true; + public boolean isMoneyCommand; - if(Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) - return Econ.modifyMoney(myFaction, -cost, toDoThis, forDoingThis); - else - return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); - } + public FCommand() { + super(P.p); - // like above, but just make sure they can pay; returns true unless person can't afford the cost - public boolean canAffordCommand(double cost, String toDoThis) - { - if ( ! Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) return true; + // Due to safety reasons it defaults to disable on lock. + disableOnLock = true; - if(Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) - return Econ.hasAtLeast(myFaction, cost, toDoThis); - else - return Econ.hasAtLeast(fme, cost, toDoThis); - } + // The money commands must be disabled if money should not be used. + isMoneyCommand = false; + + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } + + @Override + public void execute(CommandSender sender, List args, List> commandChain) { + if (sender instanceof Player) { + this.fme = FPlayers.i.get((Player) sender); + this.myFaction = this.fme.getFaction(); + } else { + this.fme = null; + this.myFaction = null; + } + super.execute(sender, args, commandChain); + } + + @Override + public boolean isEnabled() { + if (p.getLocked() && this.disableOnLock) { + msg("Factions was locked by an admin. Please try again later."); + return false; + } + + if (this.isMoneyCommand && !Conf.econEnabled) { + msg("Faction economy features are disabled on this server."); + return false; + } + + if (this.isMoneyCommand && !Conf.bankEnabled) { + msg("The faction bank system is disabled on this server."); + return false; + } + + return true; + } + + @Override + public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { + boolean superValid = super.validSenderType(sender, informSenderIfNot); + if (!superValid) return false; + + if (!(this.senderMustBeMember || this.senderMustBeModerator || this.senderMustBeAdmin)) return true; + + if (!(sender instanceof Player)) return false; + + FPlayer fplayer = FPlayers.i.get((Player) sender); + + if (!fplayer.hasFaction()) { + sender.sendMessage(p.txt.parse("You are not member of any faction.")); + return false; + } + + if (this.senderMustBeModerator && !fplayer.getRole().isAtLeast(Role.MODERATOR)) { + sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); + return false; + } + + if (this.senderMustBeAdmin && !fplayer.getRole().isAtLeast(Role.ADMIN)) { + sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); + return false; + } + + return true; + } + + // -------------------------------------------- // + // Assertions + // -------------------------------------------- // + + public boolean assertHasFaction() { + if (me == null) return true; + + if (!fme.hasFaction()) { + sendMessage("You are not member of any faction."); + return false; + } + return true; + } + + public boolean assertMinRole(Role role) { + if (me == null) return true; + + if (fme.getRole().value < role.value) { + msg("You must be " + role + " to " + this.getHelpShort() + "."); + return false; + } + return true; + } + + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // + + // FPLAYER ====================== + public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) { + FPlayer ret = def; + + if (name != null) { + FPlayer fplayer = FPlayers.i.get(name); + if (fplayer != null) { + ret = fplayer; + } + } + + if (msg && ret == null) { + this.msg("No player \"

%s\" could be found.", name); + } + + return ret; + } + + public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { + return this.strAsFPlayer(this.argAsString(idx), def, msg); + } + + public FPlayer argAsFPlayer(int idx, FPlayer def) { + return this.argAsFPlayer(idx, def, true); + } + + public FPlayer argAsFPlayer(int idx) { + return this.argAsFPlayer(idx, null); + } + + // BEST FPLAYER MATCH ====================== + public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) { + FPlayer ret = def; + + if (name != null) { + FPlayer fplayer = FPlayers.i.getBestIdMatch(name); + if (fplayer != null) { + ret = fplayer; + } + } + + if (msg && ret == null) { + this.msg("No player match found for \"

%s\".", name); + } + + return ret; + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) { + return this.strAsBestFPlayerMatch(this.argAsString(idx), def, msg); + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { + return this.argAsBestFPlayerMatch(idx, def, true); + } + + public FPlayer argAsBestFPlayerMatch(int idx) { + return this.argAsBestFPlayerMatch(idx, null); + } + + // FACTION ====================== + public Faction strAsFaction(String name, Faction def, boolean msg) { + Faction ret = def; + + if (name != null) { + Faction faction = null; + + // First we try an exact match + if (faction == null) { + faction = Factions.i.getByTag(name); + } + + // Next we match faction tags + if (faction == null) { + faction = Factions.i.getBestTagMatch(name); + } + + // Next we match player names + if (faction == null) { + FPlayer fplayer = FPlayers.i.getBestIdMatch(name); + if (fplayer != null) { + faction = fplayer.getFaction(); + } + } + + if (faction != null) { + ret = faction; + } + } + + if (msg && ret == null) { + this.msg("The faction or player \"

%s\" could not be found.", name); + } + + return ret; + } + + public Faction argAsFaction(int idx, Faction def, boolean msg) { + return this.strAsFaction(this.argAsString(idx), def, msg); + } + + public Faction argAsFaction(int idx, Faction def) { + return this.argAsFaction(idx, def, true); + } + + public Faction argAsFaction(int idx) { + return this.argAsFaction(idx, null); + } + + // -------------------------------------------- // + // Commonly used logic + // -------------------------------------------- // + + public boolean canIAdministerYou(FPlayer i, FPlayer you) { + if (!i.getFaction().equals(you.getFaction())) { + i.sendMessage(p.txt.parse("%s is not in the same faction as you.", you.describeTo(i, true))); + return false; + } + + if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.ADMIN)) { + return true; + } + + if (you.getRole().equals(Role.ADMIN)) { + i.sendMessage(p.txt.parse("Only the faction admin can do that.")); + } else if (i.getRole().equals(Role.MODERATOR)) { + if (i == you) { + return true; //Moderators can control themselves + } else { + i.sendMessage(p.txt.parse("Moderators can't control each other...")); + } + } else { + i.sendMessage(p.txt.parse("You must be a faction moderator to do that.")); + } + + return false; + } + + // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost + public boolean payForCommand(double cost, String toDoThis, String forDoingThis) { + if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) return true; + + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) + return Econ.modifyMoney(myFaction, -cost, toDoThis, forDoingThis); + else + return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); + } + + // like above, but just make sure they can pay; returns true unless person can't afford the cost + public boolean canAffordCommand(double cost, String toDoThis) { + if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) return true; + + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) + return Econ.hasAtLeast(myFaction, cost, toDoThis); + else + return Econ.hasAtLeast(fme, cost, toDoThis); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java index 19f3a8b1..b0616376 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java @@ -1,98 +1,88 @@ package com.massivecraft.factions.cmd; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.Faction; import com.massivecraft.factions.event.FactionRelationEvent; import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Relation; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; -public abstract class FRelationCommand extends FCommand -{ - public Relation targetRelation; - - public FRelationCommand() - { - super(); - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("player name", "you"); - - this.permission = Permission.RELATION.node; - this.disableOnLock = true; - - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } - - @Override - public void perform() - { - Faction them = this.argAsFaction(0); - if (them == null) return; - - if ( ! them.isNormal()) - { - msg("Nope! You can't."); - return; - } - - if (them == myFaction) - { - msg("Nope! You can't declare a relation to yourself :)"); - return; - } +public abstract class FRelationCommand extends FCommand { + public Relation targetRelation; - if (myFaction.getRelationWish(them) == targetRelation) - { - msg("You already have that relation wish set with %s.", them.getTag()); - return; - } + public FRelationCommand() { + super(); + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("player name", "you"); - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if ( ! payForCommand(targetRelation.getRelationCost(), "to change a relation wish", "for changing a relation wish")) return; + this.permission = Permission.RELATION.node; + this.disableOnLock = true; - // try to set the new relation - Relation oldRelation = myFaction.getRelationTo(them, true); - myFaction.setRelationWish(them, targetRelation); - Relation currentRelation = myFaction.getRelationTo(them, true); - ChatColor currentRelationColor = currentRelation.getColor(); + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } - // if the relation change was successful - if (targetRelation.value == currentRelation.value) - { - // trigger the faction relation event - FactionRelationEvent relationEvent = new FactionRelationEvent(myFaction, them, oldRelation, currentRelation); - Bukkit.getServer().getPluginManager().callEvent(relationEvent); + @Override + public void perform() { + Faction them = this.argAsFaction(0); + if (them == null) return; - them.msg("Your faction is now "+currentRelationColor+targetRelation.toString()+" to "+currentRelationColor+myFaction.getTag()); - myFaction.msg("Your faction is now "+currentRelationColor+targetRelation.toString()+" to "+currentRelationColor+them.getTag()); - } - // inform the other faction of your request - else - { - them.msg(currentRelationColor+myFaction.getTag()+" wishes to be your "+targetRelation.getColor()+targetRelation.toString()); - them.msg("Type /"+Conf.baseCommandAliases.get(0)+" "+targetRelation+" "+myFaction.getTag()+" to accept."); - myFaction.msg(currentRelationColor+them.getTag()+" were informed that you wish to be "+targetRelation.getColor()+targetRelation); - } - - if ( ! targetRelation.isNeutral() && them.isPeaceful()) - { - them.msg("This will have no effect while your faction is peaceful."); - myFaction.msg("This will have no effect while their faction is peaceful."); - } - - if ( ! targetRelation.isNeutral() && myFaction.isPeaceful()) - { - them.msg("This will have no effect while their faction is peaceful."); - myFaction.msg("This will have no effect while your faction is peaceful."); - } + if (!them.isNormal()) { + msg("Nope! You can't."); + return; + } - SpoutFeatures.updateAppearances(myFaction, them); - SpoutFeatures.updateTerritoryDisplayLoc(null); - } + if (them == myFaction) { + msg("Nope! You can't declare a relation to yourself :)"); + return; + } + + if (myFaction.getRelationWish(them) == targetRelation) { + msg("You already have that relation wish set with %s.", them.getTag()); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(targetRelation.getRelationCost(), "to change a relation wish", "for changing a relation wish")) + return; + + // try to set the new relation + Relation oldRelation = myFaction.getRelationTo(them, true); + myFaction.setRelationWish(them, targetRelation); + Relation currentRelation = myFaction.getRelationTo(them, true); + ChatColor currentRelationColor = currentRelation.getColor(); + + // if the relation change was successful + if (targetRelation.value == currentRelation.value) { + // trigger the faction relation event + FactionRelationEvent relationEvent = new FactionRelationEvent(myFaction, them, oldRelation, currentRelation); + Bukkit.getServer().getPluginManager().callEvent(relationEvent); + + them.msg("Your faction is now " + currentRelationColor + targetRelation.toString() + " to " + currentRelationColor + myFaction.getTag()); + myFaction.msg("Your faction is now " + currentRelationColor + targetRelation.toString() + " to " + currentRelationColor + them.getTag()); + } + // inform the other faction of your request + else { + them.msg(currentRelationColor + myFaction.getTag() + " wishes to be your " + targetRelation.getColor() + targetRelation.toString()); + them.msg("Type /" + Conf.baseCommandAliases.get(0) + " " + targetRelation + " " + myFaction.getTag() + " to accept."); + myFaction.msg(currentRelationColor + them.getTag() + " were informed that you wish to be " + targetRelation.getColor() + targetRelation); + } + + if (!targetRelation.isNeutral() && them.isPeaceful()) { + them.msg("This will have no effect while your faction is peaceful."); + myFaction.msg("This will have no effect while their faction is peaceful."); + } + + if (!targetRelation.isNeutral() && myFaction.isPeaceful()) { + them.msg("This will have no effect while their faction is peaceful."); + myFaction.msg("This will have no effect while your faction is peaceful."); + } + + SpoutFeatures.updateAppearances(myFaction, them); + SpoutFeatures.updateTerritoryDisplayLoc(null); + } } diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java index 8510d00c..433eb380 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java @@ -1,60 +1,56 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; +public class FPlayerJoinEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); -public class FPlayerJoinEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); + FPlayer fplayer; + Faction faction; + PlayerJoinReason reason; + boolean cancelled = false; - FPlayer fplayer; - Faction faction; - PlayerJoinReason reason; - boolean cancelled = false; - public enum PlayerJoinReason - { - CREATE, LEADER, COMMAND - } - public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) - { - fplayer = fp; - faction = f; - reason = r; - } + public enum PlayerJoinReason { + CREATE, LEADER, COMMAND + } - public FPlayer getFPlayer() - { - return fplayer; - } - public Faction getFaction() - { - return faction; - } - public PlayerJoinReason getReason() - { - return reason; - } - public HandlerList getHandlers() - { - return handlers; - } + public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { + fplayer = fp; + faction = f; + reason = r; + } - public static HandlerList getHandlerList() - { - return handlers; - } - @Override - public boolean isCancelled() - { - return cancelled; - } - @Override - public void setCancelled(boolean c) - { - cancelled = c; - } + public FPlayer getFPlayer() { + return fplayer; + } + + public Faction getFaction() { + return faction; + } + + public PlayerJoinReason getReason() { + return reason; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + cancelled = c; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java index 12e951bb..805ec745 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java @@ -1,71 +1,59 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; +public class FPlayerLeaveEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private PlayerLeaveReason reason; + FPlayer FPlayer; + Faction Faction; + boolean cancelled = false; -public class FPlayerLeaveEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - private PlayerLeaveReason reason; - FPlayer FPlayer; - Faction Faction; - boolean cancelled = false; + public enum PlayerLeaveReason { + KICKED, DISBAND, RESET, JOINOTHER, LEAVE + } - public enum PlayerLeaveReason - { - KICKED, DISBAND, RESET, JOINOTHER, LEAVE - } + public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { + FPlayer = p; + Faction = f; + reason = r; + } - public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) - { - FPlayer = p; - Faction = f; - reason = r; - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } - - public PlayerLeaveReason getReason() - { - return reason; - } - - public FPlayer getFPlayer() - { - return FPlayer; - } - - public Faction getFaction() - { - return Faction; - } + public PlayerLeaveReason getReason() { + return reason; + } - @Override - public boolean isCancelled() - { - return cancelled; - } + public FPlayer getFPlayer() { + return FPlayer; + } - @Override - public void setCancelled(boolean c) - { - if (reason == PlayerLeaveReason.DISBAND || reason == PlayerLeaveReason.RESET) - { - cancelled = false; - return; - } - cancelled = c; - } + public Faction getFaction() { + return Faction; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + if (reason == PlayerLeaveReason.DISBAND || reason == PlayerLeaveReason.RESET) { + cancelled = false; + return; + } + cancelled = c; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java index 5732699b..1f18d39a 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java @@ -1,63 +1,53 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Factions; +public class FactionCreateEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); -public class FactionCreateEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - - private String factionTag; - private Player sender; - private boolean cancelled; - - public FactionCreateEvent(Player sender, String tag) - { - this.factionTag = tag; - this.sender = sender; - this.cancelled = false; - } - - public FPlayer getFPlayer() - { - return FPlayers.i.get(sender); - } - - public String getFactionId() - { - return Factions.i.getNextId(); - } + private String factionTag; + private Player sender; + private boolean cancelled; - public String getFactionTag() - { - return factionTag; - } + public FactionCreateEvent(Player sender, String tag) { + this.factionTag = tag; + this.sender = sender; + this.cancelled = false; + } - public HandlerList getHandlers() - { - return handlers; - } - - public static HandlerList getHandlerList() - { - return handlers; - } + public FPlayer getFPlayer() { + return FPlayers.i.get(sender); + } - @Override - public boolean isCancelled() - { - return cancelled; - } + public String getFactionId() { + return Factions.i.getNextId(); + } - @Override - public void setCancelled(boolean c) - { - this.cancelled = c; - } + public String getFactionTag() { + return factionTag; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java index 2d742feb..b7f767ae 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java @@ -1,64 +1,54 @@ package com.massivecraft.factions.event; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; -public class FactionDisbandEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); +public class FactionDisbandEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private String id; - private Player sender; + private boolean cancelled; + private String id; + private Player sender; - public FactionDisbandEvent(Player sender, String factionId) - { - cancelled = false; - this.sender = sender; - this.id = factionId; - } + public FactionDisbandEvent(Player sender, String factionId) { + cancelled = false; + this.sender = sender; + this.id = factionId; + } - public HandlerList getHandlers() - { - return handlers; - } + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public Faction getFaction() - { - return Factions.i.get(id); - } + public Faction getFaction() { + return Factions.i.get(id); + } - public FPlayer getFPlayer() - { - return FPlayers.i.get(sender); - } + public FPlayer getFPlayer() { + return FPlayers.i.get(sender); + } - public Player getPlayer() - { - return sender; - } + public Player getPlayer() { + return sender; + } - @Override - public boolean isCancelled() - { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) - { - cancelled = c; - } + @Override + public void setCancelled(boolean c) { + cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java index b79fe948..05f0d344 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java @@ -1,56 +1,47 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Relation; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.struct.Relation; -import com.massivecraft.factions.Faction; +public class FactionRelationEvent extends Event { + private static final HandlerList handlers = new HandlerList(); -public class FactionRelationEvent extends Event -{ - private static final HandlerList handlers = new HandlerList(); + private Faction fsender; + private Faction ftarget; + private Relation foldrel; + private Relation frel; - private Faction fsender; - private Faction ftarget; - private Relation foldrel; - private Relation frel; + public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) { + fsender = sender; + ftarget = target; + foldrel = oldrel; + frel = rel; + } - public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) - { - fsender = sender; - ftarget = target; - foldrel = oldrel; - frel = rel; - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public Relation getOldRelation() { + return foldrel; + } - public Relation getOldRelation() - { - return foldrel; - } + public Relation getRelation() { + return frel; + } - public Relation getRelation() - { - return frel; - } + public Faction getFaction() { + return fsender; + } - public Faction getFaction() - { - return fsender; - } - - public Faction getTargetFaction() - { - return ftarget; - } + public Faction getTargetFaction() { + return ftarget; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java index 4454f8f8..d8862526 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java @@ -1,74 +1,62 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; +public class FactionRenameEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); -public class FactionRenameEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private FPlayer fplayer; + private Faction faction; + private String tag; - private boolean cancelled; - private FPlayer fplayer; - private Faction faction; - private String tag; + public FactionRenameEvent(FPlayer sender, String newTag) { + fplayer = sender; + faction = sender.getFaction(); + tag = newTag; + this.cancelled = false; + } - public FactionRenameEvent(FPlayer sender, String newTag) - { - fplayer = sender; - faction = sender.getFaction(); - tag = newTag; - this.cancelled = false; - } + public Faction getFaction() { + return (faction); + } - public Faction getFaction() - { - return(faction); - } + public FPlayer getFPlayer() { + return (fplayer); + } - public FPlayer getFPlayer() - { - return(fplayer); - } + public Player getPlayer() { + return (fplayer.getPlayer()); + } - public Player getPlayer() - { - return(fplayer.getPlayer()); - } + public String getOldFactionTag() { + return (faction.getTag()); + } - public String getOldFactionTag() - { - return(faction.getTag()); - } + public String getFactionTag() { + return (tag); + } - public String getFactionTag() - { - return(tag); - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean c) - { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java index abc08e1b..55ff0eef 100644 --- a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java @@ -1,80 +1,67 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; -import org.bukkit.entity.Player; +public class LandClaimEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); -public class LandClaimEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private FLocation location; + private Faction faction; + private FPlayer fplayer; - private boolean cancelled; - private FLocation location; - private Faction faction; - private FPlayer fplayer; + public LandClaimEvent(FLocation loc, Faction f, FPlayer p) { + cancelled = false; + location = loc; + faction = f; + fplayer = p; + } - public LandClaimEvent(FLocation loc, Faction f, FPlayer p) - { - cancelled = false; - location = loc; - faction = f; - fplayer = p; - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public FLocation getLocation() { + return this.location; + } - public FLocation getLocation() - { - return this.location; - } + public Faction getFaction() { + return faction; + } - public Faction getFaction() - { - return faction; - } + public String getFactionId() { + return faction.getId(); + } - public String getFactionId() - { - return faction.getId(); - } + public String getFactionTag() { + return faction.getTag(); + } - public String getFactionTag() - { - return faction.getTag(); - } + public FPlayer getFPlayer() { + return fplayer; + } - public FPlayer getFPlayer() - { - return fplayer; - } + public Player getPlayer() { + return fplayer.getPlayer(); + } - public Player getPlayer() - { - return fplayer.getPlayer(); - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean c) - { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java index d93d510f..0e705778 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java @@ -1,57 +1,47 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; -import org.bukkit.entity.Player; +public class LandUnclaimAllEvent extends Event { + private static final HandlerList handlers = new HandlerList(); -public class LandUnclaimAllEvent extends Event -{ - private static final HandlerList handlers = new HandlerList(); + private Faction faction; + private FPlayer fplayer; - private Faction faction; - private FPlayer fplayer; + public LandUnclaimAllEvent(Faction f, FPlayer p) { + faction = f; + fplayer = p; + } - public LandUnclaimAllEvent(Faction f, FPlayer p) - { - faction = f; - fplayer = p; - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public Faction getFaction() { + return faction; + } - public Faction getFaction() - { - return faction; - } + public String getFactionId() { + return faction.getId(); + } - public String getFactionId() - { - return faction.getId(); - } + public String getFactionTag() { + return faction.getTag(); + } - public String getFactionTag() - { - return faction.getTag(); - } + public FPlayer getFPlayer() { + return fplayer; + } - public FPlayer getFPlayer() - { - return fplayer; - } - - public Player getPlayer() - { - return fplayer.getPlayer(); - } + public Player getPlayer() { + return fplayer.getPlayer(); + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java index 53d1b052..436f58cb 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java @@ -1,79 +1,67 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; -import org.bukkit.entity.Player; +public class LandUnclaimEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); -public class LandUnclaimEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private FLocation location; + private Faction faction; + private FPlayer fplayer; - private boolean cancelled; - private FLocation location; - private Faction faction; - private FPlayer fplayer; + public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) { + cancelled = false; + location = loc; + faction = f; + fplayer = p; + } - public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) - { - cancelled = false; - location = loc; - faction = f; - fplayer = p; - } + public HandlerList getHandlers() { + return handlers; + } - public HandlerList getHandlers() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public FLocation getLocation() { + return this.location; + } - public FLocation getLocation() - { - return this.location; - } + public Faction getFaction() { + return faction; + } - public Faction getFaction() - { - return faction; - } + public String getFactionId() { + return faction.getId(); + } - public String getFactionId() - { - return faction.getId(); - } + public String getFactionTag() { + return faction.getTag(); + } - public String getFactionTag() - { - return faction.getTag(); - } + public FPlayer getFPlayer() { + return fplayer; + } - public FPlayer getFPlayer() - { - return fplayer; - } + public Player getPlayer() { + return fplayer.getPlayer(); + } - public Player getPlayer() - { - return fplayer.getPlayer(); - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean c) { - cancelled = c; - } + @Override + public void setCancelled(boolean c) { + cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java index 76eeb8d1..cd64dc0e 100644 --- a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java +++ b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java @@ -1,85 +1,72 @@ package com.massivecraft.factions.event; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; -import org.bukkit.entity.Player; +public class PowerLossEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private Faction faction; + private FPlayer fplayer; + private String message; -public class PowerLossEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); + public PowerLossEvent(Faction f, FPlayer p) { + cancelled = false; + faction = f; + fplayer = p; + } - private boolean cancelled; - private Faction faction; - private FPlayer fplayer; - private String message; + @Override + public HandlerList getHandlers() { + return handlers; + } - public PowerLossEvent(Faction f, FPlayer p) - { - cancelled = false; - faction = f; - fplayer = p; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() - { - return handlers; - } + public Faction getFaction() { + return faction; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public String getFactionId() { + return faction.getId(); + } - public Faction getFaction() - { - return faction; - } + public String getFactionTag() { + return faction.getTag(); + } - public String getFactionId() - { - return faction.getId(); - } + public FPlayer getFPlayer() { + return fplayer; + } - public String getFactionTag() - { - return faction.getTag(); - } + public Player getPlayer() { + return fplayer.getPlayer(); + } - public FPlayer getFPlayer() - { - return fplayer; - } + public String getMessage() { + return message; + } - public Player getPlayer() - { - return fplayer.getPlayer(); - } + public void setMessage(String message) { + this.message = message; + } - public String getMessage() { - return message; - } + @Override + public boolean isCancelled() { + return cancelled; + } - public void setMessage(String message) { - this.message = message; - } - - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean c) - { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java b/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java index 7e4921b8..ba66a878 100644 --- a/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java +++ b/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java @@ -1,8 +1,7 @@ package com.massivecraft.factions.iface; -public interface EconomyParticipator extends RelationParticipator -{ - public String getAccountId(); - - public void msg(String str, Object... args); +public interface EconomyParticipator extends RelationParticipator { + public String getAccountId(); + + public void msg(String str, Object... args); } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java b/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java index b46b6f3b..d8d93a5d 100644 --- a/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java +++ b/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java @@ -1,16 +1,16 @@ package com.massivecraft.factions.iface; +import com.massivecraft.factions.struct.Relation; import org.bukkit.ChatColor; -import com.massivecraft.factions.struct.Relation; +public interface RelationParticipator { + public String describeTo(RelationParticipator that); -public interface RelationParticipator -{ - public String describeTo(RelationParticipator that); - public String describeTo(RelationParticipator that, boolean ucfirst); - - public Relation getRelationTo(RelationParticipator that); - public Relation getRelationTo(RelationParticipator that, boolean ignorePeaceful); - - public ChatColor getColorTo(RelationParticipator to); + public String describeTo(RelationParticipator that, boolean ucfirst); + + public Relation getRelationTo(RelationParticipator that); + + public Relation getRelationTo(RelationParticipator that, boolean ignorePeaceful); + + public ChatColor getColorTo(RelationParticipator to); } diff --git a/src/main/java/com/massivecraft/factions/integration/Econ.java b/src/main/java/com/massivecraft/factions/integration/Econ.java index b9ec1dbf..9d058c4b 100644 --- a/src/main/java/com/massivecraft/factions/integration/Econ.java +++ b/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -1,393 +1,332 @@ package com.massivecraft.factions.integration; +import com.massivecraft.factions.*; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.struct.Role; +import com.massivecraft.factions.util.RelationUtil; +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.economy.EconomyResponse; +import org.bukkit.Bukkit; +import org.bukkit.plugin.RegisteredServiceProvider; + import java.util.HashSet; import java.util.Set; import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.P; -import com.massivecraft.factions.iface.EconomyParticipator; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.struct.Role; -import com.massivecraft.factions.util.RelationUtil; +public class Econ { + private static Economy econ = null; -import net.milkbowl.vault.economy.Economy; -import net.milkbowl.vault.economy.EconomyResponse; + public static void setup() { + if (isSetup()) return; + + String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; + + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + P.p.log(integrationFail + "is not installed."); + return; + } + + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + P.p.log(integrationFail + "is not hooked into an economy plugin."); + return; + } + econ = rsp.getProvider(); + + P.p.log("Economy integration through Vault plugin successful."); + + if (!Conf.econEnabled) + P.p.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); + + P.p.cmdBase.cmdHelp.updateHelp(); + + oldMoneyDoTransfer(); + } + + public static boolean shouldBeUsed() { + return Conf.econEnabled && econ != null && econ.isEnabled(); + } + + public static boolean isSetup() { + return econ != null; + } -public class Econ -{ - private static Economy econ = null; + public static void modifyUniverseMoney(double delta) { + if (!shouldBeUsed()) return; - public static void setup() - { - if (isSetup()) return; + if (Conf.econUniverseAccount == null) return; + if (Conf.econUniverseAccount.length() == 0) return; + if (!econ.hasAccount(Conf.econUniverseAccount)) return; - String integrationFail = "Economy integration is "+(Conf.econEnabled ? "enabled, but" : "disabled, and")+" the plugin \"Vault\" "; + modifyBalance(Conf.econUniverseAccount, delta); + } - if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) - { - P.p.log(integrationFail+"is not installed."); - return; - } + public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) { + if (!shouldBeUsed()) { + P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); + return; + } + to.msg("%s's balance is %s.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId()))); + } - RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); - if (rsp == null) - { - P.p.log(integrationFail+"is not hooked into an economy plugin."); - return; - } - econ = rsp.getProvider(); + public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) { + Faction fI = RelationUtil.getFaction(i); + Faction fYou = RelationUtil.getFaction(you); - P.p.log("Economy integration through Vault plugin successful."); + // This is a system invoker. Accept it. + if (fI == null) return true; - if ( ! Conf.econEnabled) - P.p.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); + // Bypassing players can do any kind of transaction + if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) return true; - P.p.cmdBase.cmdHelp.updateHelp(); + // Players with the any withdraw can do. + if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) return true; - oldMoneyDoTransfer(); - } + // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. + if (i == you) return true; - public static boolean shouldBeUsed() - { - return Conf.econEnabled && econ != null && econ.isEnabled(); - } - - public static boolean isSetup() - { - return econ != null; - } + // A faction can always transfer away the money of it's members and its own money... + // This will however probably never happen as a faction does not have free will. + // Ohh by the way... Yes it could. For daily rent to the faction. + if (i == fI && fI == fYou) return true; + // Factions can be controlled by members that are moderators... or any member if any member can withdraw. + if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer) i).getRole().value >= Role.MODERATOR.value)) + return true; - public static void modifyUniverseMoney(double delta) - { - if (!shouldBeUsed()) return; + // Otherwise you may not! ;,,; + i.msg("%s lacks permission to control %s's money.", i.describeTo(i, true), you.describeTo(i)); + return false; + } - if (Conf.econUniverseAccount == null) return; - if (Conf.econUniverseAccount.length() == 0) return; - if ( ! econ.hasAccount(Conf.econUniverseAccount)) return; + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + return transferMoney(invoker, from, to, amount, true); + } - modifyBalance(Conf.econUniverseAccount, delta); - } - - public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) - { - if (!shouldBeUsed()) - { - P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); - return; - } - to.msg("%s's balance is %s.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId()))); - } - - public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) - { - Faction fI = RelationUtil.getFaction(i); - Faction fYou = RelationUtil.getFaction(you); - - // This is a system invoker. Accept it. - if (fI == null) return true; - - // Bypassing players can do any kind of transaction - if (i instanceof FPlayer && ((FPlayer)i).isAdminBypassing()) return true; - - // Players with the any withdraw can do. - if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer)i).getPlayer())) return true; - - // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. - if (i == you) return true; - - // A faction can always transfer away the money of it's members and its own money... - // This will however probably never happen as a faction does not have free will. - // Ohh by the way... Yes it could. For daily rent to the faction. - if (i == fI && fI == fYou) return true; - - // Factions can be controlled by members that are moderators... or any member if any member can withdraw. - if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer)i).getRole().value >= Role.MODERATOR.value)) return true; - - // Otherwise you may not! ;,,; - i.msg("%s lacks permission to control %s's money.", i.describeTo(i, true), you.describeTo(i)); - return false; - } - - public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) - { - return transferMoney(invoker, from, to, amount, true); - } - public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) - { - if ( ! shouldBeUsed()) return false; + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { + if (!shouldBeUsed()) return false; - // The amount must be positive. - // If the amount is negative we must flip and multiply amount with -1. - if (amount < 0) - { - amount *= -1; - EconomyParticipator temp = from; - from = to; - to = temp; - } - - // Check the rights - if ( ! canIControllYou(invoker, from)) return false; - - // Is there enough money for the transaction to happen? - if ( ! econ.has(from.getAccountId(), amount)) - { - // There was not enough money to pay - if (invoker != null && notify) - invoker.msg("%s can't afford to transfer %s to %s.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); + // The amount must be positive. + // If the amount is negative we must flip and multiply amount with -1. + if (amount < 0) { + amount *= -1; + EconomyParticipator temp = from; + from = to; + to = temp; + } - return false; - } - - // Transfer money - EconomyResponse erw = econ.withdrawPlayer(from.getAccountId(), amount); + // Check the rights + if (!canIControllYou(invoker, from)) return false; - if (erw.transactionSuccess()) { - EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount); - if (erd.transactionSuccess()) { - if (notify) sendTransferInfo(invoker, from, to, amount); - return true; - } else { - // transaction failed, refund account - econ.depositPlayer(from.getAccountId(), amount); - } - } + // Is there enough money for the transaction to happen? + if (!econ.has(from.getAccountId(), amount)) { + // There was not enough money to pay + if (invoker != null && notify) + invoker.msg("%s can't afford to transfer %s to %s.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); - // if we get here something with the transaction failed - if (notify) - invoker.msg("Unable to transfer %s to %s from %s.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); + return false; + } - return false; - } - - public static Set getFplayers(EconomyParticipator ep) - { - Set fplayers = new HashSet(); - - if (ep == null) - { - // Add nothing - } - else if (ep instanceof FPlayer) - { - fplayers.add((FPlayer)ep); - } - else if (ep instanceof Faction) - { - fplayers.addAll(((Faction)ep).getFPlayers()); - } - - return fplayers; - } - - public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) - { - Set recipients = new HashSet(); - recipients.addAll(getFplayers(invoker)); - recipients.addAll(getFplayers(from)); - recipients.addAll(getFplayers(to)); - - if (invoker == null) - { - for (FPlayer recipient : recipients) - { - recipient.msg("%s was transfered from %s to %s.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); - } - } - else if (invoker == from) - { - for (FPlayer recipient : recipients) - { - recipient.msg("%s gave %s to %s.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); - } - } - else if (invoker == to) - { - for (FPlayer recipient : recipients) - { - recipient.msg("%s took %s from %s.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); - } - } - else - { - for (FPlayer recipient : recipients) - { - recipient.msg("%s transfered %s from %s to %s.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); - } - } - } + // Transfer money + EconomyResponse erw = econ.withdrawPlayer(from.getAccountId(), amount); - public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) - { - if ( ! shouldBeUsed()) return true; + if (erw.transactionSuccess()) { + EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount); + if (erd.transactionSuccess()) { + if (notify) sendTransferInfo(invoker, from, to, amount); + return true; + } else { + // transaction failed, refund account + econ.depositPlayer(from.getAccountId(), amount); + } + } - if ( ! econ.has(ep.getAccountId(), delta)) - { - if (toDoThis != null && !toDoThis.isEmpty()) - ep.msg("%s can't afford %s %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis); - return false; - } - return true; - } + // if we get here something with the transaction failed + if (notify) + invoker.msg("Unable to transfer %s to %s from %s.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); - public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) - { - if ( ! shouldBeUsed()) return false; + return false; + } - String acc = ep.getAccountId(); - String You = ep.describeTo(ep, true); - - if (delta == 0) - { - // no money actually transferred? + public static Set getFplayers(EconomyParticipator ep) { + Set fplayers = new HashSet(); + + if (ep == null) { + // Add nothing + } else if (ep instanceof FPlayer) { + fplayers.add((FPlayer) ep); + } else if (ep instanceof Faction) { + fplayers.addAll(((Faction) ep).getFPlayers()); + } + + return fplayers; + } + + public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + Set recipients = new HashSet(); + recipients.addAll(getFplayers(invoker)); + recipients.addAll(getFplayers(from)); + recipients.addAll(getFplayers(to)); + + if (invoker == null) { + for (FPlayer recipient : recipients) { + recipient.msg("%s was transfered from %s to %s.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } else if (invoker == from) { + for (FPlayer recipient : recipients) { + recipient.msg("%s gave %s to %s.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); + } + } else if (invoker == to) { + for (FPlayer recipient : recipients) { + recipient.msg("%s took %s from %s.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); + } + } else { + for (FPlayer recipient : recipients) { + recipient.msg("%s transfered %s from %s to %s.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } + } + + public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) { + if (!shouldBeUsed()) return true; + + if (!econ.has(ep.getAccountId(), delta)) { + if (toDoThis != null && !toDoThis.isEmpty()) + ep.msg("%s can't afford %s %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis); + return false; + } + return true; + } + + public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { + if (!shouldBeUsed()) return false; + + String acc = ep.getAccountId(); + String You = ep.describeTo(ep, true); + + if (delta == 0) { + // no money actually transferred? // ep.msg("%s didn't have to pay anything %s.", You, forDoingThis); // might be for gains, might be for losses - return true; - } + return true; + } - if (delta > 0) - { - // The player should gain money - // The account might not have enough space - EconomyResponse er = econ.depositPlayer(acc, delta); - if (er.transactionSuccess()) { - modifyUniverseMoney(-delta); - if (forDoingThis != null && !forDoingThis.isEmpty()) - ep.msg("%s gained %s %s.", You, moneyString(delta), forDoingThis); - return true; - } else { - // transfer to account failed - if (forDoingThis != null && !forDoingThis.isEmpty()) - ep.msg("%s would have gained %s %s, but the deposit failed.", You, moneyString(delta), forDoingThis); - return false; - } - } - else - { - // The player should loose money - // The player might not have enough. - - if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) - { - // There is enough money to pay - modifyUniverseMoney(-delta); - if (forDoingThis != null && !forDoingThis.isEmpty()) - ep.msg("%s lost %s %s.", You, moneyString(-delta), forDoingThis); - return true; - } - else - { - // There was not enough money to pay - if (toDoThis != null && !toDoThis.isEmpty()) - ep.msg("%s can't afford %s %s.", You, moneyString(-delta), toDoThis); - return false; - } - } - } + if (delta > 0) { + // The player should gain money + // The account might not have enough space + EconomyResponse er = econ.depositPlayer(acc, delta); + if (er.transactionSuccess()) { + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) + ep.msg("%s gained %s %s.", You, moneyString(delta), forDoingThis); + return true; + } else { + // transfer to account failed + if (forDoingThis != null && !forDoingThis.isEmpty()) + ep.msg("%s would have gained %s %s, but the deposit failed.", You, moneyString(delta), forDoingThis); + return false; + } + } else { + // The player should loose money + // The player might not have enough. - // format money string based on server's set currency type, like "24 gold" or "$24.50" - public static String moneyString(double amount) - { - return econ.format(amount); - } - - public static void oldMoneyDoTransfer() - { - if ( ! shouldBeUsed()) return; - - for (Faction faction : Factions.i.get()) - { - if (faction.money > 0) - { - econ.depositPlayer(faction.getAccountId(), faction.money); - faction.money = 0; - } - } - } + if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) { + // There is enough money to pay + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) + ep.msg("%s lost %s %s.", You, moneyString(-delta), forDoingThis); + return true; + } else { + // There was not enough money to pay + if (toDoThis != null && !toDoThis.isEmpty()) + ep.msg("%s can't afford %s %s.", You, moneyString(-delta), toDoThis); + return false; + } + } + } - // calculate the cost for claiming land - public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) - { - if ( ! shouldBeUsed()) - { - return 0d; - } + // format money string based on server's set currency type, like "24 gold" or "$24.50" + public static String moneyString(double amount) { + return econ.format(amount); + } - // basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction - return Conf.econCostClaimWilderness - + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) - - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus: 0); - } + public static void oldMoneyDoTransfer() { + if (!shouldBeUsed()) return; - // calculate refund amount for unclaiming land - public static double calculateClaimRefund(int ownedLand) - { - return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier; - } + for (Faction faction : Factions.i.get()) { + if (faction.money > 0) { + econ.depositPlayer(faction.getAccountId(), faction.money); + faction.money = 0; + } + } + } - // calculate value of all owned land - public static double calculateTotalLandValue(int ownedLand) - { - double amount = 0; - for (int x = 0; x < ownedLand; x++) { - amount += calculateClaimCost(x, false); - } - return amount; - } + // calculate the cost for claiming land + public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) { + if (!shouldBeUsed()) { + return 0d; + } - // calculate refund amount for all owned land - public static double calculateTotalLandRefund(int ownedLand) - { - return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier; - } + // basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction + return Conf.econCostClaimWilderness + + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) + - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0); + } + + // calculate refund amount for unclaiming land + public static double calculateClaimRefund(int ownedLand) { + return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier; + } + + // calculate value of all owned land + public static double calculateTotalLandValue(int ownedLand) { + double amount = 0; + for (int x = 0; x < ownedLand; x++) { + amount += calculateClaimCost(x, false); + } + return amount; + } + + // calculate refund amount for all owned land + public static double calculateTotalLandRefund(int ownedLand) { + return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier; + } - // -------------------------------------------- // - // Standard account management methods - // -------------------------------------------- // + // -------------------------------------------- // + // Standard account management methods + // -------------------------------------------- // - public static boolean hasAccount(String name) - { - return econ.hasAccount(name); - } + public static boolean hasAccount(String name) { + return econ.hasAccount(name); + } - public static double getBalance(String account) - { - return econ.getBalance(account); - } + public static double getBalance(String account) { + return econ.getBalance(account); + } - public static boolean setBalance(String account, double amount) - { - double current = econ.getBalance(account); - if (current > amount) - return econ.withdrawPlayer(account, current - amount).transactionSuccess(); - else - return econ.depositPlayer(account, amount - current).transactionSuccess(); - } + public static boolean setBalance(String account, double amount) { + double current = econ.getBalance(account); + if (current > amount) + return econ.withdrawPlayer(account, current - amount).transactionSuccess(); + else + return econ.depositPlayer(account, amount - current).transactionSuccess(); + } - public static boolean modifyBalance(String account, double amount) - { - if (amount < 0) - return econ.withdrawPlayer(account, -amount).transactionSuccess(); - else - return econ.depositPlayer(account, amount).transactionSuccess(); - } + public static boolean modifyBalance(String account, double amount) { + if (amount < 0) + return econ.withdrawPlayer(account, -amount).transactionSuccess(); + else + return econ.depositPlayer(account, amount).transactionSuccess(); + } - public static boolean deposit(String account, double amount) - { - return econ.depositPlayer(account, amount).transactionSuccess(); - } + public static boolean deposit(String account, double amount) { + return econ.depositPlayer(account, amount).transactionSuccess(); + } - public static boolean withdraw(String account, double amount) - { - return econ.withdrawPlayer(account, amount).transactionSuccess(); - } + public static boolean withdraw(String account, double amount) { + return econ.withdrawPlayer(account, amount).transactionSuccess(); + } } diff --git a/src/main/java/com/massivecraft/factions/integration/EssentialsFeatures.java b/src/main/java/com/massivecraft/factions/integration/EssentialsFeatures.java index 2b4b8af1..09768984 100644 --- a/src/main/java/com/massivecraft/factions/integration/EssentialsFeatures.java +++ b/src/main/java/com/massivecraft/factions/integration/EssentialsFeatures.java @@ -1,22 +1,20 @@ package com.massivecraft.factions.integration; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.Location; -import org.bukkit.plugin.Plugin; - -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.P; - import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.Teleport; import com.earth2me.essentials.Trade; import com.earth2me.essentials.chat.EssentialsChat; import com.earth2me.essentials.chat.EssentialsLocalChatEvent; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.P; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; /* @@ -26,111 +24,90 @@ import com.earth2me.essentials.chat.EssentialsLocalChatEvent; // silence deprecation warnings with this old interface @SuppressWarnings("deprecation") -public class EssentialsFeatures -{ - private static EssentialsChat essChat; - private static IEssentials essentials; +public class EssentialsFeatures { + private static EssentialsChat essChat; + private static IEssentials essentials; - public static void setup() - { - // integrate main essentials plugin - // TODO: this is the old Essentials method not supported in 3.0... probably needs to eventually be moved to EssentialsOldVersionFeatures and new method implemented - if (essentials == null) - { - Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); - if (ess != null && ess.isEnabled()) - essentials = (IEssentials)ess; - } + public static void setup() { + // integrate main essentials plugin + // TODO: this is the old Essentials method not supported in 3.0... probably needs to eventually be moved to EssentialsOldVersionFeatures and new method implemented + if (essentials == null) { + Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); + if (ess != null && ess.isEnabled()) + essentials = (IEssentials) ess; + } - // integrate chat - if (essChat != null) return; + // integrate chat + if (essChat != null) return; - Plugin test = Bukkit.getServer().getPluginManager().getPlugin("EssentialsChat"); - if (test == null || !test.isEnabled()) return; + Plugin test = Bukkit.getServer().getPluginManager().getPlugin("EssentialsChat"); + if (test == null || !test.isEnabled()) return; - essChat = (EssentialsChat)test; + essChat = (EssentialsChat) test; - // try newer Essentials 3.x integration method - try - { - Class.forName("com.earth2me.essentials.chat.EssentialsLocalChatEvent"); - integrateChat(essChat); - } - catch (ClassNotFoundException ex) - { - // no? try older Essentials 2.x integration method - try - { - EssentialsOldVersionFeatures.integrateChat(essChat); - } - catch (NoClassDefFoundError ex2) { /* no known integration method, then */ } - } - } + // try newer Essentials 3.x integration method + try { + Class.forName("com.earth2me.essentials.chat.EssentialsLocalChatEvent"); + integrateChat(essChat); + } catch (ClassNotFoundException ex) { + // no? try older Essentials 2.x integration method + try { + EssentialsOldVersionFeatures.integrateChat(essChat); + } catch (NoClassDefFoundError ex2) { /* no known integration method, then */ } + } + } - public static void unhookChat() - { - if (essChat == null) return; + public static void unhookChat() { + if (essChat == null) return; - try - { - EssentialsOldVersionFeatures.unhookChat(); - } - catch (NoClassDefFoundError ex) {} - } + try { + EssentialsOldVersionFeatures.unhookChat(); + } catch (NoClassDefFoundError ex) { + } + } - // return false if feature is disabled or Essentials isn't available - public static boolean handleTeleport(Player player, Location loc) - { - if ( ! Conf.homesTeleportCommandEssentialsIntegration || essentials == null) return false; + // return false if feature is disabled or Essentials isn't available + public static boolean handleTeleport(Player player, Location loc) { + if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) return false; - Teleport teleport = (Teleport) essentials.getUser(player).getTeleport(); - Trade trade = new Trade(Conf.econCostHome, essentials); - try - { - teleport.teleport(loc, trade); - } - catch (Exception e) - { - player.sendMessage(ChatColor.RED.toString()+e.getMessage()); - } - return true; - } + Teleport teleport = (Teleport) essentials.getUser(player).getTeleport(); + Trade trade = new Trade(Conf.econCostHome, essentials); + try { + teleport.teleport(loc, trade); + } catch (Exception e) { + player.sendMessage(ChatColor.RED.toString() + e.getMessage()); + } + return true; + } - public static void integrateChat(EssentialsChat instance) - { - essChat = instance; - try - { - Bukkit.getServer().getPluginManager().registerEvents(new LocalChatListener(), P.p); - P.p.log("Found and will integrate chat with newer "+essChat.getDescription().getFullName()); + public static void integrateChat(EssentialsChat instance) { + essChat = instance; + try { + Bukkit.getServer().getPluginManager().registerEvents(new LocalChatListener(), P.p); + P.p.log("Found and will integrate chat with newer " + essChat.getDescription().getFullName()); - // curly braces used to be accepted by the format string EssentialsChat but no longer are, so... deal with chatTagReplaceString which might need updating - if (Conf.chatTagReplaceString.contains("{")) - { - Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]"); - P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you."); - } - } - catch (NoSuchMethodError ex) - { - essChat = null; - } - } + // curly braces used to be accepted by the format string EssentialsChat but no longer are, so... deal with chatTagReplaceString which might need updating + if (Conf.chatTagReplaceString.contains("{")) { + Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]"); + P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you."); + } + } catch (NoSuchMethodError ex) { + essChat = null; + } + } - private static class LocalChatListener implements Listener - { - @SuppressWarnings("unused") - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerChat(EssentialsLocalChatEvent event) - { - Player speaker = event.getPlayer(); - String format = event.getFormat(); - format = format.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(speaker)); - event.setFormat(format); - // NOTE: above doesn't do relation coloring. if/when we can get a local recipient list from EssentialsLocalChatEvent, we'll probably - // want to pass it on to FactionsPlayerListener.onPlayerChat(PlayerChatEvent event) rather than duplicating code - } - } + private static class LocalChatListener implements Listener { + @SuppressWarnings("unused") + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerChat(EssentialsLocalChatEvent event) { + Player speaker = event.getPlayer(); + String format = event.getFormat(); + format = format.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(speaker)); + event.setFormat(format); + // NOTE: above doesn't do relation coloring. if/when we can get a local recipient list from EssentialsLocalChatEvent, we'll probably + // want to pass it on to FactionsPlayerListener.onPlayerChat(PlayerChatEvent event) rather than duplicating code + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/EssentialsOldVersionFeatures.java b/src/main/java/com/massivecraft/factions/integration/EssentialsOldVersionFeatures.java index 50591743..f1e4ac17 100644 --- a/src/main/java/com/massivecraft/factions/integration/EssentialsOldVersionFeatures.java +++ b/src/main/java/com/massivecraft/factions/integration/EssentialsOldVersionFeatures.java @@ -1,59 +1,47 @@ package com.massivecraft.factions.integration; -import org.bukkit.entity.Player; -import org.bukkit.event.player.AsyncPlayerChatEvent; - -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.P; - import com.earth2me.essentials.chat.EssentialsChat; import com.earth2me.essentials.chat.IEssentialsChatListener; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.P; +import org.bukkit.entity.Player; +import org.bukkit.event.player.AsyncPlayerChatEvent; /* * This Essentials integration handler is for older 2.x.x versions of Essentials which have "IEssentialsChatListener" */ -public class EssentialsOldVersionFeatures -{ - private static EssentialsChat essChat; +public class EssentialsOldVersionFeatures { + private static EssentialsChat essChat; - public static void integrateChat(EssentialsChat instance) - { - essChat = instance; - try - { - essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener() - { - public boolean shouldHandleThisChat(AsyncPlayerChatEvent event) - { - return P.p.shouldLetFactionsHandleThisChat(event); - } - public String modifyMessage(AsyncPlayerChatEvent event, Player target, String message) - { - return message.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(event.getPlayer())); - } - }); - P.p.log("Found and will integrate chat with "+essChat.getDescription().getFullName()); + public static void integrateChat(EssentialsChat instance) { + essChat = instance; + try { + essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener() { + public boolean shouldHandleThisChat(AsyncPlayerChatEvent event) { + return P.p.shouldLetFactionsHandleThisChat(event); + } - // As of Essentials 2.8+, curly braces are not accepted and are instead replaced with square braces, so... deal with it - if (essChat.getDescription().getVersion().startsWith("2.8.") && Conf.chatTagReplaceString.contains("{")) - { - Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]"); - P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you."); - } - } - catch (NoSuchMethodError ex) - { - essChat = null; - } - } + public String modifyMessage(AsyncPlayerChatEvent event, Player target, String message) { + return message.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(event.getPlayer())); + } + }); + P.p.log("Found and will integrate chat with " + essChat.getDescription().getFullName()); - public static void unhookChat() - { - if (essChat != null) - { - essChat.removeEssentialsChatListener("Factions"); - } - } + // As of Essentials 2.8+, curly braces are not accepted and are instead replaced with square braces, so... deal with it + if (essChat.getDescription().getVersion().startsWith("2.8.") && Conf.chatTagReplaceString.contains("{")) { + Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]"); + P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you."); + } + } catch (NoSuchMethodError ex) { + essChat = null; + } + } + + public static void unhookChat() { + if (essChat != null) { + essChat.removeEssentialsChatListener("Factions"); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/LWCFeatures.java b/src/main/java/com/massivecraft/factions/integration/LWCFeatures.java index b7e904be..19192a43 100644 --- a/src/main/java/com/massivecraft/factions/integration/LWCFeatures.java +++ b/src/main/java/com/massivecraft/factions/integration/LWCFeatures.java @@ -1,90 +1,72 @@ package com.massivecraft.factions.integration; +import com.griefcraft.lwc.LWC; +import com.griefcraft.lwc.LWCPlugin; +import com.massivecraft.factions.*; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.plugin.Plugin; + import java.util.LinkedList; import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.plugin.Plugin; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; +public class LWCFeatures { + private static LWC lwc; -import com.griefcraft.lwc.LWC; -import com.griefcraft.lwc.LWCPlugin; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; + public static void setup() { + Plugin test = Bukkit.getServer().getPluginManager().getPlugin("LWC"); + if (test == null || !test.isEnabled()) return; -public class LWCFeatures -{ - private static LWC lwc; + lwc = ((LWCPlugin) test).getLWC(); + P.p.log("Successfully hooked into LWC!" + (Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\").")); + } - public static void setup() - { - Plugin test = Bukkit.getServer().getPluginManager().getPlugin("LWC"); - if(test == null || !test.isEnabled()) return; + public static boolean getEnabled() { + return Conf.lwcIntegration && lwc != null; + } - lwc = ((LWCPlugin)test).getLWC(); - P.p.log("Successfully hooked into LWC!"+(Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\").")); - } + public static void clearOtherChests(FLocation flocation, Faction faction) { + Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16); + if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error + Chunk chunk = location.getChunk(); + BlockState[] blocks = chunk.getTileEntities(); + List chests = new LinkedList(); - public static boolean getEnabled() - { - return Conf.lwcIntegration && lwc != null; - } + for (int x = 0; x < blocks.length; x++) { + if (blocks[x].getType() == Material.CHEST) { + chests.add(blocks[x].getBlock()); + } + } - public static void clearOtherChests(FLocation flocation, Faction faction) - { - Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16); - if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error - Chunk chunk = location.getChunk(); - BlockState[] blocks = chunk.getTileEntities(); - List chests = new LinkedList(); - - for(int x = 0; x < blocks.length; x++) - { - if(blocks[x].getType() == Material.CHEST) - { - chests.add(blocks[x].getBlock()); - } - } - - for(int x = 0; x < chests.size(); x++) - { - if(lwc.findProtection(chests.get(x)) != null) - { - if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner()))) - lwc.findProtection(chests.get(x)).remove(); - } - } - } - - public static void clearAllChests(FLocation flocation) - { - Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16); - if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error - Chunk chunk = location.getChunk(); - BlockState[] blocks = chunk.getTileEntities(); - List chests = new LinkedList(); - - for(int x = 0; x < blocks.length; x++) - { - if(blocks[x].getType() == Material.CHEST) - { - chests.add(blocks[x].getBlock()); - } - } - - for(int x = 0; x < chests.size(); x++) - { - if(lwc.findProtection(chests.get(x)) != null) - { - lwc.findProtection(chests.get(x)).remove(); - } - } - } + for (int x = 0; x < chests.size(); x++) { + if (lwc.findProtection(chests.get(x)) != null) { + if (!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner()))) + lwc.findProtection(chests.get(x)).remove(); + } + } + } + + public static void clearAllChests(FLocation flocation) { + Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16); + if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error + Chunk chunk = location.getChunk(); + BlockState[] blocks = chunk.getTileEntities(); + List chests = new LinkedList(); + + for (int x = 0; x < blocks.length; x++) { + if (blocks[x].getType() == Material.CHEST) { + chests.add(blocks[x].getBlock()); + } + } + + for (int x = 0; x < chests.size(); x++) { + if (lwc.findProtection(chests.get(x)) != null) { + lwc.findProtection(chests.get(x)).remove(); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/SpoutFeatures.java b/src/main/java/com/massivecraft/factions/integration/SpoutFeatures.java index 595ecc01..4c0d2ffc 100644 --- a/src/main/java/com/massivecraft/factions/integration/SpoutFeatures.java +++ b/src/main/java/com/massivecraft/factions/integration/SpoutFeatures.java @@ -1,329 +1,298 @@ package com.massivecraft.factions.integration; +import com.massivecraft.factions.*; +import com.massivecraft.factions.struct.Relation; +import com.massivecraft.factions.struct.Role; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.getspout.spoutapi.SpoutManager; +import org.getspout.spoutapi.gui.Color; +import org.getspout.spoutapi.player.SpoutPlayer; + import java.util.Set; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.P; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.plugin.Plugin; -import org.bukkit.entity.Player; +public class SpoutFeatures { + private transient static boolean spoutMe = false; + private transient static SpoutMainListener mainListener; + private transient static boolean listenersHooked; -import com.massivecraft.factions.struct.Relation; -import com.massivecraft.factions.struct.Role; + public static void setup() { + Plugin test = Bukkit.getServer().getPluginManager().getPlugin("Spout"); + if (test == null || !test.isEnabled()) return; -import org.getspout.spoutapi.gui.Color; -import org.getspout.spoutapi.player.SpoutPlayer; -import org.getspout.spoutapi.SpoutManager; + setAvailable(true, test.getDescription().getFullName()); + } + + // set integration availability + public static void setAvailable(boolean enable, String pluginName) { + spoutMe = enable; + if (!spoutMe) return; + + P.p.log("Found and will use features of " + pluginName); + + if (!listenersHooked) { + listenersHooked = true; + mainListener = new SpoutMainListener(); + Bukkit.getServer().getPluginManager().registerEvents(mainListener, P.p); + } + } + + // If we're successfully hooked into Spout + public static boolean enabled() { + return spoutMe; + } + + // If Spout is available and the specified Player is running the Spoutcraft client + public static boolean availableFor(Player player) { + return spoutMe && SpoutManager.getPlayer(player).isSpoutCraftEnabled(); + } -public class SpoutFeatures -{ - private transient static boolean spoutMe = false; - private transient static SpoutMainListener mainListener; - private transient static boolean listenersHooked; + // update displayed current territory for all players inside a specified chunk; if specified chunk is null, then simply update everyone online + public static void updateTerritoryDisplayLoc(FLocation fLoc) { + if (!enabled()) + return; - public static void setup() - { - Plugin test = Bukkit.getServer().getPluginManager().getPlugin("Spout"); - if (test == null || !test.isEnabled()) return; + Set players = FPlayers.i.getOnline(); - setAvailable(true, test.getDescription().getFullName()); - } + for (FPlayer player : players) { + if (fLoc == null) + mainListener.updateTerritoryDisplay(player, false); + else if (player.getLastStoodAt().equals(fLoc)) + mainListener.updateTerritoryDisplay(player, true); + } + } - // set integration availability - public static void setAvailable(boolean enable, String pluginName) - { - spoutMe = enable; - if (!spoutMe) return; + // update displayed current territory for specified player; returns false if unsuccessful + public static boolean updateTerritoryDisplay(FPlayer player) { + if (!enabled()) + return false; - P.p.log("Found and will use features of "+pluginName); + return mainListener.updateTerritoryDisplay(player, true); + } - if (!listenersHooked) - { - listenersHooked = true; - mainListener = new SpoutMainListener(); - Bukkit.getServer().getPluginManager().registerEvents(mainListener, P.p); - } - } + // update owner list for all players inside a specified chunk; if specified chunk is null, then simply update everyone online + public static void updateOwnerListLoc(FLocation fLoc) { + if (!enabled()) + return; - // If we're successfully hooked into Spout - public static boolean enabled() - { - return spoutMe; - } + Set players = FPlayers.i.getOnline(); - // If Spout is available and the specified Player is running the Spoutcraft client - public static boolean availableFor(Player player) - { - return spoutMe && SpoutManager.getPlayer(player).isSpoutCraftEnabled(); - } + for (FPlayer player : players) { + if (fLoc == null || player.getLastStoodAt().equals(fLoc)) + mainListener.updateOwnerList(player); + } + } + + // update owner list for specified player + public static void updateOwnerList(FPlayer player) { + if (!enabled()) + return; + + mainListener.updateOwnerList(player); + } + + public static void playerDisconnect(FPlayer player) { + if (!enabled()) + return; + + mainListener.removeTerritoryLabels(player.getName()); + } - // update displayed current territory for all players inside a specified chunk; if specified chunk is null, then simply update everyone online - public static void updateTerritoryDisplayLoc(FLocation fLoc) - { - if (!enabled()) - return; + // update all appearances between every player + public static void updateAppearances() { + if (!enabled()) + return; - Set players = FPlayers.i.getOnline(); + Set players = FPlayers.i.getOnline(); - for (FPlayer player : players) - { - if (fLoc == null) - mainListener.updateTerritoryDisplay(player, false); - else if (player.getLastStoodAt().equals(fLoc)) - mainListener.updateTerritoryDisplay(player, true); - } - } + for (FPlayer playerA : players) { + for (FPlayer playerB : players) { + updateSingle(playerB, playerA); + } + } + } - // update displayed current territory for specified player; returns false if unsuccessful - public static boolean updateTerritoryDisplay(FPlayer player) - { - if (!enabled()) - return false; + // update all appearances related to a specific player + public static void updateAppearances(Player player) { + if (!enabled() || player == null) + return; - return mainListener.updateTerritoryDisplay(player, true); - } + Set players = FPlayers.i.getOnline(); + FPlayer playerA = FPlayers.i.get(player); - // update owner list for all players inside a specified chunk; if specified chunk is null, then simply update everyone online - public static void updateOwnerListLoc(FLocation fLoc) - { - if (!enabled()) - return; + for (FPlayer playerB : players) { + updateSingle(playerB, playerA); + updateSingle(playerA, playerB); + } + } - Set players = FPlayers.i.getOnline(); + // as above method, but with a delay added; useful for after-login update which doesn't always propagate if done immediately + public static void updateAppearancesShortly(final Player player) { + P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, new Runnable() { + @Override + public void run() { + updateAppearances(player); + } + }, 100); + } - for (FPlayer player : players) - { - if (fLoc == null || player.getLastStoodAt().equals(fLoc)) - mainListener.updateOwnerList(player); - } - } + // update all appearances related to a single faction + public static void updateAppearances(Faction faction) { + if (!enabled() || faction == null) + return; - // update owner list for specified player - public static void updateOwnerList(FPlayer player) - { - if (!enabled()) - return; + Set players = FPlayers.i.getOnline(); + Faction factionA; - mainListener.updateOwnerList(player); - } + for (FPlayer playerA : players) { + factionA = playerA.getFaction(); - public static void playerDisconnect(FPlayer player) - { - if (!enabled()) - return; + for (FPlayer playerB : players) { + if (factionA != faction && playerB.getFaction() != faction) + continue; - mainListener.removeTerritoryLabels(player.getName()); - } + updateSingle(playerB, playerA); + } + } + } + + // update all appearances between two factions + public static void updateAppearances(Faction factionA, Faction factionB) { + if (!enabled() || factionA == null || factionB == null) + return; + + for (FPlayer playerA : factionA.getFPlayersWhereOnline(true)) { + for (FPlayer playerB : factionB.getFPlayersWhereOnline(true)) { + updateSingle(playerB, playerA); + updateSingle(playerA, playerB); + } + } + } - // update all appearances between every player - public static void updateAppearances() - { - if (!enabled()) - return; + // update a single appearance; internal use only by above public methods + private static void updateSingle(FPlayer viewer, FPlayer viewed) { + if (viewer == null || viewed == null) + return; - Set players = FPlayers.i.getOnline(); + Faction viewedFaction = viewed.getFaction(); + if (viewedFaction == null) + return; - for (FPlayer playerA : players) - { - for (FPlayer playerB : players) - { - updateSingle(playerB, playerA); - } - } - } + // these still end up returning null on occasion at this point, mucking up the SpoutManager.getPlayer() method + if (viewer.getPlayer() == null || viewed.getPlayer() == null) + return; - // update all appearances related to a specific player - public static void updateAppearances(Player player) - { - if (!enabled() || player == null) - return; + SpoutPlayer pViewer = SpoutManager.getPlayer(viewer.getPlayer()); + SpoutPlayer pViewed = SpoutManager.getPlayer(viewed.getPlayer()); + if (pViewed == null || pViewer == null) + return; - Set players = FPlayers.i.getOnline(); - FPlayer playerA = FPlayers.i.get(player); + String viewedTitle = viewed.getTitle(); + Role viewedRole = viewed.getRole(); - for (FPlayer playerB : players) - { - updateSingle(playerB, playerA); - updateSingle(playerA, playerB); - } - } + if ((Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames) && viewer != viewed) { + if (viewedFaction.isNormal()) { + String addTag = ""; + if (Conf.spoutFactionTagsOverNames) + addTag += viewedFaction.getTag(viewed.getColorTo(viewer).toString() + "[") + "]"; - // as above method, but with a delay added; useful for after-login update which doesn't always propagate if done immediately - public static void updateAppearancesShortly(final Player player) - { - P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, new Runnable() - { - @Override - public void run() - { - updateAppearances(player); - } - }, 100); - } + String rolePrefix = viewedRole.getPrefix(); + if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty())) + addTag += (addTag.isEmpty() ? "" : " ") + viewedRole.getPrefix() + viewedTitle; - // update all appearances related to a single faction - public static void updateAppearances(Faction faction) - { - if (!enabled() || faction == null) - return; + pViewed.setTitleFor(pViewer, addTag + "\n" + pViewed.getDisplayName()); + } else { + pViewed.setTitleFor(pViewer, pViewed.getDisplayName()); + } + } - Set players = FPlayers.i.getOnline(); - Faction factionA; + if + ( + ( + Conf.spoutFactionAdminCapes + && + viewedRole.equals(Role.ADMIN) + ) + || + ( + Conf.spoutFactionModeratorCapes + && + viewedRole.equals(Role.MODERATOR) + ) + ) { + Relation relation = viewer.getRelationTo(viewed); + String cape = ""; + if (!viewedFaction.isNormal()) { + // yeah, no cape if no faction + } else if (viewedFaction.isPeaceful()) + cape = Conf.capePeaceful; + else if (relation.isNeutral()) + cape = Conf.capeNeutral; + else if (relation.isMember()) + cape = Conf.capeMember; + else if (relation.isEnemy()) + cape = Conf.capeEnemy; + else if (relation.isAlly()) + cape = Conf.capeAlly; - for (FPlayer playerA : players) - { - factionA = playerA.getFaction(); - - for (FPlayer playerB : players) - { - if (factionA != faction && playerB.getFaction() != faction) - continue; - - updateSingle(playerB, playerA); - } - } - } - - // update all appearances between two factions - public static void updateAppearances(Faction factionA, Faction factionB) - { - if (!enabled() || factionA == null || factionB == null) - return; - - for (FPlayer playerA : factionA.getFPlayersWhereOnline(true)) - { - for (FPlayer playerB : factionB.getFPlayersWhereOnline(true)) - { - updateSingle(playerB, playerA); - updateSingle(playerA, playerB); - } - } - } + if (cape.isEmpty()) + pViewed.resetCapeFor(pViewer); + else + pViewed.setCapeFor(pViewer, cape); + } else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes) { + pViewed.resetCapeFor(pViewer); + } + } - // update a single appearance; internal use only by above public methods - private static void updateSingle(FPlayer viewer, FPlayer viewed) - { - if (viewer == null || viewed == null) - return; + // method to convert a Bukkit ChatColor to a Spout Color + protected static Color getSpoutColor(ChatColor inColor, int alpha) { + if (inColor == null) + return SpoutFixedColor(191, 191, 191, alpha); - Faction viewedFaction = viewed.getFaction(); - if (viewedFaction == null) - return; + switch (inColor.getChar()) { + case 0x1: + return SpoutFixedColor(0, 0, 191, alpha); + case 0x2: + return SpoutFixedColor(0, 191, 0, alpha); + case 0x3: + return SpoutFixedColor(0, 191, 191, alpha); + case 0x4: + return SpoutFixedColor(191, 0, 0, alpha); + case 0x5: + return SpoutFixedColor(191, 0, 191, alpha); + case 0x6: + return SpoutFixedColor(191, 191, 0, alpha); + case 0x7: + return SpoutFixedColor(191, 191, 191, alpha); + case 0x8: + return SpoutFixedColor(64, 64, 64, alpha); + case 0x9: + return SpoutFixedColor(64, 64, 255, alpha); + case 0xA: + return SpoutFixedColor(64, 255, 64, alpha); + case 0xB: + return SpoutFixedColor(64, 255, 255, alpha); + case 0xC: + return SpoutFixedColor(255, 64, 64, alpha); + case 0xD: + return SpoutFixedColor(255, 64, 255, alpha); + case 0xE: + return SpoutFixedColor(255, 255, 64, alpha); + case 0xF: + return SpoutFixedColor(255, 255, 255, alpha); + default: + return SpoutFixedColor(0, 0, 0, alpha); + } + } - // these still end up returning null on occasion at this point, mucking up the SpoutManager.getPlayer() method - if (viewer.getPlayer() == null || viewed.getPlayer() == null) - return; - - SpoutPlayer pViewer = SpoutManager.getPlayer(viewer.getPlayer()); - SpoutPlayer pViewed = SpoutManager.getPlayer(viewed.getPlayer()); - if (pViewed == null || pViewer == null) - return; - - String viewedTitle = viewed.getTitle(); - Role viewedRole = viewed.getRole(); - - if ((Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames) && viewer != viewed) - { - if (viewedFaction.isNormal()) - { - String addTag = ""; - if (Conf.spoutFactionTagsOverNames) - addTag += viewedFaction.getTag(viewed.getColorTo(viewer).toString() + "[") + "]"; - - String rolePrefix = viewedRole.getPrefix(); - if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty())) - addTag += (addTag.isEmpty() ? "" : " ") + viewedRole.getPrefix() + viewedTitle; - - pViewed.setTitleFor(pViewer, addTag + "\n" + pViewed.getDisplayName()); - } - else - { - pViewed.setTitleFor(pViewer, pViewed.getDisplayName()); - } - } - - if - ( - ( - Conf.spoutFactionAdminCapes - && - viewedRole.equals(Role.ADMIN) - ) - || - ( - Conf.spoutFactionModeratorCapes - && - viewedRole.equals(Role.MODERATOR) - ) - ) - { - Relation relation = viewer.getRelationTo(viewed); - String cape = ""; - if (!viewedFaction.isNormal()) - { - // yeah, no cape if no faction - } - else if (viewedFaction.isPeaceful()) - cape = Conf.capePeaceful; - else if (relation.isNeutral()) - cape = Conf.capeNeutral; - else if (relation.isMember()) - cape = Conf.capeMember; - else if (relation.isEnemy()) - cape = Conf.capeEnemy; - else if (relation.isAlly()) - cape = Conf.capeAlly; - - if (cape.isEmpty()) - pViewed.resetCapeFor(pViewer); - else - pViewed.setCapeFor(pViewer, cape); - } - else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes) - { - pViewed.resetCapeFor(pViewer); - } - } - - - // method to convert a Bukkit ChatColor to a Spout Color - protected static Color getSpoutColor(ChatColor inColor, int alpha) - { - if (inColor == null) - return SpoutFixedColor(191, 191, 191, alpha); - - switch (inColor.getChar()) - { - case 0x1: return SpoutFixedColor(0, 0, 191, alpha); - case 0x2: return SpoutFixedColor(0, 191, 0, alpha); - case 0x3: return SpoutFixedColor(0, 191, 191, alpha); - case 0x4: return SpoutFixedColor(191, 0, 0, alpha); - case 0x5: return SpoutFixedColor(191, 0, 191, alpha); - case 0x6: return SpoutFixedColor(191, 191, 0, alpha); - case 0x7: return SpoutFixedColor(191, 191, 191, alpha); - case 0x8: return SpoutFixedColor(64, 64, 64, alpha); - case 0x9: return SpoutFixedColor(64, 64, 255, alpha); - case 0xA: return SpoutFixedColor(64, 255, 64, alpha); - case 0xB: return SpoutFixedColor(64, 255, 255, alpha); - case 0xC: return SpoutFixedColor(255, 64, 64, alpha); - case 0xD: return SpoutFixedColor(255, 64, 255, alpha); - case 0xE: return SpoutFixedColor(255, 255, 64, alpha); - case 0xF: return SpoutFixedColor(255, 255, 255, alpha); - default: return SpoutFixedColor(0, 0, 0, alpha); - } - } - private static Color SpoutFixedColor(int r, int g, int b, int a) - { - return new Color(r/255.0f, g/255.0f, b/255.0f, a/255.0f); - } + private static Color SpoutFixedColor(int r, int g, int b, int a) { + return new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); + } } diff --git a/src/main/java/com/massivecraft/factions/integration/SpoutMainListener.java b/src/main/java/com/massivecraft/factions/integration/SpoutMainListener.java index b7843724..4bde7b3f 100644 --- a/src/main/java/com/massivecraft/factions/integration/SpoutMainListener.java +++ b/src/main/java/com/massivecraft/factions/integration/SpoutMainListener.java @@ -1,247 +1,217 @@ package com.massivecraft.factions.integration; -import java.util.HashMap; -import java.util.Map; - +import com.massivecraft.factions.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; - -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; - +import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.event.spout.SpoutCraftEnableEvent; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.player.SpoutPlayer; -import org.getspout.spoutapi.SpoutManager; + +import java.util.HashMap; +import java.util.Map; -public class SpoutMainListener implements Listener -{ - @EventHandler(priority = EventPriority.NORMAL) - public void onSpoutCraftEnable(SpoutCraftEnableEvent event) - { - final FPlayer me = FPlayers.i.get(event.getPlayer()); +public class SpoutMainListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL) + public void onSpoutCraftEnable(SpoutCraftEnableEvent event) { + final FPlayer me = FPlayers.i.get(event.getPlayer()); - SpoutFeatures.updateAppearances(me.getPlayer()); - updateTerritoryDisplay(me, true); - } + SpoutFeatures.updateAppearances(me.getPlayer()); + updateTerritoryDisplay(me, true); + } - //-----------------------------------------------------------------------------------------// - // Everything below this is handled in here to prevent errors on servers not running Spout - //-----------------------------------------------------------------------------------------// + //-----------------------------------------------------------------------------------------// + // Everything below this is handled in here to prevent errors on servers not running Spout + //-----------------------------------------------------------------------------------------// - private transient static Map territoryLabels = new HashMap(); - private transient static Map territoryChangeLabels = new HashMap(); - private transient static Map ownerLabels = new HashMap(); - private final static int SCREEN_WIDTH = 427; + private transient static Map territoryLabels = new HashMap(); + private transient static Map territoryChangeLabels = new HashMap(); + private transient static Map ownerLabels = new HashMap(); + private final static int SCREEN_WIDTH = 427; // private final static int SCREEN_HEIGHT = 240; - public boolean updateTerritoryDisplay(FPlayer player, boolean notify) - { - Player p = player.getPlayer(); - if (p == null) - return false; + public boolean updateTerritoryDisplay(FPlayer player, boolean notify) { + Player p = player.getPlayer(); + if (p == null) + return false; - SpoutPlayer sPlayer = SpoutManager.getPlayer(p); - if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && ! Conf.spoutTerritoryNoticeShow)) - return false; + SpoutPlayer sPlayer = SpoutManager.getPlayer(p); + if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && !Conf.spoutTerritoryNoticeShow)) + return false; - doLabels(player, sPlayer, notify); + doLabels(player, sPlayer, notify); - return true; - } + return true; + } - public void updateOwnerList(FPlayer player) - { - SpoutPlayer sPlayer = SpoutManager.getPlayer(player.getPlayer()); - if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && ! Conf.spoutTerritoryNoticeShow)) - return; + public void updateOwnerList(FPlayer player) { + SpoutPlayer sPlayer = SpoutManager.getPlayer(player.getPlayer()); + if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && !Conf.spoutTerritoryNoticeShow)) + return; - FLocation here = player.getLastStoodAt(); - Faction factionHere = Board.getFactionAt(here); + FLocation here = player.getLastStoodAt(); + Faction factionHere = Board.getFactionAt(here); - doOwnerList(player, sPlayer, here, factionHere); + doOwnerList(player, sPlayer, here, factionHere); - return; - } + return; + } - public void removeTerritoryLabels(String playerName) - { - territoryLabels.remove(playerName); - territoryChangeLabels.remove(playerName); - ownerLabels.remove(playerName); - } + public void removeTerritoryLabels(String playerName) { + territoryLabels.remove(playerName); + territoryChangeLabels.remove(playerName); + ownerLabels.remove(playerName); + } - private void doLabels(FPlayer player, SpoutPlayer sPlayer, boolean notify) - { - FLocation here = player.getLastStoodAt(); - Faction factionHere = Board.getFactionAt(here); - String tag = factionHere.getColorTo(player).toString() + factionHere.getTag(); + private void doLabels(FPlayer player, SpoutPlayer sPlayer, boolean notify) { + FLocation here = player.getLastStoodAt(); + Faction factionHere = Board.getFactionAt(here); + String tag = factionHere.getColorTo(player).toString() + factionHere.getTag(); - // ---------------------- - // Main territory display - // ---------------------- - if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0) - { - GenericLabel label; - if (territoryLabels.containsKey(player.getName())) - label = territoryLabels.get(player.getName()); - else - { - label = new GenericLabel(); - label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning - label.setScale(Conf.spoutTerritoryDisplaySize); + // ---------------------- + // Main territory display + // ---------------------- + if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0) { + GenericLabel label; + if (territoryLabels.containsKey(player.getName())) + label = territoryLabels.get(player.getName()); + else { + label = new GenericLabel(); + label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning + label.setScale(Conf.spoutTerritoryDisplaySize); - sPlayer.getMainScreen().attachWidget(P.p, label); - territoryLabels.put(player.getName(), label); - } + sPlayer.getMainScreen().attachWidget(P.p, label); + territoryLabels.put(player.getName(), label); + } - String msg = tag; + String msg = tag; - if (Conf.spoutTerritoryDisplayShowDescription && !factionHere.getDescription().isEmpty()) - msg += " - " + factionHere.getDescription(); + if (Conf.spoutTerritoryDisplayShowDescription && !factionHere.getDescription().isEmpty()) + msg += " - " + factionHere.getDescription(); - label.setText(msg); - alignLabel(label, msg); - label.setDirty(true); - } + label.setText(msg); + alignLabel(label, msg); + label.setDirty(true); + } - // ----------------------- - // Fading territory notice - // ----------------------- - if (notify && Conf.spoutTerritoryNoticeShow && Conf.spoutTerritoryNoticeSize > 0) - { - NoticeLabel label; - if (territoryChangeLabels.containsKey(player.getName())) - label = territoryChangeLabels.get(player.getName()); - else - { - label = new NoticeLabel(Conf.spoutTerritoryNoticeLeaveAfterSeconds); - label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning - label.setScale(Conf.spoutTerritoryNoticeSize); - label.setY(Conf.spoutTerritoryNoticeTop); - sPlayer.getMainScreen().attachWidget(P.p, label); - territoryChangeLabels.put(player.getName(), label); - } + // ----------------------- + // Fading territory notice + // ----------------------- + if (notify && Conf.spoutTerritoryNoticeShow && Conf.spoutTerritoryNoticeSize > 0) { + NoticeLabel label; + if (territoryChangeLabels.containsKey(player.getName())) + label = territoryChangeLabels.get(player.getName()); + else { + label = new NoticeLabel(Conf.spoutTerritoryNoticeLeaveAfterSeconds); + label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning + label.setScale(Conf.spoutTerritoryNoticeSize); + label.setY(Conf.spoutTerritoryNoticeTop); + sPlayer.getMainScreen().attachWidget(P.p, label); + territoryChangeLabels.put(player.getName(), label); + } - String msg = tag; + String msg = tag; - if (Conf.spoutTerritoryNoticeShowDescription && !factionHere.getDescription().isEmpty()) - msg += " - " + factionHere.getDescription(); + if (Conf.spoutTerritoryNoticeShowDescription && !factionHere.getDescription().isEmpty()) + msg += " - " + factionHere.getDescription(); - label.setText(msg); - alignLabel(label, msg, 2); - label.resetNotice(); - label.setDirty(true); - } + label.setText(msg); + alignLabel(label, msg, 2); + label.resetNotice(); + label.setDirty(true); + } - // and owner list, of course - doOwnerList(player, sPlayer, here, factionHere); - } - - private void doOwnerList(FPlayer player, SpoutPlayer sPlayer, FLocation here, Faction factionHere) - { - // ---------- - // Owner list - // ---------- - if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0 && Conf.spoutTerritoryOwnersShow && Conf.ownedAreasEnabled) - { - GenericLabel label; - if (ownerLabels.containsKey(player.getName())) - label = ownerLabels.get(player.getName()); - else - { - label = new GenericLabel(); - label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning - label.setScale(Conf.spoutTerritoryDisplaySize); - label.setY((int)(10 * Conf.spoutTerritoryDisplaySize)); - sPlayer.getMainScreen().attachWidget(P.p, label); - ownerLabels.put(player.getName(), label); - } + // and owner list, of course + doOwnerList(player, sPlayer, here, factionHere); + } - String msg = ""; + private void doOwnerList(FPlayer player, SpoutPlayer sPlayer, FLocation here, Faction factionHere) { + // ---------- + // Owner list + // ---------- + if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0 && Conf.spoutTerritoryOwnersShow && Conf.ownedAreasEnabled) { + GenericLabel label; + if (ownerLabels.containsKey(player.getName())) + label = ownerLabels.get(player.getName()); + else { + label = new GenericLabel(); + label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning + label.setScale(Conf.spoutTerritoryDisplaySize); + label.setY((int) (10 * Conf.spoutTerritoryDisplaySize)); + sPlayer.getMainScreen().attachWidget(P.p, label); + ownerLabels.put(player.getName(), label); + } - if (player.getFaction() == factionHere) - { - msg = factionHere.getOwnerListString(here); + String msg = ""; - if (!msg.isEmpty()) - msg = Conf.ownedLandMessage + msg; - } + if (player.getFaction() == factionHere) { + msg = factionHere.getOwnerListString(here); - label.setText(msg); - alignLabel(label, msg); - label.setDirty(true); - } - } + if (!msg.isEmpty()) + msg = Conf.ownedLandMessage + msg; + } + + label.setText(msg); + alignLabel(label, msg); + label.setDirty(true); + } + } - // this is only necessary because Spout text size scaling is currently bugged and breaks their built-in alignment methods - public void alignLabel(GenericLabel label, String text) - { - alignLabel(label, text, Conf.spoutTerritoryDisplayPosition); - } - public void alignLabel(GenericLabel label, String text, int alignment) - { - int labelWidth = (int)((float)GenericLabel.getStringWidth(text) * Conf.spoutTerritoryDisplaySize); - if (labelWidth > SCREEN_WIDTH) - { - label.setX(0); - return; - } + // this is only necessary because Spout text size scaling is currently bugged and breaks their built-in alignment methods + public void alignLabel(GenericLabel label, String text) { + alignLabel(label, text, Conf.spoutTerritoryDisplayPosition); + } - switch (alignment) - { - case 1: // left aligned - label.setX(0); - break; - case 2: // center aligned - label.setX((SCREEN_WIDTH - labelWidth) / 2); - break; - default: // right aligned - label.setX(SCREEN_WIDTH - labelWidth); - } - } + public void alignLabel(GenericLabel label, String text, int alignment) { + int labelWidth = (int) ((float) GenericLabel.getStringWidth(text) * Conf.spoutTerritoryDisplaySize); + if (labelWidth > SCREEN_WIDTH) { + label.setX(0); + return; + } + + switch (alignment) { + case 1: // left aligned + label.setX(0); + break; + case 2: // center aligned + label.setX((SCREEN_WIDTH - labelWidth) / 2); + break; + default: // right aligned + label.setX(SCREEN_WIDTH - labelWidth); + } + } - private static class NoticeLabel extends GenericLabel - { - private int initial; - private int countdown; // current delay countdown + private static class NoticeLabel extends GenericLabel { + private int initial; + private int countdown; // current delay countdown - public NoticeLabel(float secondsOfLife) - { - initial = (int)(secondsOfLife * 20); - resetNotice(); - } + public NoticeLabel(float secondsOfLife) { + initial = (int) (secondsOfLife * 20); + resetNotice(); + } - public final void resetNotice() - { - countdown = initial; - } + public final void resetNotice() { + countdown = initial; + } - @Override - public void onTick() - { - if (countdown <= 0) - return; + @Override + public void onTick() { + if (countdown <= 0) + return; - this.countdown -= 1; + this.countdown -= 1; - if (this.countdown <= 0) - { - this.setText(""); - this.setDirty(true); - } - } - } + if (this.countdown <= 0) { + this.setText(""); + this.setDirty(true); + } + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/integration/Worldguard.java b/src/main/java/com/massivecraft/factions/integration/Worldguard.java index 3a6c544a..18f6cade 100644 --- a/src/main/java/com/massivecraft/factions/integration/Worldguard.java +++ b/src/main/java/com/massivecraft/factions/integration/Worldguard.java @@ -1,152 +1,133 @@ package com.massivecraft.factions.integration; import com.massivecraft.factions.P; +import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.Vector; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.DefaultFlag; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + import java.util.ArrayList; import java.util.List; import java.util.Map; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; import static com.sk89q.worldguard.bukkit.BukkitUtil.*; -import com.sk89q.worldguard.protection.flags.DefaultFlag; - -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.BlockVector; - -import org.bukkit.World; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.plugin.Plugin; -import org.bukkit.entity.Player; /* * Worldguard Region Checking * Author: Spathizilla */ -public class Worldguard -{ - private static WorldGuardPlugin wg; - private static boolean enabled = false; +public class Worldguard { + private static WorldGuardPlugin wg; + private static boolean enabled = false; - public static void init(Plugin plugin) - { - Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard"); - if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) - { - enabled = false; - wg = null; - P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); - } - else - { - wg = (WorldGuardPlugin) wgplug; - enabled = true; - P.p.log("Successfully hooked to WorldGuard."); - } - } + public static void init(Plugin plugin) { + Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard"); + if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) { + enabled = false; + wg = null; + P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); + } else { + wg = (WorldGuardPlugin) wgplug; + enabled = true; + P.p.log("Successfully hooked to WorldGuard."); + } + } - public static boolean isEnabled() - { - return enabled; - } + public static boolean isEnabled() { + return enabled; + } - // PVP Flag check - // Returns: - // True: PVP is allowed - // False: PVP is disallowed - public static boolean isPVP(Player player) - { - if( ! enabled) - { - // No WG hooks so we'll always bypass this check. - return true; - } + // PVP Flag check + // Returns: + // True: PVP is allowed + // False: PVP is disallowed + public static boolean isPVP(Player player) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return true; + } - Location loc = player.getLocation(); - World world = loc.getWorld(); - Vector pt = toVector(loc); + Location loc = player.getLocation(); + World world = loc.getWorld(); + Vector pt = toVector(loc); - RegionManager regionManager = wg.getRegionManager(world); - ApplicableRegionSet set = regionManager.getApplicableRegions(pt); - return set.allows(DefaultFlag.PVP); - } + RegionManager regionManager = wg.getRegionManager(world); + ApplicableRegionSet set = regionManager.getApplicableRegions(pt); + return set.allows(DefaultFlag.PVP); + } - // Check if player can build at location by worldguards rules. - // Returns: - // True: Player can build in the region. - // False: Player can not build in the region. - public static boolean playerCanBuild(Player player, Location loc) - { - if( ! enabled) - { - // No WG hooks so we'll always bypass this check. - return false; - } - - World world = loc.getWorld(); - Vector pt = toVector(loc); - - if (wg.getRegionManager(world).getApplicableRegions(pt).size() > 0) - return wg.canBuild(player, loc); - return false; - } + // Check if player can build at location by worldguards rules. + // Returns: + // True: Player can build in the region. + // False: Player can not build in the region. + public static boolean playerCanBuild(Player player, Location loc) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return false; + } - // Check for Regions in chunk the chunk - // Returns: - // True: Regions found within chunk - // False: No regions found within chunk - public static boolean checkForRegionsInChunk(Location loc) - { - if( ! enabled) - { - // No WG hooks so we'll always bypass this check. - return false; - } + World world = loc.getWorld(); + Vector pt = toVector(loc); - World world = loc.getWorld(); - Chunk chunk = world.getChunkAt(loc); - int minChunkX = chunk.getX() << 4; - int minChunkZ = chunk.getZ() << 4; - int maxChunkX = minChunkX + 15; - int maxChunkZ = minChunkZ + 15; + if (wg.getRegionManager(world).getApplicableRegions(pt).size() > 0) + return wg.canBuild(player, loc); + return false; + } - int worldHeight = world.getMaxHeight(); // Allow for heights other than default + // Check for Regions in chunk the chunk + // Returns: + // True: Regions found within chunk + // False: No regions found within chunk + public static boolean checkForRegionsInChunk(Location loc) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return false; + } - BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ); - BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ); + World world = loc.getWorld(); + Chunk chunk = world.getChunkAt(loc); + int minChunkX = chunk.getX() << 4; + int minChunkZ = chunk.getZ() << 4; + int maxChunkX = minChunkX + 15; + int maxChunkZ = minChunkZ + 15; - RegionManager regionManager = wg.getRegionManager(world); - ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); - Map allregions = regionManager.getRegions(); - List allregionslist = new ArrayList(allregions.values()); - List overlaps; - boolean foundregions = false; + int worldHeight = world.getMaxHeight(); // Allow for heights other than default - try - { - overlaps = region.getIntersectingRegions(allregionslist); - if(overlaps == null || overlaps.isEmpty()) - { - foundregions = false; - } - else - { - foundregions = true; - } - } - catch (Exception e) - { - e.printStackTrace(); - } + BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ); + BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ); - region = null; - allregionslist = null; - overlaps = null; + RegionManager regionManager = wg.getRegionManager(world); + ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); + Map allregions = regionManager.getRegions(); + List allregionslist = new ArrayList(allregions.values()); + List overlaps; + boolean foundregions = false; - return foundregions; - } + try { + overlaps = region.getIntersectingRegions(allregionslist); + if (overlaps == null || overlaps.isEmpty()) { + foundregions = false; + } else { + foundregions = true; + } + } catch (Exception e) { + e.printStackTrace(); + } + + region = null; + allregionslist = null; + overlaps = null; + + return foundregions; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/integration/capi/CapiFeatures.java b/src/main/java/com/massivecraft/factions/integration/capi/CapiFeatures.java index c1dbc013..e95ced40 100644 --- a/src/main/java/com/massivecraft/factions/integration/capi/CapiFeatures.java +++ b/src/main/java/com/massivecraft/factions/integration/capi/CapiFeatures.java @@ -1,19 +1,15 @@ package com.massivecraft.factions.integration.capi; +import com.massivecraft.factions.P; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; -import com.massivecraft.factions.P; - -public class CapiFeatures -{ - public static void setup() - { - Plugin plug = Bukkit.getServer().getPluginManager().getPlugin("capi"); - if (plug != null && plug.getClass().getName().equals("com.massivecraft.capi.P")) - { - P.p.log("Integration with the CAPI plugin was successful"); - Bukkit.getPluginManager().registerEvents(new PluginCapiListener(P.p), P.p); - } - } +public class CapiFeatures { + public static void setup() { + Plugin plug = Bukkit.getServer().getPluginManager().getPlugin("capi"); + if (plug != null && plug.getClass().getName().equals("com.massivecraft.capi.P")) { + P.p.log("Integration with the CAPI plugin was successful"); + Bukkit.getPluginManager().registerEvents(new PluginCapiListener(P.p), P.p); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/capi/PluginCapiListener.java b/src/main/java/com/massivecraft/factions/integration/capi/PluginCapiListener.java index 4d283ded..548addf3 100644 --- a/src/main/java/com/massivecraft/factions/integration/capi/PluginCapiListener.java +++ b/src/main/java/com/massivecraft/factions/integration/capi/PluginCapiListener.java @@ -1,14 +1,5 @@ package com.massivecraft.factions.integration.capi; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; - import com.massivecraft.capi.Channel; import com.massivecraft.capi.Channels; import com.massivecraft.capi.events.CAPIListChannelsEvent; @@ -20,106 +11,99 @@ import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.Relation; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; -public class PluginCapiListener implements Listener -{ - P p; - - Set myChannelIds = new LinkedHashSet(); - - public PluginCapiListener(P p) - { - this.p = p; - - myChannelIds.add("faction"); - myChannelIds.add("allies"); - } - - private String replacePlayerTags(String format, FPlayer me, FPlayer you) - { - String meFactionTag = me.getChatTag(you); - format = format.replace("{ME_FACTIONTAG}", meFactionTag.length() == 0 ? "" : meFactionTag); - format = format.replace("{ME_FACTIONTAG_PADR}", meFactionTag.length() == 0 ? "" : meFactionTag+" "); - format = format.replace("{ME_FACTIONTAG_PADL}", meFactionTag.length() == 0 ? "" : " "+meFactionTag); - format = format.replace("{ME_FACTIONTAG_PADB}", meFactionTag.length() == 0 ? "" : " "+meFactionTag+" "); +import java.util.LinkedHashSet; +import java.util.Set; - String youFactionTag = you.getChatTag(me); - format = format.replace("{YOU_FACTIONTAG}", youFactionTag.length() == 0 ? "" : youFactionTag); - format = format.replace("{YOU_FACTIONTAG_PADR}", youFactionTag.length() == 0 ? "" : youFactionTag+" "); - format = format.replace("{YOU_FACTIONTAG_PADL}", youFactionTag.length() == 0 ? "" : " "+youFactionTag); - format = format.replace("{YOU_FACTIONTAG_PADB}", youFactionTag.length() == 0 ? "" : " "+youFactionTag+" "); - - return format; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onListChannelsEvent(CAPIListChannelsEvent event) - { - for (Channel c : Channels.i.getAll()) - { - if (myChannelIds.contains(c.getId())) - { - event.getChannels().add(c); - } - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onMessageToChannel(CAPIMessageToChannelEvent event) - { - if (event.isCancelled()) return; - if ( ! myChannelIds.contains(event.getChannel().getId())) return; - - Player me = event.getMe(); - FPlayer fme = FPlayers.i.get(me); - Faction myFaction = fme.getFaction(); - - if (event.getChannel().getId().equals("faction") && myFaction.isNormal()) - { - event.getThem().addAll(myFaction.getOnlinePlayers()); +public class PluginCapiListener implements Listener { + P p; - // Send to any players who are spying chat... could probably be implemented better than this - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - if(fplayer.isSpyingChat() && fplayer.getFaction() != myFaction) - fplayer.sendMessage("[FCspy] "+myFaction.getTag()+": "+event.getMessage()); - } - } - else if (event.getChannel().getId().equals("allies")) - { - for (Player somePlayer : Bukkit.getServer().getOnlinePlayers()) - { - FPlayer someFPlayer = FPlayers.i.get(somePlayer); - if (someFPlayer.getRelationTo(fme).isAtLeast(Relation.ALLY)) - event.getThem().add(somePlayer); - // Send to any players who are spying chat - else if(someFPlayer.isSpyingChat()) - someFPlayer.sendMessage("[ACspy]: " + event.getMessage()); - } - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onMessageToPlayer(CAPIMessageToPlayerEvent event) - { - if (event.isCancelled()) return; - event.setFormat(this.replacePlayerTags(event.getFormat(), FPlayers.i.get(event.getMe()), FPlayers.i.get(event.getYou()))); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onSelectChannel(CAPISelectChannelEvent event) - { - if (event.isCancelled()) return; - String channelId = event.getChannel().getId(); - if ( ! myChannelIds.contains(channelId)) return; - - Player me = event.getMe(); - FPlayer fme = FPlayers.i.get(me); - - if ( ! fme.hasFaction()) - { - event.setFailMessage(p.txt.parse("You must be member in a faction to use this channel.")); - event.setCancelled(true); - } - } + Set myChannelIds = new LinkedHashSet(); + + public PluginCapiListener(P p) { + this.p = p; + + myChannelIds.add("faction"); + myChannelIds.add("allies"); + } + + private String replacePlayerTags(String format, FPlayer me, FPlayer you) { + String meFactionTag = me.getChatTag(you); + format = format.replace("{ME_FACTIONTAG}", meFactionTag.length() == 0 ? "" : meFactionTag); + format = format.replace("{ME_FACTIONTAG_PADR}", meFactionTag.length() == 0 ? "" : meFactionTag + " "); + format = format.replace("{ME_FACTIONTAG_PADL}", meFactionTag.length() == 0 ? "" : " " + meFactionTag); + format = format.replace("{ME_FACTIONTAG_PADB}", meFactionTag.length() == 0 ? "" : " " + meFactionTag + " "); + + String youFactionTag = you.getChatTag(me); + format = format.replace("{YOU_FACTIONTAG}", youFactionTag.length() == 0 ? "" : youFactionTag); + format = format.replace("{YOU_FACTIONTAG_PADR}", youFactionTag.length() == 0 ? "" : youFactionTag + " "); + format = format.replace("{YOU_FACTIONTAG_PADL}", youFactionTag.length() == 0 ? "" : " " + youFactionTag); + format = format.replace("{YOU_FACTIONTAG_PADB}", youFactionTag.length() == 0 ? "" : " " + youFactionTag + " "); + + return format; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onListChannelsEvent(CAPIListChannelsEvent event) { + for (Channel c : Channels.i.getAll()) { + if (myChannelIds.contains(c.getId())) { + event.getChannels().add(c); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onMessageToChannel(CAPIMessageToChannelEvent event) { + if (event.isCancelled()) return; + if (!myChannelIds.contains(event.getChannel().getId())) return; + + Player me = event.getMe(); + FPlayer fme = FPlayers.i.get(me); + Faction myFaction = fme.getFaction(); + + if (event.getChannel().getId().equals("faction") && myFaction.isNormal()) { + event.getThem().addAll(myFaction.getOnlinePlayers()); + + // Send to any players who are spying chat... could probably be implemented better than this + for (FPlayer fplayer : FPlayers.i.getOnline()) { + if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction) + fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + event.getMessage()); + } + } else if (event.getChannel().getId().equals("allies")) { + for (Player somePlayer : Bukkit.getServer().getOnlinePlayers()) { + FPlayer someFPlayer = FPlayers.i.get(somePlayer); + if (someFPlayer.getRelationTo(fme).isAtLeast(Relation.ALLY)) + event.getThem().add(somePlayer); + // Send to any players who are spying chat + else if (someFPlayer.isSpyingChat()) + someFPlayer.sendMessage("[ACspy]: " + event.getMessage()); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onMessageToPlayer(CAPIMessageToPlayerEvent event) { + if (event.isCancelled()) return; + event.setFormat(this.replacePlayerTags(event.getFormat(), FPlayers.i.get(event.getMe()), FPlayers.i.get(event.getYou()))); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onSelectChannel(CAPISelectChannelEvent event) { + if (event.isCancelled()) return; + String channelId = event.getChannel().getId(); + if (!myChannelIds.contains(channelId)) return; + + Player me = event.getMe(); + FPlayer fme = FPlayers.i.get(me); + + if (!fme.hasFaction()) { + event.setFailMessage(p.txt.parse("You must be member in a faction to use this channel.")); + event.setCancelled(true); + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java index da97a611..62c70c9a 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -1,5 +1,9 @@ package com.massivecraft.factions.listeners; +import com.massivecraft.factions.*; +import com.massivecraft.factions.integration.Worldguard; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.struct.Relation; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -7,253 +11,208 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; - -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; -import com.massivecraft.factions.integration.Worldguard; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.struct.Relation; +import org.bukkit.event.block.*; -public class FactionsBlockListener implements Listener -{ - public P p; - public FactionsBlockListener(P p) - { - this.p = p; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onBlockPlace(BlockPlaceEvent event) - { - if (event.isCancelled()) return; - if ( ! event.canBuild()) return; - - // special case for flint&steel, which should only be prevented by DenyUsage list - if (event.getBlockPlaced().getType() == Material.FIRE) - { - return; - } +public class FactionsBlockListener implements Listener { + public P p; - if ( ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) - event.setCancelled(true); - } + public FactionsBlockListener(P p) { + this.p = p; + } - @EventHandler(priority = EventPriority.NORMAL) - public void onBlockBreak(BlockBreakEvent event) - { - if (event.isCancelled()) return; + @EventHandler(priority = EventPriority.NORMAL) + public void onBlockPlace(BlockPlaceEvent event) { + if (event.isCancelled()) return; + if (!event.canBuild()) return; - if ( ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) - { - event.setCancelled(true); - } - } + // special case for flint&steel, which should only be prevented by DenyUsage list + if (event.getBlockPlaced().getType() == Material.FIRE) { + return; + } - @EventHandler(priority = EventPriority.NORMAL) - public void onBlockDamage(BlockDamageEvent event) - { - if (event.isCancelled()) return; + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) + event.setCancelled(true); + } - if (event.getInstaBreak() && ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) - { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.NORMAL) + public void onBlockBreak(BlockBreakEvent event) { + if (event.isCancelled()) return; - @EventHandler(priority = EventPriority.NORMAL) - public void onBlockPistonExtend(BlockPistonExtendEvent event) - { - if (event.isCancelled()) return; - if ( ! Conf.pistonProtectionThroughDenyBuild) return; + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { + event.setCancelled(true); + } + } - Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock())); + @EventHandler(priority = EventPriority.NORMAL) + public void onBlockDamage(BlockDamageEvent event) { + if (event.isCancelled()) return; - // 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 (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { + 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); - return; - } + @EventHandler(priority = EventPriority.NORMAL) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + if (event.isCancelled()) return; + if (!Conf.pistonProtectionThroughDenyBuild) return; + + Faction pistonFaction = Board.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); + + // 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); + return; + } /* - * note that I originally was testing the territory of each affected block, but since I found that pistons can only push + * note that I originally was testing the territory of each affected block, but since I found that pistons can only push * up to 12 blocks and the width of any territory is 16 blocks, it should be safe (and much more lightweight) to test * only the final target block as done above */ - } + } - @EventHandler(priority = EventPriority.NORMAL) - public void onBlockPistonRetract(BlockPistonRetractEvent event) - { - // if not a sticky piston, retraction should be fine - if (event.isCancelled() || !event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) - { - return; - } + @EventHandler(priority = EventPriority.NORMAL) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + // if not a sticky piston, retraction should be fine + if (event.isCancelled() || !event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) { + return; + } - Location targetLoc = event.getRetractLocation(); + Location targetLoc = event.getRetractLocation(); - // if potentially retracted block is just air/water/lava, no worries - if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) - { - return; - } + // if potentially retracted block is just air/water/lava, no worries + if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) { + return; + } - Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock())); + Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock())); - if (!canPistonMoveBlock(pistonFaction, targetLoc)) - { - event.setCancelled(true); - return; - } - } + if (!canPistonMoveBlock(pistonFaction, targetLoc)) { + event.setCancelled(true); + return; + } + } - private boolean canPistonMoveBlock(Faction pistonFaction, Location target) - { + private boolean canPistonMoveBlock(Faction pistonFaction, Location target) { - Faction otherFaction = Board.getFactionAt(new FLocation(target)); + Faction otherFaction = Board.getFactionAt(new FLocation(target)); - if (pistonFaction == otherFaction) - return true; + if (pistonFaction == otherFaction) + return true; - if (otherFaction.isNone()) - { - if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName())) - return true; + if (otherFaction.isNone()) { + if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName())) + return true; - return false; - } - else if (otherFaction.isSafeZone()) - { - if ( ! Conf.safeZoneDenyBuild) - return true; + return false; + } else if (otherFaction.isSafeZone()) { + if (!Conf.safeZoneDenyBuild) + return true; - return false; - } - else if (otherFaction.isWarZone()) - { - if ( ! Conf.warZoneDenyBuild) - return true; + return false; + } else if (otherFaction.isWarZone()) { + if (!Conf.warZoneDenyBuild) + return true; - return false; - } + return false; + } - Relation rel = pistonFaction.getRelationTo(otherFaction); + Relation rel = pistonFaction.getRelationTo(otherFaction); - if (rel.confDenyBuild(otherFaction.hasPlayersOnline())) - return false; + if (rel.confDenyBuild(otherFaction.hasPlayersOnline())) + return false; - return true; - } + return true; + } - public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) - { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) return true; + public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { + String name = player.getName(); + if (Conf.playersWhoBypassAllProtection.contains(name)) return true; - FPlayer me = FPlayers.i.get(name); - if (me.isAdminBypassing()) return true; + FPlayer me = FPlayers.i.get(name); + if (me.isAdminBypassing()) return true; - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getFactionAt(loc); + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getFactionAt(loc); - if (otherFaction.isNone()) - { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; + if (otherFaction.isNone()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; - if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) - return true; // This is not faction territory. Use whatever you like here. + if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) + return true; // This is not faction territory. Use whatever you like here. - if (!justCheck) - me.msg("You can't "+action+" in the wilderness."); + if (!justCheck) + me.msg("You can't " + action + " in the wilderness."); - return false; - } - else if (otherFaction.isSafeZone()) - { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; + return false; + } else if (otherFaction.isSafeZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; - if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) - return true; + if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) + return true; - if (!justCheck) - me.msg("You can't "+action+" in a safe zone."); + if (!justCheck) + me.msg("You can't " + action + " in a safe zone."); - return false; - } - else if (otherFaction.isWarZone()) - { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; + return false; + } else if (otherFaction.isWarZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; - if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) - return true; + if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) + return true; - if (!justCheck) - me.msg("You can't "+action+" in a war zone."); + if (!justCheck) + me.msg("You can't " + action + " in a war zone."); - return false; - } + return false; + } - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - boolean online = otherFaction.hasPlayersOnline(); - boolean pain = !justCheck && rel.confPainBuild(online); - boolean deny = rel.confDenyBuild(online); + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + boolean online = otherFaction.hasPlayersOnline(); + boolean pain = !justCheck && rel.confPainBuild(online); + boolean deny = rel.confDenyBuild(online); - // hurt the player for building/destroying in other territory? - if (pain) - { - player.damage(Conf.actionDeniedPainAmount); + // hurt the player for building/destroying in other territory? + if (pain) { + player.damage(Conf.actionDeniedPainAmount); - if (!deny) - me.msg("It is painful to try to "+action+" in the territory of "+otherFaction.getTag(myFaction)); - } + if (!deny) + me.msg("It is painful to try to " + action + " in the territory of " + otherFaction.getTag(myFaction)); + } - // cancel building/destroying in other territory? - if (deny) - { - if (!justCheck) - me.msg("You can't "+action+" in the territory of "+otherFaction.getTag(myFaction)); + // cancel building/destroying in other territory? + if (deny) { + if (!justCheck) + me.msg("You can't " + action + " in the territory of " + otherFaction.getTag(myFaction)); - return false; - } + return false; + } - // Also cancel and/or cause pain if player doesn't have ownership rights for this claim - if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) - { - if (!pain && Conf.ownedAreaPainBuild && !justCheck) - { - player.damage(Conf.actionDeniedPainAmount); + // Also cancel and/or cause pain if player doesn't have ownership rights for this claim + if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!pain && Conf.ownedAreaPainBuild && !justCheck) { + player.damage(Conf.actionDeniedPainAmount); - if (!Conf.ownedAreaDenyBuild) - me.msg("It is painful to try to "+action+" in this territory, it is owned by: "+otherFaction.getOwnerListString(loc)); - } - if (Conf.ownedAreaDenyBuild) - { - if (!justCheck) - me.msg("You can't "+action+" in this territory, it is owned by: "+otherFaction.getOwnerListString(loc)); + if (!Conf.ownedAreaDenyBuild) + me.msg("It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); + } + if (Conf.ownedAreaDenyBuild) { + if (!justCheck) + me.msg("You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); - return false; - } - } + return false; + } + } - return true; - } + return true; + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java index 2db79759..bb49b1b9 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java @@ -1,8 +1,8 @@ package com.massivecraft.factions.listeners; -import java.util.logging.Level; -import java.util.UnknownFormatConversionException; - +import com.massivecraft.factions.*; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.struct.Relation; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -11,175 +11,146 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChatEvent; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; -import com.massivecraft.factions.struct.ChatMode; -import com.massivecraft.factions.struct.Relation; +import java.util.UnknownFormatConversionException; +import java.util.logging.Level; -public class FactionsChatListener implements Listener -{ - public P p; - public FactionsChatListener(P p) - { - this.p = p; - } - - // this is for handling slashless command usage and faction/alliance chat, set at lowest priority so Factions gets to them first - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerEarlyChat(PlayerChatEvent event) - { - if (event.isCancelled()) return; - - Player talkingPlayer = event.getPlayer(); - String msg = event.getMessage(); - FPlayer me = FPlayers.i.get(talkingPlayer); - ChatMode chat = me.getChatMode(); +public class FactionsChatListener implements Listener { + public P p; - // slashless factions commands need to be handled here if the user isn't in public chat mode - if (chat != ChatMode.PUBLIC && p.handleCommand(talkingPlayer, msg, false, true)) - { - if (Conf.logPlayerCommands) - Bukkit.getLogger().log(Level.INFO, "[PLAYER_COMMAND] "+talkingPlayer.getName()+": "+msg); - event.setCancelled(true); - return; - } + public FactionsChatListener(P p) { + this.p = p; + } - // Is it a faction chat message? - if (chat == ChatMode.FACTION) - { - Faction myFaction = me.getFaction(); - - String message = String.format(Conf.factionChatFormat, me.describeTo(myFaction), msg); - myFaction.sendMessage(message); - - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("FactionChat "+myFaction.getTag()+": "+message)); + // this is for handling slashless command usage and faction/alliance chat, set at lowest priority so Factions gets to them first + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerEarlyChat(PlayerChatEvent event) { + if (event.isCancelled()) return; - //Send to any players who are spying chat - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - if(fplayer.isSpyingChat() && fplayer.getFaction() != myFaction) - fplayer.sendMessage("[FCspy] "+myFaction.getTag()+": "+message); - } + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + FPlayer me = FPlayers.i.get(talkingPlayer); + ChatMode chat = me.getChatMode(); - event.setCancelled(true); - return; - } - else if (chat == ChatMode.ALLIANCE) - { - Faction myFaction = me.getFaction(); - - String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - - //Send message to our own faction - myFaction.sendMessage(message); + // slashless factions commands need to be handled here if the user isn't in public chat mode + if (chat != ChatMode.PUBLIC && p.handleCommand(talkingPlayer, msg, false, true)) { + if (Conf.logPlayerCommands) + Bukkit.getLogger().log(Level.INFO, "[PLAYER_COMMAND] " + talkingPlayer.getName() + ": " + msg); + event.setCancelled(true); + return; + } - //Send to all our allies - for (FPlayer fplayer : FPlayers.i.getOnline()) - { - if(myFaction.getRelationTo(fplayer) == Relation.ALLY) - fplayer.sendMessage(message); + // Is it a faction chat message? + if (chat == ChatMode.FACTION) { + Faction myFaction = me.getFaction(); - //Send to any players who are spying chat - else if(fplayer.isSpyingChat()) - fplayer.sendMessage("[ACspy]: " + message); - } - - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: "+message)); - - event.setCancelled(true); - return; - } - } + String message = String.format(Conf.factionChatFormat, me.describeTo(myFaction), msg); + myFaction.sendMessage(message); - // this is for handling insertion of the player's faction tag, set at highest priority to give other plugins a chance to modify chat first - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerChat(PlayerChatEvent event) - { - if (event.isCancelled()) return; + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("FactionChat " + myFaction.getTag() + ": " + message)); - // Are we to insert the Faction tag into the format? - // If we are not to insert it - we are done. - if ( ! Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin) return; + //Send to any players who are spying chat + for (FPlayer fplayer : FPlayers.i.getOnline()) { + if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction) + fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message); + } - Player talkingPlayer = event.getPlayer(); - String msg = event.getMessage(); - String eventFormat = event.getFormat(); - FPlayer me = FPlayers.i.get(talkingPlayer); - int InsertIndex = 0; - - if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) - { - // we're using the "replace" method of inserting the faction tags - // if they stuck "[FACTION_TITLE]" in there, go ahead and do it too - if (eventFormat.contains("[FACTION_TITLE]")) - { - eventFormat = eventFormat.replace("[FACTION_TITLE]", me.getTitle()); - } - InsertIndex = eventFormat.indexOf(Conf.chatTagReplaceString); - eventFormat = eventFormat.replace(Conf.chatTagReplaceString, ""); - Conf.chatTagPadAfter = false; - Conf.chatTagPadBefore = false; - } - else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString)) - { - // we're using the "insert after string" method - InsertIndex = eventFormat.indexOf(Conf.chatTagInsertAfterString) + Conf.chatTagInsertAfterString.length(); - } - else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) - { - // we're using the "insert before string" method - InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString); - } - else - { - // we'll fall back to using the index place method - InsertIndex = Conf.chatTagInsertIndex; - if (InsertIndex > eventFormat.length()) - return; - } - - String formatStart = eventFormat.substring(0, InsertIndex) + ((Conf.chatTagPadBefore && !me.getChatTag().isEmpty()) ? " " : ""); - String formatEnd = ((Conf.chatTagPadAfter && !me.getChatTag().isEmpty()) ? " " : "") + eventFormat.substring(InsertIndex); - - String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd; - - // Relation Colored? - if (Conf.chatTagRelationColored) - { - // We must choke the standard message and send out individual messages to all players - // Why? Because the relations will differ. - event.setCancelled(true); - - for (Player listeningPlayer : event.getRecipients()) - { - FPlayer you = FPlayers.i.get(listeningPlayer); - String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; - try - { - listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); - } - catch (UnknownFormatConversionException ex) - { - Conf.chatTagInsertIndex = 0; - P.p.log(Level.SEVERE, "Critical error in chat message formatting!"); - P.p.log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); - P.p.log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); - return; - } - } - - // Write to the log... We will write the non colored message. - String nonColoredMsg = ChatColor.stripColor(String.format(nonColoredMsgFormat, talkingPlayer.getDisplayName(), msg)); - Bukkit.getLogger().log(Level.INFO, nonColoredMsg); - } - else - { - // No relation color. - event.setFormat(nonColoredMsgFormat); - } - } + event.setCancelled(true); + return; + } else if (chat == ChatMode.ALLIANCE) { + Faction myFaction = me.getFaction(); + + String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + + //Send message to our own faction + myFaction.sendMessage(message); + + //Send to all our allies + for (FPlayer fplayer : FPlayers.i.getOnline()) { + if (myFaction.getRelationTo(fplayer) == Relation.ALLY) + fplayer.sendMessage(message); + + //Send to any players who are spying chat + else if (fplayer.isSpyingChat()) + fplayer.sendMessage("[ACspy]: " + message); + } + + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); + + event.setCancelled(true); + return; + } + } + + // this is for handling insertion of the player's faction tag, set at highest priority to give other plugins a chance to modify chat first + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerChat(PlayerChatEvent event) { + if (event.isCancelled()) return; + + // Are we to insert the Faction tag into the format? + // If we are not to insert it - we are done. + if (!Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin) return; + + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + String eventFormat = event.getFormat(); + FPlayer me = FPlayers.i.get(talkingPlayer); + int InsertIndex = 0; + + if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) { + // we're using the "replace" method of inserting the faction tags + // if they stuck "[FACTION_TITLE]" in there, go ahead and do it too + if (eventFormat.contains("[FACTION_TITLE]")) { + eventFormat = eventFormat.replace("[FACTION_TITLE]", me.getTitle()); + } + InsertIndex = eventFormat.indexOf(Conf.chatTagReplaceString); + eventFormat = eventFormat.replace(Conf.chatTagReplaceString, ""); + Conf.chatTagPadAfter = false; + Conf.chatTagPadBefore = false; + } else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString)) { + // we're using the "insert after string" method + InsertIndex = eventFormat.indexOf(Conf.chatTagInsertAfterString) + Conf.chatTagInsertAfterString.length(); + } else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) { + // we're using the "insert before string" method + InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString); + } else { + // we'll fall back to using the index place method + InsertIndex = Conf.chatTagInsertIndex; + if (InsertIndex > eventFormat.length()) + return; + } + + String formatStart = eventFormat.substring(0, InsertIndex) + ((Conf.chatTagPadBefore && !me.getChatTag().isEmpty()) ? " " : ""); + String formatEnd = ((Conf.chatTagPadAfter && !me.getChatTag().isEmpty()) ? " " : "") + eventFormat.substring(InsertIndex); + + String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd; + + // Relation Colored? + if (Conf.chatTagRelationColored) { + // We must choke the standard message and send out individual messages to all players + // Why? Because the relations will differ. + event.setCancelled(true); + + for (Player listeningPlayer : event.getRecipients()) { + FPlayer you = FPlayers.i.get(listeningPlayer); + String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; + try { + listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); + } catch (UnknownFormatConversionException ex) { + Conf.chatTagInsertIndex = 0; + P.p.log(Level.SEVERE, "Critical error in chat message formatting!"); + P.p.log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); + P.p.log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); + return; + } + } + + // Write to the log... We will write the non colored message. + String nonColoredMsg = ChatColor.stripColor(String.format(nonColoredMsgFormat, talkingPlayer.getDisplayName(), msg)); + Bukkit.getLogger().log(Level.INFO, nonColoredMsg); + } else { + // No relation color. + event.setFormat(nonColoredMsgFormat); + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java index 49fd6c38..ad24310c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -1,39 +1,18 @@ package com.massivecraft.factions.listeners; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.text.MessageFormat; -import java.util.Set; - +import com.massivecraft.factions.*; +import com.massivecraft.factions.event.PowerLossEvent; +import com.massivecraft.factions.struct.Relation; +import com.massivecraft.factions.util.MiscUtil; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Enderman; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.*; import org.bukkit.entity.minecart.ExplosiveMinecart; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Wither; -import org.bukkit.entity.WitherSkull; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.PotionSplashEvent; +import org.bukkit.event.entity.*; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingBreakEvent; import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause; @@ -41,626 +20,528 @@ import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.P; -import com.massivecraft.factions.event.PowerLossEvent; -import com.massivecraft.factions.struct.Relation; -import com.massivecraft.factions.util.MiscUtil; +import java.text.MessageFormat; +import java.util.*; -public class FactionsEntityListener implements Listener -{ - public P p; - public FactionsEntityListener(P p) - { - this.p = p; - } +public class FactionsEntityListener implements Listener { + public P p; - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityDeath(EntityDeathEvent event) - { - Entity entity = event.getEntity(); - if ( ! (entity instanceof Player)) - { - return; - } - - Player player = (Player) entity; - FPlayer fplayer = FPlayers.i.get(player); - Faction faction = Board.getFactionAt(new FLocation(player.getLocation())); + public FactionsEntityListener(P p) { + this.p = p; + } - PowerLossEvent powerLossEvent = new PowerLossEvent(faction,fplayer); - // Check for no power loss conditions - if (faction.isWarZone()) - { - // war zones always override worldsNoPowerLoss either way, thus this layout - if (! Conf.warZonePowerLoss) - { - powerLossEvent.setMessage("You didn't lose any power since you were in a war zone."); - powerLossEvent.setCancelled(true); - } - if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) - { - powerLossEvent.setMessage("The world you are in has power loss normally disabled, but you still lost power since you were in a war zone.\nYour power is now %d / %d"); - } - } - else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) - { - powerLossEvent.setMessage("You didn't lose any power since you were in the wilderness."); - powerLossEvent.setCancelled(true); - } - else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) - { - powerLossEvent.setMessage("You didn't lose any power due to the world you died in."); - powerLossEvent.setCancelled(true); - } - else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) - { - powerLossEvent.setMessage("You didn't lose any power since you are in a peaceful faction."); - powerLossEvent.setCancelled(true); - } - else { - powerLossEvent.setMessage("Your power is now %d / %d"); - } + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityDeath(EntityDeathEvent event) { + Entity entity = event.getEntity(); + if (!(entity instanceof Player)) { + return; + } - // call Event - Bukkit.getPluginManager().callEvent(powerLossEvent); + Player player = (Player) entity; + FPlayer fplayer = FPlayers.i.get(player); + Faction faction = Board.getFactionAt(new FLocation(player.getLocation())); - // Call player onDeath if the event is not cancelled - if(!powerLossEvent.isCancelled()) - { - fplayer.onDeath(); - } - // Send the message from the powerLossEvent - final String msg = powerLossEvent.getMessage(); - if (msg != null && !msg.isEmpty()) - { - fplayer.msg(msg,fplayer.getPowerRounded(),fplayer.getPowerMaxRounded()); - } - } - - /** - * Who can I hurt? - * I can never hurt members or allies. - * I can always hurt enemies. - * I can hurt neutrals as long as they are outside their own territory. - */ - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityDamage(EntityDamageEvent event) - { - if (event.isCancelled()) return; - - if (event instanceof EntityDamageByEntityEvent) - { - EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent)event; - if ( ! this.canDamagerHurtDamagee(sub, true)) - { - event.setCancelled(true); - } - } - else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) - { - // Players can not take any damage in a Safe Zone - event.setCancelled(true); - } - } + PowerLossEvent powerLossEvent = new PowerLossEvent(faction, fplayer); + // Check for no power loss conditions + if (faction.isWarZone()) { + // war zones always override worldsNoPowerLoss either way, thus this layout + if (!Conf.warZonePowerLoss) { + powerLossEvent.setMessage("You didn't lose any power since you were in a war zone."); + powerLossEvent.setCancelled(true); + } + if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + powerLossEvent.setMessage("The world you are in has power loss normally disabled, but you still lost power since you were in a war zone.\nYour power is now %d / %d"); + } + } else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) { + powerLossEvent.setMessage("You didn't lose any power since you were in the wilderness."); + powerLossEvent.setCancelled(true); + } else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + powerLossEvent.setMessage("You didn't lose any power due to the world you died in."); + powerLossEvent.setCancelled(true); + } else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { + powerLossEvent.setMessage("You didn't lose any power since you are in a peaceful faction."); + powerLossEvent.setCancelled(true); + } else { + powerLossEvent.setMessage("Your power is now %d / %d"); + } - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityExplode(EntityExplodeEvent event) - { - if (event.isCancelled()) return; - - Location loc = event.getLocation(); - Entity boomer = event.getEntity(); - Faction faction = Board.getFactionAt(new FLocation(loc)); + // call Event + Bukkit.getPluginManager().callEvent(powerLossEvent); - if (faction.noExplosionsInTerritory()) - { - // faction is peaceful and has explosions set to disabled - event.setCancelled(true); - return; - } + // Call player onDeath if the event is not cancelled + if (!powerLossEvent.isCancelled()) { + fplayer.onDeath(); + } + // Send the message from the powerLossEvent + final String msg = powerLossEvent.getMessage(); + if (msg != null && !msg.isEmpty()) { + fplayer.msg(msg, fplayer.getPowerRounded(), fplayer.getPowerMaxRounded()); + } + } - boolean online = faction.hasPlayersOnline(); + /** + * Who can I hurt? I can never hurt members or allies. I can always hurt enemies. I can hurt neutrals as long as + * they are outside their own territory. + */ + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityDamage(EntityDamageEvent event) { + if (event.isCancelled()) return; - if - ( - boomer instanceof Creeper - && - ( - (faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockCreepers) - || - faction.isSafeZone() - ) - ) - { - // creeper which needs prevention - event.setCancelled(true); - } - else if - ( - // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever - (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) - && - ( - (faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockFireballs) - || - faction.isSafeZone() - ) - ) - { - // ghast fireball which needs prevention - event.setCancelled(true); - } - else if - ( - (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) - && - ( - (faction.isNone() && Conf.wildernessBlockTNT && ! Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && ( online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline )) - || - (faction.isWarZone() && Conf.warZoneBlockTNT) - || - (faction.isSafeZone() && Conf.safeZoneBlockTNT) - ) - ) - { - // TNT which needs prevention - event.setCancelled(true); - } - else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) - { - // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... - // this change below provides workaround for waterwalling providing perfect protection, - // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots - Block center = loc.getBlock(); - if (center.isLiquid()) - { - // a single surrounding block in all 6 directions is broken if the material is weak enough - List targets = new ArrayList(); - targets.add(center.getRelative(0, 0, 1)); - targets.add(center.getRelative(0, 0, -1)); - targets.add(center.getRelative(0, 1, 0)); - targets.add(center.getRelative(0, -1, 0)); - targets.add(center.getRelative(1, 0, 0)); - targets.add(center.getRelative(-1, 0, 0)); - for (Block target : targets) - { - int id = target.getTypeId(); - // ignore air, bedrock, water, lava, obsidian, enchanting table, etc.... too bad we can't get a blast resistance value through Bukkit yet - if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 90 && id != 116 && id != 119 && id != 120 && id != 130) - target.breakNaturally(); - } - } - } - } + if (event instanceof EntityDamageByEntityEvent) { + EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event; + if (!this.canDamagerHurtDamagee(sub, true)) { + event.setCancelled(true); + } + } else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { + // Players can not take any damage in a Safe Zone + event.setCancelled(true); + } + } - // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityCombustByEntity(EntityCombustByEntityEvent event) - { - if (event.isCancelled()) return; - - EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0); - if ( ! this.canDamagerHurtDamagee(sub, false)) - event.setCancelled(true); - sub = null; - } + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityExplode(EntityExplodeEvent event) { + if (event.isCancelled()) return; - private static final Set badPotionEffects = new LinkedHashSet(Arrays.asList( - PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, - PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, - PotionEffectType.WITHER - )); + Location loc = event.getLocation(); + Entity boomer = event.getEntity(); + Faction faction = Board.getFactionAt(new FLocation(loc)); - @EventHandler(priority = EventPriority.NORMAL) - public void onPotionSplashEvent(PotionSplashEvent event) - { - if (event.isCancelled()) return; + if (faction.noExplosionsInTerritory()) { + // faction is peaceful and has explosions set to disabled + event.setCancelled(true); + return; + } - // see if the potion has a harmful effect - boolean badjuju = false; - for (PotionEffect effect : event.getPotion().getEffects()) - { - if (badPotionEffects.contains(effect.getType())) - { - badjuju = true; - break; - } - } - if ( ! badjuju) return; + boolean online = faction.hasPlayersOnline(); - Entity thrower = event.getPotion().getShooter(); + if + ( + boomer instanceof Creeper + && + ( + (faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) + || + (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) + || + (faction.isWarZone() && Conf.warZoneBlockCreepers) + || + faction.isSafeZone() + ) + ) { + // creeper which needs prevention + event.setCancelled(true); + } else if + ( + // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) + && + ( + (faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) + || + (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) + || + (faction.isWarZone() && Conf.warZoneBlockFireballs) + || + faction.isSafeZone() + ) + ) { + // ghast fireball which needs prevention + event.setCancelled(true); + } else if + ( + (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) + && + ( + (faction.isNone() && Conf.wildernessBlockTNT && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) + || + (faction.isNormal() && (online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline)) + || + (faction.isWarZone() && Conf.warZoneBlockTNT) + || + (faction.isSafeZone() && Conf.safeZoneBlockTNT) + ) + ) { + // TNT which needs prevention + event.setCancelled(true); + } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { + // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... + // this change below provides workaround for waterwalling providing perfect protection, + // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots + Block center = loc.getBlock(); + if (center.isLiquid()) { + // a single surrounding block in all 6 directions is broken if the material is weak enough + List targets = new ArrayList(); + targets.add(center.getRelative(0, 0, 1)); + targets.add(center.getRelative(0, 0, -1)); + targets.add(center.getRelative(0, 1, 0)); + targets.add(center.getRelative(0, -1, 0)); + targets.add(center.getRelative(1, 0, 0)); + targets.add(center.getRelative(-1, 0, 0)); + for (Block target : targets) { + int id = target.getTypeId(); + // ignore air, bedrock, water, lava, obsidian, enchanting table, etc.... too bad we can't get a blast resistance value through Bukkit yet + if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 90 && id != 116 && id != 119 && id != 120 && id != 130) + target.breakNaturally(); + } + } + } + } - // scan through affected entities to make sure they're all valid targets - Iterator iter = event.getAffectedEntities().iterator(); - while (iter.hasNext()) - { - LivingEntity target = iter.next(); - EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0); - if ( ! this.canDamagerHurtDamagee(sub, true)) - event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (so no iter.remove()), but this works - sub = null; - } - } + // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { + if (event.isCancelled()) return; - public boolean isPlayerInSafeZone(Entity damagee) - { - if ( ! (damagee instanceof Player)) - { - return false; - } - if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone()) - { - return true; - } - return false; - } + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0); + if (!this.canDamagerHurtDamagee(sub, false)) + event.setCancelled(true); + sub = null; + } - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) - { - return canDamagerHurtDamagee(sub, true); - } + private static final Set badPotionEffects = new LinkedHashSet(Arrays.asList( + PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, + PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, + PotionEffectType.WITHER + )); - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) - { - Entity damager = sub.getDamager(); - Entity damagee = sub.getEntity(); - int damage = sub.getDamage(); - - if ( ! (damagee instanceof Player)) - return true; + @EventHandler(priority = EventPriority.NORMAL) + public void onPotionSplashEvent(PotionSplashEvent event) { + if (event.isCancelled()) return; - FPlayer defender = FPlayers.i.get((Player)damagee); - - if (defender == null || defender.getPlayer() == null) - return true; - - Location defenderLoc = defender.getPlayer().getLocation(); - Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc)); + // see if the potion has a harmful effect + boolean badjuju = false; + for (PotionEffect effect : event.getPotion().getEffects()) { + if (badPotionEffects.contains(effect.getType())) { + badjuju = true; + break; + } + } + if (!badjuju) return; - // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source - if (damager instanceof Projectile) - damager = ((Projectile)damager).getShooter(); + Entity thrower = event.getPotion().getShooter(); - if (damager == damagee) // ender pearl usage and other self-inflicted damage - return true; + // scan through affected entities to make sure they're all valid targets + Iterator iter = event.getAffectedEntities().iterator(); + while (iter.hasNext()) { + LivingEntity target = iter.next(); + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0); + if (!this.canDamagerHurtDamagee(sub, true)) + event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (so no iter.remove()), but this works + sub = null; + } + } - // Players can not take attack damage in a SafeZone, or possibly peaceful territory - if (defLocFaction.noPvPInTerritory()) { - if (damager instanceof Player) - { - if (notify) - { - FPlayer attacker = FPlayers.i.get((Player)damager); - attacker.msg("You can't hurt other players in "+(defLocFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); - } - return false; - } - return !defLocFaction.noMonstersInTerritory(); - } - - if ( ! (damager instanceof Player)) - return true; - - FPlayer attacker = FPlayers.i.get((Player)damager); - - if (attacker == null || attacker.getPlayer() == null) - return true; + public boolean isPlayerInSafeZone(Entity damagee) { + if (!(damagee instanceof Player)) { + return false; + } + if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone()) { + return true; + } + return false; + } - if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true; + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { + return canDamagerHurtDamagee(sub, true); + } - if (attacker.hasLoginPvpDisabled()) - { - if (notify) attacker.msg("You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); - return false; - } - - Faction locFaction = Board.getFactionAt(new FLocation(attacker)); - - // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? - if (locFaction.noPvPInTerritory()) - { - if (notify) attacker.msg("You can't hurt other players while you are in "+(locFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); - return false; - } + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { + Entity damager = sub.getDamager(); + Entity damagee = sub.getEntity(); + int damage = sub.getDamage(); - if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) - return true; + if (!(damagee instanceof Player)) + return true; - if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) - return true; + FPlayer defender = FPlayers.i.get((Player) damagee); - Faction defendFaction = defender.getFaction(); - Faction attackFaction = attacker.getFaction(); - - if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) - { - if (notify) attacker.msg("You can't hurt other players until you join a faction."); - return false; - } - else if (defendFaction.isNone()) - { - if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) - { - // Allow PVP vs. Factionless in attacker's faction territory - return true; - } - else if (Conf.disablePVPForFactionlessPlayers) - { - if (notify) attacker.msg("You can't hurt players who are not currently in a faction."); - return false; - } - } - - if (defendFaction.isPeaceful()) - { - if (notify) attacker.msg("You can't hurt players who are in a peaceful faction."); - return false; - } - else if (attackFaction.isPeaceful()) - { - if (notify) attacker.msg("You can't hurt players while you are in a peaceful faction."); - return false; - } - - Relation relation = defendFaction.getRelationTo(attackFaction); - - // You can not hurt neutral factions - if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) - { - if (notify) attacker.msg("You can't hurt neutral factions. Declare them as an enemy."); - return false; - } - - // Players without faction may be hurt anywhere - if (!defender.hasFaction()) - return true; - - // You can never hurt faction members or allies - if (relation.isMember() || relation.isAlly()) - { - if (notify) attacker.msg("You can't hurt %s.", defender.describeTo(attacker)); - return false; - } - - boolean ownTerritory = defender.isInOwnTerritory(); - - // You can not hurt neutrals in their own territory. - if (ownTerritory && relation.isNeutral()) - { - if (notify) - { - attacker.msg("You can't hurt %s in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); - defender.msg("%s tried to hurt you.", attacker.describeTo(defender, true)); - } - return false; - } - - // Damage will be dealt. However check if the damage should be reduced. - if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) - { - int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor)); - sub.setDamage(newDamage); - - // Send message - if (notify) - { - String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? - defender.msg("Enemy damage reduced by %s.", perc); - } - } - - return true; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onCreatureSpawn(CreatureSpawnEvent event) - { - if (event.isCancelled() || event.getLocation() == null) - { - return; - } - - if (Conf.safeZoneNerfedCreatureTypes.contains(event.getEntityType()) && Board.getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityTarget(EntityTargetEvent event) - { - if (event.isCancelled()) return; - - // if there is a target - Entity target = event.getTarget(); - if (target == null) - { - return; - } - - // We are interested in blocking targeting for certain mobs: - if ( ! Conf.safeZoneNerfedCreatureTypes.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) - { - return; - } - - // in case the target is in a safe zone. - if (Board.getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) - { - event.setCancelled(true); - } - } + if (defender == null || defender.getPlayer() == null) + return true; - @EventHandler(priority = EventPriority.NORMAL) - public void onPaintingBreak(HangingBreakEvent event) - { - if (event.isCancelled()) return; - if (event.getCause() == RemoveCause.EXPLOSION) - { - Location loc = event.getEntity().getLocation(); - Faction faction = Board.getFactionAt(new FLocation(loc)); - if (faction.noExplosionsInTerritory()) - { - // faction is peaceful and has explosions set to disabled - event.setCancelled(true); - return; - } + Location defenderLoc = defender.getPlayer().getLocation(); + Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc)); - boolean online = faction.hasPlayersOnline(); - - if - ( - ( - faction.isNone() - && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()) - && (Conf.wildernessBlockCreepers || Conf.wildernessBlockFireballs || Conf.wildernessBlockTNT) - ) - || - ( - faction.isNormal() - && - ( online - ? (Conf.territoryBlockCreepers || Conf.territoryBlockFireballs || Conf.territoryBlockTNT) - : (Conf.territoryBlockCreepersWhenOffline || Conf.territoryBlockFireballsWhenOffline || Conf.territoryBlockTNTWhenOffline) - ) - ) - || - ( - faction.isWarZone() - && (Conf.warZoneBlockCreepers || Conf.warZoneBlockFireballs || Conf.warZoneBlockTNT) - ) - || - faction.isSafeZone() - ) - { - // explosion which needs prevention - event.setCancelled(true); - } - } - - if (! (event instanceof HangingBreakByEntityEvent)) - { - return; - } + // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source + if (damager instanceof Projectile) + damager = ((Projectile) damager).getShooter(); - Entity breaker = ((HangingBreakByEntityEvent)event).getRemover(); - if (! (breaker instanceof Player)) - { - return; - } + if (damager == damagee) // ender pearl usage and other self-inflicted damage + return true; - if ( ! FactionsBlockListener.playerCanBuildDestroyBlock((Player)breaker, event.getEntity().getLocation(), "remove paintings", false)) - { - event.setCancelled(true); - } - } + // Players can not take attack damage in a SafeZone, or possibly peaceful territory + if (defLocFaction.noPvPInTerritory()) { + if (damager instanceof Player) { + if (notify) { + FPlayer attacker = FPlayers.i.get((Player) damager); + attacker.msg("You can't hurt other players in " + (defLocFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); + } + return false; + } + return !defLocFaction.noMonstersInTerritory(); + } - @EventHandler(priority = EventPriority.NORMAL) - public void onPaintingPlace(HangingPlaceEvent event) - { - if (event.isCancelled()) return; + if (!(damager instanceof Player)) + return true; - if ( ! FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "place paintings", false) ) - { - event.setCancelled(true); - } - } + FPlayer attacker = FPlayers.i.get((Player) damager); - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityChangeBlock(EntityChangeBlockEvent event) - { - if (event.isCancelled()) return; + if (attacker == null || attacker.getPlayer() == null) + return true; - Entity entity = event.getEntity(); + if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true; - // for now, only interested in Enderman and Wither boss tomfoolery - if (!(entity instanceof Enderman) && !(entity instanceof Wither)) return; + if (attacker.hasLoginPvpDisabled()) { + if (notify) + attacker.msg("You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); + return false; + } - Location loc = event.getBlock().getLocation(); + Faction locFaction = Board.getFactionAt(new FLocation(attacker)); - if (entity instanceof Enderman) - { - if (stopEndermanBlockManipulation(loc)) - event.setCancelled(true); - } - else if (entity instanceof Wither) - { - Faction faction = Board.getFactionAt(new FLocation(loc)); - // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever - if - ( - (faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockFireballs) - || - faction.isSafeZone() - ) - event.setCancelled(true); - } - } + // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? + if (locFaction.noPvPInTerritory()) { + if (notify) + attacker.msg("You can't hurt other players while you are in " + (locFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); + return false; + } - private boolean stopEndermanBlockManipulation(Location loc) - { - if (loc == null) - { - return false; - } - // quick check to see if all Enderman deny options are enabled; if so, no need to check location - if - ( - Conf.wildernessDenyEndermanBlocks - && - Conf.territoryDenyEndermanBlocks - && - Conf.territoryDenyEndermanBlocksWhenOffline - && - Conf.safeZoneDenyEndermanBlocks - && - Conf.warZoneDenyEndermanBlocks - ) - { - return true; - } + if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) + return true; - FLocation fLoc = new FLocation(loc); - Faction claimFaction = Board.getFactionAt(fLoc); + if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) + return true; - if (claimFaction.isNone()) - { - return Conf.wildernessDenyEndermanBlocks; - } - else if (claimFaction.isNormal()) - { - return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline; - } - else if (claimFaction.isSafeZone()) - { - return Conf.safeZoneDenyEndermanBlocks; - } - else if (claimFaction.isWarZone()) - { - return Conf.warZoneDenyEndermanBlocks; - } + Faction defendFaction = defender.getFaction(); + Faction attackFaction = attacker.getFaction(); - return false; - } + if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) { + if (notify) attacker.msg("You can't hurt other players until you join a faction."); + return false; + } else if (defendFaction.isNone()) { + if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { + // Allow PVP vs. Factionless in attacker's faction territory + return true; + } else if (Conf.disablePVPForFactionlessPlayers) { + if (notify) attacker.msg("You can't hurt players who are not currently in a faction."); + return false; + } + } + + if (defendFaction.isPeaceful()) { + if (notify) attacker.msg("You can't hurt players who are in a peaceful faction."); + return false; + } else if (attackFaction.isPeaceful()) { + if (notify) attacker.msg("You can't hurt players while you are in a peaceful faction."); + return false; + } + + Relation relation = defendFaction.getRelationTo(attackFaction); + + // You can not hurt neutral factions + if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { + if (notify) attacker.msg("You can't hurt neutral factions. Declare them as an enemy."); + return false; + } + + // Players without faction may be hurt anywhere + if (!defender.hasFaction()) + return true; + + // You can never hurt faction members or allies + if (relation.isMember() || relation.isAlly()) { + if (notify) attacker.msg("You can't hurt %s.", defender.describeTo(attacker)); + return false; + } + + boolean ownTerritory = defender.isInOwnTerritory(); + + // You can not hurt neutrals in their own territory. + if (ownTerritory && relation.isNeutral()) { + if (notify) { + attacker.msg("You can't hurt %s in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); + defender.msg("%s tried to hurt you.", attacker.describeTo(defender, true)); + } + return false; + } + + // Damage will be dealt. However check if the damage should be reduced. + if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) { + int newDamage = (int) Math.ceil(damage * (1D - Conf.territoryShieldFactor)); + sub.setDamage(newDamage); + + // Send message + if (notify) { + String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? + defender.msg("Enemy damage reduced by %s.", perc); + } + } + + return true; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onCreatureSpawn(CreatureSpawnEvent event) { + if (event.isCancelled() || event.getLocation() == null) { + return; + } + + if (Conf.safeZoneNerfedCreatureTypes.contains(event.getEntityType()) && Board.getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityTarget(EntityTargetEvent event) { + if (event.isCancelled()) return; + + // if there is a target + Entity target = event.getTarget(); + if (target == null) { + return; + } + + // We are interested in blocking targeting for certain mobs: + if (!Conf.safeZoneNerfedCreatureTypes.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) { + return; + } + + // in case the target is in a safe zone. + if (Board.getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPaintingBreak(HangingBreakEvent event) { + if (event.isCancelled()) return; + if (event.getCause() == RemoveCause.EXPLOSION) { + Location loc = event.getEntity().getLocation(); + Faction faction = Board.getFactionAt(new FLocation(loc)); + if (faction.noExplosionsInTerritory()) { + // faction is peaceful and has explosions set to disabled + event.setCancelled(true); + return; + } + + boolean online = faction.hasPlayersOnline(); + + if + ( + ( + faction.isNone() + && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()) + && (Conf.wildernessBlockCreepers || Conf.wildernessBlockFireballs || Conf.wildernessBlockTNT) + ) + || + ( + faction.isNormal() + && + (online + ? (Conf.territoryBlockCreepers || Conf.territoryBlockFireballs || Conf.territoryBlockTNT) + : (Conf.territoryBlockCreepersWhenOffline || Conf.territoryBlockFireballsWhenOffline || Conf.territoryBlockTNTWhenOffline) + ) + ) + || + ( + faction.isWarZone() + && (Conf.warZoneBlockCreepers || Conf.warZoneBlockFireballs || Conf.warZoneBlockTNT) + ) + || + faction.isSafeZone() + ) { + // explosion which needs prevention + event.setCancelled(true); + } + } + + if (!(event instanceof HangingBreakByEntityEvent)) { + return; + } + + Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); + if (!(breaker instanceof Player)) { + return; + } + + if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) breaker, event.getEntity().getLocation(), "remove paintings", false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPaintingPlace(HangingPlaceEvent event) { + if (event.isCancelled()) return; + + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "place paintings", false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + if (event.isCancelled()) return; + + Entity entity = event.getEntity(); + + // for now, only interested in Enderman and Wither boss tomfoolery + if (!(entity instanceof Enderman) && !(entity instanceof Wither)) return; + + Location loc = event.getBlock().getLocation(); + + if (entity instanceof Enderman) { + if (stopEndermanBlockManipulation(loc)) + event.setCancelled(true); + } else if (entity instanceof Wither) { + Faction faction = Board.getFactionAt(new FLocation(loc)); + // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + if + ( + (faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) + || + (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) + || + (faction.isWarZone() && Conf.warZoneBlockFireballs) + || + faction.isSafeZone() + ) + event.setCancelled(true); + } + } + + private boolean stopEndermanBlockManipulation(Location loc) { + if (loc == null) { + return false; + } + // quick check to see if all Enderman deny options are enabled; if so, no need to check location + if + ( + Conf.wildernessDenyEndermanBlocks + && + Conf.territoryDenyEndermanBlocks + && + Conf.territoryDenyEndermanBlocksWhenOffline + && + Conf.safeZoneDenyEndermanBlocks + && + Conf.warZoneDenyEndermanBlocks + ) { + return true; + } + + FLocation fLoc = new FLocation(loc); + Faction claimFaction = Board.getFactionAt(fLoc); + + if (claimFaction.isNone()) { + return Conf.wildernessDenyEndermanBlocks; + } else if (claimFaction.isNormal()) { + return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline; + } else if (claimFaction.isSafeZone()) { + return Conf.safeZoneDenyEndermanBlocks; + } else if (claimFaction.isWarZone()) { + return Conf.warZoneDenyEndermanBlocks; + } + + return false; + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java index 42ccd4c4..8f8da66c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java @@ -1,69 +1,63 @@ package com.massivecraft.factions.listeners; -import org.bukkit.block.Block; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; +import com.massivecraft.factions.Conf; import org.bukkit.Location; import org.bukkit.Material; - -import com.massivecraft.factions.Conf; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.player.PlayerTeleportEvent; -public class FactionsExploitListener implements Listener -{ - @EventHandler(priority = EventPriority.NORMAL) - public void obsidianGenerator(BlockFromToEvent event) - { - if (event.isCancelled() == true || ! Conf.handleExploitObsidianGenerators) return; +public class FactionsExploitListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL) + public void obsidianGenerator(BlockFromToEvent event) { + if (event.isCancelled() == true || !Conf.handleExploitObsidianGenerators) return; - // thanks to ObGenBlocker and WorldGuard for this method - Block block = event.getToBlock(); - int source = event.getBlock().getTypeId(); - int target = block.getTypeId(); - if ((target == 55 || target == 132) && (source == 0 || source == 10 || source == 11)) - block.setTypeId(0); - } + // thanks to ObGenBlocker and WorldGuard for this method + Block block = event.getToBlock(); + int source = event.getBlock().getTypeId(); + int target = block.getTypeId(); + if ((target == 55 || target == 132) && (source == 0 || source == 10 || source == 11)) + block.setTypeId(0); + } - @EventHandler(priority = EventPriority.NORMAL) - public void enderPearlTeleport(PlayerTeleportEvent event) - { - if (event.isCancelled() == true || ! Conf.handleExploitEnderPearlClipping) return; - if (event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) return; + @EventHandler(priority = EventPriority.NORMAL) + public void enderPearlTeleport(PlayerTeleportEvent event) { + if (event.isCancelled() == true || !Conf.handleExploitEnderPearlClipping) return; + if (event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) return; - // this exploit works when the target location is within 0.31 blocks or so of a door or glass block or similar... - Location target = event.getTo(); - Location from = event.getFrom(); + // this exploit works when the target location is within 0.31 blocks or so of a door or glass block or similar... + Location target = event.getTo(); + Location from = event.getFrom(); - // blocks who occupy less than 1 block width or length wise need to be handled differently - Material mat = event.getTo().getBlock().getType(); - if ( - ((mat == Material.THIN_GLASS || mat == Material.IRON_FENCE) && clippingThrough(target, from, 0.65)) - || ((mat == Material.FENCE || mat == Material.NETHER_FENCE) && clippingThrough(target, from, 0.45)) - ) - { - event.setTo(from); - return; - } + // blocks who occupy less than 1 block width or length wise need to be handled differently + Material mat = event.getTo().getBlock().getType(); + if ( + ((mat == Material.THIN_GLASS || mat == Material.IRON_FENCE) && clippingThrough(target, from, 0.65)) + || ((mat == Material.FENCE || mat == Material.NETHER_FENCE) && clippingThrough(target, from, 0.45)) + ) { + event.setTo(from); + return; + } - // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges - target.setX(target.getBlockX() + 0.5); - target.setZ(target.getBlockZ() + 0.5); - event.setTo(target); - - } + // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges + target.setX(target.getBlockX() + 0.5); + target.setZ(target.getBlockZ() + 0.5); + event.setTo(target); - public static boolean clippingThrough(Location target, Location from, double thickness) - { - return - ( - (from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) - || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) - || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) - || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness)) - ); - } + } + + public static boolean clippingThrough(Location target, Location from, double thickness) { + return + ( + (from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) + || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) + || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) + || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness)) + ); + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java index 19289879..f0a2dacb 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -1,9 +1,11 @@ package com.massivecraft.factions.listeners; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - +import com.massivecraft.factions.*; +import com.massivecraft.factions.integration.SpoutFeatures; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.struct.Relation; +import com.massivecraft.factions.struct.Role; +import com.massivecraft.factions.zcore.util.TextUtil; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -12,584 +14,496 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.*; import org.bukkit.util.NumberConversions; -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.P; -import com.massivecraft.factions.integration.SpoutFeatures; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.struct.Relation; -import com.massivecraft.factions.struct.Role; -import com.massivecraft.factions.zcore.util.TextUtil; - - -public class FactionsPlayerListener implements Listener -{ - public P p; - public FactionsPlayerListener(P p) - { - this.p = p; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerJoin(PlayerJoinEvent event) - { - // Make sure that all online players do have a fplayer. - final FPlayer me = FPlayers.i.get(event.getPlayer()); - - // Update the lastLoginTime for this fplayer - me.setLastLoginTime(System.currentTimeMillis()); - - // Store player's current FLocation and notify them where they are - me.setLastStoodAt(new FLocation(event.getPlayer().getLocation())); - if ( ! SpoutFeatures.updateTerritoryDisplay(me)) - me.sendFactionHereMessage(); - - SpoutFeatures.updateAppearancesShortly(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerQuit(PlayerQuitEvent event) - { - FPlayer me = FPlayers.i.get(event.getPlayer()); - - // Make sure player's power is up to date when they log off. - me.getPower(); - // and update their last login time to point to when the logged off, for auto-remove routine - me.setLastLoginTime(System.currentTimeMillis()); - - Faction myFaction = me.getFaction(); - if (myFaction != null) - { - myFaction.memberLoggedOff(); - } - SpoutFeatures.playerDisconnect(me); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerMove(PlayerMoveEvent event) - { - if (event.isCancelled()) return; - - // quick check to make sure player is moving between chunks; good performance boost - if - ( - event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 - && - event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 - && - event.getFrom().getWorld() == event.getTo().getWorld() - ) - return; - - Player player = event.getPlayer(); - FPlayer me = FPlayers.i.get(player); - - // Did we change coord? - FLocation from = me.getLastStoodAt(); - FLocation to = new FLocation(event.getTo()); - - if (from.equals(to)) - { - return; - } - - // Yes we did change coord (: - - me.setLastStoodAt(to); - - // Did we change "host"(faction)? - boolean spoutClient = SpoutFeatures.availableFor(player); - Faction factionFrom = Board.getFactionAt(from); - Faction factionTo = Board.getFactionAt(to); - boolean changedFaction = (factionFrom != factionTo); - - if (changedFaction && SpoutFeatures.updateTerritoryDisplay(me)) - changedFaction = false; - - if (me.isMapAutoUpdating()) - { - me.sendMessage(Board.getMap(me.getFaction(), to, player.getLocation().getYaw())); - - if (spoutClient && Conf.spoutTerritoryOwnersShow) - SpoutFeatures.updateOwnerList(me); - } - else - { - Faction myFaction = me.getFaction(); - String ownersTo = myFaction.getOwnerListString(to); - - if (changedFaction) - { - me.sendFactionHereMessage(); - if - ( - Conf.ownedAreasEnabled - && - Conf.ownedMessageOnBorder - && - ( - !spoutClient - || - !Conf.spoutTerritoryOwnersShow - ) - && - myFaction == factionTo - && - !ownersTo.isEmpty() - ) - { - me.sendMessage(Conf.ownedLandMessage+ownersTo); - } - } - else if (spoutClient && Conf.spoutTerritoryOwnersShow) - { - SpoutFeatures.updateOwnerList(me); - } - else if - ( - Conf.ownedAreasEnabled - && - Conf.ownedMessageInsideTerritory - && - factionFrom == factionTo - && - myFaction == factionTo - ) - { - String ownersFrom = myFaction.getOwnerListString(from); - if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) - { - if (!ownersTo.isEmpty()) - me.sendMessage(Conf.ownedLandMessage+ownersTo); - else if (!Conf.publicLandMessage.isEmpty()) - me.sendMessage(Conf.publicLandMessage); - } - } - } - - if (me.getAutoClaimFor() != null) - { - me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); - } - else if (me.isAutoSafeClaimEnabled()) - { - if ( ! Permission.MANAGE_SAFE_ZONE.has(player)) - { - me.setIsAutoSafeClaimEnabled(false); - } - else - { - if (!Board.getFactionAt(to).isSafeZone()) - { - Board.setFactionAt(Factions.i.getSafeZone(), to); - me.msg("This land is now a safe zone."); - } - } - } - else if (me.isAutoWarClaimEnabled()) - { - if ( ! Permission.MANAGE_WAR_ZONE.has(player)) - { - me.setIsAutoWarClaimEnabled(false); - } - else - { - if (!Board.getFactionAt(to).isWarZone()) - { - Board.setFactionAt(Factions.i.getWarZone(), to); - me.msg("This land is now a war zone."); - } - } - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerInteract(PlayerInteractEvent event) - { - if (event.isCancelled()) return; - // only need to check right-clicks and physical as of MC 1.4+; good performance boost - if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) return; - - Block block = event.getClickedBlock(); - Player player = event.getPlayer(); - - if (block == null) return; // clicked in air, apparently - - if ( ! canPlayerUseBlock(player, block, false)) - { - event.setCancelled(true); - if (Conf.handleExploitInteractionSpam) - { - String name = player.getName(); - InteractAttemptSpam attempt = interactSpammers.get(name); - if (attempt == null) - { - attempt = new InteractAttemptSpam(); - interactSpammers.put(name, attempt); - } - int count = attempt.increment(); - if (count >= 10) - { - FPlayer me = FPlayers.i.get(name); - me.msg("Ouch, that is starting to hurt. You should give it a rest."); - player.damage(NumberConversions.floor((double)count / 10)); - } - } - return; - } - - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // only interested on right-clicks for below - - if ( ! playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) - { - event.setCancelled(true); - return; - } - } - - - // for handling people who repeatedly spam attempts to open a door (or similar) in another faction's territory - private Map interactSpammers = new HashMap(); - private static class InteractAttemptSpam - { - private int attempts = 0; - private long lastAttempt = System.currentTimeMillis(); - - // returns the current attempt count - public int increment() - { - long Now = System.currentTimeMillis(); - if (Now > lastAttempt + 2000) - attempts = 1; - else - attempts++; - lastAttempt = Now; - return attempts; - } - } - - - public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) - { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) return true; - - FPlayer me = FPlayers.i.get(name); - if (me.isAdminBypassing()) return true; - - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getFactionAt(loc); - - if (otherFaction.hasPlayersOnline()) - { - if ( ! Conf.territoryDenyUseageMaterials.contains(material)) - return true; // Item isn't one we're preventing for online factions. - } - else - { - if ( ! Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) - return true; // Item isn't one we're preventing for offline factions. - } - - if (otherFaction.isNone()) - { - if (!Conf.wildernessDenyUseage || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) - return true; // This is not faction territory. Use whatever you like here. - - if (!justCheck) - me.msg("You can't use %s in the wilderness.", TextUtil.getMaterialName(material)); - - return false; - } - else if (otherFaction.isSafeZone()) - { - if (!Conf.safeZoneDenyUseage || Permission.MANAGE_SAFE_ZONE.has(player)) - return true; - - if (!justCheck) - me.msg("You can't use %s in a safe zone.", TextUtil.getMaterialName(material)); - - return false; - } - else if (otherFaction.isWarZone()) - { - if (!Conf.warZoneDenyUseage || Permission.MANAGE_WAR_ZONE.has(player)) - return true; - - if (!justCheck) - me.msg("You can't use %s in a war zone.", TextUtil.getMaterialName(material)); - - return false; - } - - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - - // Cancel if we are not in our own territory - if (rel.confDenyUseage()) - { - if (!justCheck) - me.msg("You can't use %s in the territory of %s.", TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); - - return false; - } - - // Also cancel if player doesn't have ownership rights for this claim - if (Conf.ownedAreasEnabled && Conf.ownedAreaDenyUseage && !otherFaction.playerHasOwnershipRights(me, loc)) - { - if (!justCheck) - me.msg("You can't use %s in this territory, it is owned by: %s.", TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); - - return false; - } - - return true; - } - - public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) - { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) return true; - - FPlayer me = FPlayers.i.get(name); - if (me.isAdminBypassing()) return true; - - Material material = block.getType(); - FLocation loc = new FLocation(block); - Faction otherFaction = Board.getFactionAt(loc); - - // no door/chest/whatever protection in wilderness, war zones, or safe zones - if (!otherFaction.isNormal()) - return true; - - // We only care about some material types. - if (otherFaction.hasPlayersOnline()) - { - if ( ! Conf.territoryProtectedMaterials.contains(material)) - return true; - } - else - { - if ( ! Conf.territoryProtectedMaterialsWhenOffline.contains(material)) - return true; - } - - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - - // You may use any block unless it is another faction's territory... - if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials)) - { - if (!justCheck) - me.msg("You can't %s %s in the territory of %s.", (material == Material.SOIL ? "trample" : "use"), TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); - - return false; - } - - // Also cancel if player doesn't have ownership rights for this claim - if (Conf.ownedAreasEnabled && Conf.ownedAreaProtectMaterials && !otherFaction.playerHasOwnershipRights(me, loc)) - { - if (!justCheck) - me.msg("You can't use %s in this territory, it is owned by: %s.", TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); - - return false; - } - - return true; - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerRespawn(PlayerRespawnEvent event) - { - FPlayer me = FPlayers.i.get(event.getPlayer()); - - me.getPower(); // update power, so they won't have gained any while dead - - Location home = me.getFaction().getHome(); - if - ( - Conf.homesEnabled - && - Conf.homesTeleportToOnDeath - && - home != null - && - ( - Conf.homesRespawnFromNoPowerLossWorlds - || - ! Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()) - ) - ) - { - event.setRespawnLocation(home); - } - } - - // For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected), - // but these separate bucket events below always fire without fail - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) - { - if (event.isCancelled()) return; - - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); - - if ( ! playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) - { - event.setCancelled(true); - return; - } - } - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerBucketFill(PlayerBucketFillEvent event) - { - if (event.isCancelled()) return; - - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); - - if ( ! playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) - { - event.setCancelled(true); - return; - } - } - - public static boolean preventCommand(String fullCmd, Player player) - { - if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty() && Conf.permanentFactionMemberDenyCommands.isEmpty())) - return false; - - fullCmd = fullCmd.toLowerCase(); - - FPlayer me = FPlayers.i.get(player); - - String shortCmd; // command without the slash at the beginning - if (fullCmd.startsWith("/")) - shortCmd = fullCmd.substring(1); - else - { - shortCmd = fullCmd; - fullCmd = "/" + fullCmd; - } - - if - ( - me.hasFaction() - && - ! me.isAdminBypassing() - && - ! Conf.permanentFactionMemberDenyCommands.isEmpty() - && - me.getFaction().isPermanent() - && - isCommandInList(fullCmd, shortCmd, Conf.permanentFactionMemberDenyCommands.iterator()) - ) - { - me.msg("You can't use the command \""+fullCmd+"\" because you are in a permanent faction."); - return true; - } - - if (!me.isInOthersTerritory()) - { - return false; - } - - Relation rel = me.getRelationToLocation(); - if (rel.isAtLeast(Relation.ALLY)) - { - return false; - } - - if - ( - rel.isNeutral() - && - ! Conf.territoryNeutralDenyCommands.isEmpty() - && - ! me.isAdminBypassing() - && - isCommandInList(fullCmd, shortCmd, Conf.territoryNeutralDenyCommands.iterator()) - ) - { - me.msg("You can't use the command \""+fullCmd+"\" in neutral territory."); - return true; - } - - if - ( - rel.isEnemy() - && - ! Conf.territoryEnemyDenyCommands.isEmpty() - && - ! me.isAdminBypassing() - && - isCommandInList(fullCmd, shortCmd, Conf.territoryEnemyDenyCommands.iterator()) - ) - { - me.msg("You can't use the command \""+fullCmd+"\" in enemy territory."); - return true; - } - - return false; - } - - private static boolean isCommandInList(String fullCmd, String shortCmd, Iterator iter) - { - String cmdCheck; - while (iter.hasNext()) - { - cmdCheck = iter.next(); - if (cmdCheck == null) - { - iter.remove(); - continue; - } - - cmdCheck = cmdCheck.toLowerCase(); - if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) - return true; - } - return false; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerKick(PlayerKickEvent event) - { - if (event.isCancelled()) return; - - FPlayer badGuy = FPlayers.i.get(event.getPlayer()); - if (badGuy == null) - { - return; - } - - SpoutFeatures.playerDisconnect(badGuy); - - // if player was banned (not just kicked), get rid of their stored info - if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) - { - if (badGuy.getRole() == Role.ADMIN) - badGuy.getFaction().promoteNewLeader(); - - badGuy.leave(false); - badGuy.detach(); - } - } +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + + +public class FactionsPlayerListener implements Listener { + public P p; + + public FactionsPlayerListener(P p) { + this.p = p; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerJoin(PlayerJoinEvent event) { + // Make sure that all online players do have a fplayer. + final FPlayer me = FPlayers.i.get(event.getPlayer()); + + // Update the lastLoginTime for this fplayer + me.setLastLoginTime(System.currentTimeMillis()); + + // Store player's current FLocation and notify them where they are + me.setLastStoodAt(new FLocation(event.getPlayer().getLocation())); + if (!SpoutFeatures.updateTerritoryDisplay(me)) + me.sendFactionHereMessage(); + + SpoutFeatures.updateAppearancesShortly(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerQuit(PlayerQuitEvent event) { + FPlayer me = FPlayers.i.get(event.getPlayer()); + + // Make sure player's power is up to date when they log off. + me.getPower(); + // and update their last login time to point to when the logged off, for auto-remove routine + me.setLastLoginTime(System.currentTimeMillis()); + + Faction myFaction = me.getFaction(); + if (myFaction != null) { + myFaction.memberLoggedOff(); + } + SpoutFeatures.playerDisconnect(me); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerMove(PlayerMoveEvent event) { + if (event.isCancelled()) return; + + // quick check to make sure player is moving between chunks; good performance boost + if + ( + event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 + && + event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 + && + event.getFrom().getWorld() == event.getTo().getWorld() + ) + return; + + Player player = event.getPlayer(); + FPlayer me = FPlayers.i.get(player); + + // Did we change coord? + FLocation from = me.getLastStoodAt(); + FLocation to = new FLocation(event.getTo()); + + if (from.equals(to)) { + return; + } + + // Yes we did change coord (: + + me.setLastStoodAt(to); + + // Did we change "host"(faction)? + boolean spoutClient = SpoutFeatures.availableFor(player); + Faction factionFrom = Board.getFactionAt(from); + Faction factionTo = Board.getFactionAt(to); + boolean changedFaction = (factionFrom != factionTo); + + if (changedFaction && SpoutFeatures.updateTerritoryDisplay(me)) + changedFaction = false; + + if (me.isMapAutoUpdating()) { + me.sendMessage(Board.getMap(me.getFaction(), to, player.getLocation().getYaw())); + + if (spoutClient && Conf.spoutTerritoryOwnersShow) + SpoutFeatures.updateOwnerList(me); + } else { + Faction myFaction = me.getFaction(); + String ownersTo = myFaction.getOwnerListString(to); + + if (changedFaction) { + me.sendFactionHereMessage(); + if + ( + Conf.ownedAreasEnabled + && + Conf.ownedMessageOnBorder + && + ( + !spoutClient + || + !Conf.spoutTerritoryOwnersShow + ) + && + myFaction == factionTo + && + !ownersTo.isEmpty() + ) { + me.sendMessage(Conf.ownedLandMessage + ownersTo); + } + } else if (spoutClient && Conf.spoutTerritoryOwnersShow) { + SpoutFeatures.updateOwnerList(me); + } else if + ( + Conf.ownedAreasEnabled + && + Conf.ownedMessageInsideTerritory + && + factionFrom == factionTo + && + myFaction == factionTo + ) { + String ownersFrom = myFaction.getOwnerListString(from); + if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) { + if (!ownersTo.isEmpty()) + me.sendMessage(Conf.ownedLandMessage + ownersTo); + else if (!Conf.publicLandMessage.isEmpty()) + me.sendMessage(Conf.publicLandMessage); + } + } + } + + if (me.getAutoClaimFor() != null) { + me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); + } else if (me.isAutoSafeClaimEnabled()) { + if (!Permission.MANAGE_SAFE_ZONE.has(player)) { + me.setIsAutoSafeClaimEnabled(false); + } else { + if (!Board.getFactionAt(to).isSafeZone()) { + Board.setFactionAt(Factions.i.getSafeZone(), to); + me.msg("This land is now a safe zone."); + } + } + } else if (me.isAutoWarClaimEnabled()) { + if (!Permission.MANAGE_WAR_ZONE.has(player)) { + me.setIsAutoWarClaimEnabled(false); + } else { + if (!Board.getFactionAt(to).isWarZone()) { + Board.setFactionAt(Factions.i.getWarZone(), to); + me.msg("This land is now a war zone."); + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.isCancelled()) return; + // only need to check right-clicks and physical as of MC 1.4+; good performance boost + if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) return; + + Block block = event.getClickedBlock(); + Player player = event.getPlayer(); + + if (block == null) return; // clicked in air, apparently + + if (!canPlayerUseBlock(player, block, false)) { + event.setCancelled(true); + if (Conf.handleExploitInteractionSpam) { + String name = player.getName(); + InteractAttemptSpam attempt = interactSpammers.get(name); + if (attempt == null) { + attempt = new InteractAttemptSpam(); + interactSpammers.put(name, attempt); + } + int count = attempt.increment(); + if (count >= 10) { + FPlayer me = FPlayers.i.get(name); + me.msg("Ouch, that is starting to hurt. You should give it a rest."); + player.damage(NumberConversions.floor((double) count / 10)); + } + } + return; + } + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // only interested on right-clicks for below + + if (!playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) { + event.setCancelled(true); + return; + } + } + + + // for handling people who repeatedly spam attempts to open a door (or similar) in another faction's territory + private Map interactSpammers = new HashMap(); + + private static class InteractAttemptSpam { + private int attempts = 0; + private long lastAttempt = System.currentTimeMillis(); + + // returns the current attempt count + public int increment() { + long Now = System.currentTimeMillis(); + if (Now > lastAttempt + 2000) + attempts = 1; + else + attempts++; + lastAttempt = Now; + return attempts; + } + } + + + public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) { + String name = player.getName(); + if (Conf.playersWhoBypassAllProtection.contains(name)) return true; + + FPlayer me = FPlayers.i.get(name); + if (me.isAdminBypassing()) return true; + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getFactionAt(loc); + + if (otherFaction.hasPlayersOnline()) { + if (!Conf.territoryDenyUseageMaterials.contains(material)) + return true; // Item isn't one we're preventing for online factions. + } else { + if (!Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) + return true; // Item isn't one we're preventing for offline factions. + } + + if (otherFaction.isNone()) { + if (!Conf.wildernessDenyUseage || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) + return true; // This is not faction territory. Use whatever you like here. + + if (!justCheck) + me.msg("You can't use %s in the wilderness.", TextUtil.getMaterialName(material)); + + return false; + } else if (otherFaction.isSafeZone()) { + if (!Conf.safeZoneDenyUseage || Permission.MANAGE_SAFE_ZONE.has(player)) + return true; + + if (!justCheck) + me.msg("You can't use %s in a safe zone.", TextUtil.getMaterialName(material)); + + return false; + } else if (otherFaction.isWarZone()) { + if (!Conf.warZoneDenyUseage || Permission.MANAGE_WAR_ZONE.has(player)) + return true; + + if (!justCheck) + me.msg("You can't use %s in a war zone.", TextUtil.getMaterialName(material)); + + return false; + } + + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + + // Cancel if we are not in our own territory + if (rel.confDenyUseage()) { + if (!justCheck) + me.msg("You can't use %s in the territory of %s.", TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); + + return false; + } + + // Also cancel if player doesn't have ownership rights for this claim + if (Conf.ownedAreasEnabled && Conf.ownedAreaDenyUseage && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!justCheck) + me.msg("You can't use %s in this territory, it is owned by: %s.", TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); + + return false; + } + + return true; + } + + public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) { + String name = player.getName(); + if (Conf.playersWhoBypassAllProtection.contains(name)) return true; + + FPlayer me = FPlayers.i.get(name); + if (me.isAdminBypassing()) return true; + + Material material = block.getType(); + FLocation loc = new FLocation(block); + Faction otherFaction = Board.getFactionAt(loc); + + // no door/chest/whatever protection in wilderness, war zones, or safe zones + if (!otherFaction.isNormal()) + return true; + + // We only care about some material types. + if (otherFaction.hasPlayersOnline()) { + if (!Conf.territoryProtectedMaterials.contains(material)) + return true; + } else { + if (!Conf.territoryProtectedMaterialsWhenOffline.contains(material)) + return true; + } + + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + + // You may use any block unless it is another faction's territory... + if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials)) { + if (!justCheck) + me.msg("You can't %s %s in the territory of %s.", (material == Material.SOIL ? "trample" : "use"), TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); + + return false; + } + + // Also cancel if player doesn't have ownership rights for this claim + if (Conf.ownedAreasEnabled && Conf.ownedAreaProtectMaterials && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!justCheck) + me.msg("You can't use %s in this territory, it is owned by: %s.", TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); + + return false; + } + + return true; + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerRespawn(PlayerRespawnEvent event) { + FPlayer me = FPlayers.i.get(event.getPlayer()); + + me.getPower(); // update power, so they won't have gained any while dead + + Location home = me.getFaction().getHome(); + if + ( + Conf.homesEnabled + && + Conf.homesTeleportToOnDeath + && + home != null + && + ( + Conf.homesRespawnFromNoPowerLossWorlds + || + !Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()) + ) + ) { + event.setRespawnLocation(home); + } + } + + // For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected), + // but these separate bucket events below always fire without fail + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { + if (event.isCancelled()) return; + + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); + + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + return; + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerBucketFill(PlayerBucketFillEvent event) { + if (event.isCancelled()) return; + + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); + + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + return; + } + } + + public static boolean preventCommand(String fullCmd, Player player) { + if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty() && Conf.permanentFactionMemberDenyCommands.isEmpty())) + return false; + + fullCmd = fullCmd.toLowerCase(); + + FPlayer me = FPlayers.i.get(player); + + String shortCmd; // command without the slash at the beginning + if (fullCmd.startsWith("/")) + shortCmd = fullCmd.substring(1); + else { + shortCmd = fullCmd; + fullCmd = "/" + fullCmd; + } + + if + ( + me.hasFaction() + && + !me.isAdminBypassing() + && + !Conf.permanentFactionMemberDenyCommands.isEmpty() + && + me.getFaction().isPermanent() + && + isCommandInList(fullCmd, shortCmd, Conf.permanentFactionMemberDenyCommands.iterator()) + ) { + me.msg("You can't use the command \"" + fullCmd + "\" because you are in a permanent faction."); + return true; + } + + if (!me.isInOthersTerritory()) { + return false; + } + + Relation rel = me.getRelationToLocation(); + if (rel.isAtLeast(Relation.ALLY)) { + return false; + } + + if + ( + rel.isNeutral() + && + !Conf.territoryNeutralDenyCommands.isEmpty() + && + !me.isAdminBypassing() + && + isCommandInList(fullCmd, shortCmd, Conf.territoryNeutralDenyCommands.iterator()) + ) { + me.msg("You can't use the command \"" + fullCmd + "\" in neutral territory."); + return true; + } + + if + ( + rel.isEnemy() + && + !Conf.territoryEnemyDenyCommands.isEmpty() + && + !me.isAdminBypassing() + && + isCommandInList(fullCmd, shortCmd, Conf.territoryEnemyDenyCommands.iterator()) + ) { + me.msg("You can't use the command \"" + fullCmd + "\" in enemy territory."); + return true; + } + + return false; + } + + private static boolean isCommandInList(String fullCmd, String shortCmd, Iterator iter) { + String cmdCheck; + while (iter.hasNext()) { + cmdCheck = iter.next(); + if (cmdCheck == null) { + iter.remove(); + continue; + } + + cmdCheck = cmdCheck.toLowerCase(); + if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) + return true; + } + return false; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerKick(PlayerKickEvent event) { + if (event.isCancelled()) return; + + FPlayer badGuy = FPlayers.i.get(event.getPlayer()); + if (badGuy == null) { + return; + } + + SpoutFeatures.playerDisconnect(badGuy); + + // if player was banned (not just kicked), get rid of their stored info + if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) { + if (badGuy.getRole() == Role.ADMIN) + badGuy.getFaction().promoteNewLeader(); + + badGuy.leave(false); + badGuy.detach(); + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsServerListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsServerListener.java index 205a547e..bb82bc3c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsServerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsServerListener.java @@ -1,42 +1,36 @@ package com.massivecraft.factions.listeners; -import org.bukkit.plugin.Plugin; +import com.massivecraft.factions.P; +import com.massivecraft.factions.integration.SpoutFeatures; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; - -import com.massivecraft.factions.P; -import com.massivecraft.factions.integration.SpoutFeatures; +import org.bukkit.plugin.Plugin; -public class FactionsServerListener implements Listener -{ - public P p; - public FactionsServerListener(P p) - { - this.p = p; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginDisable(PluginDisableEvent event) - { - String name = event.getPlugin().getDescription().getName(); - if (name.equals("Spout")) - { - SpoutFeatures.setAvailable(false, ""); - } - } +public class FactionsServerListener implements Listener { + public P p; - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginEnable(PluginEnableEvent event) - { - Plugin plug = event.getPlugin(); - String name = plug.getDescription().getName(); - if (name.equals("Spout")) - { - SpoutFeatures.setAvailable(true, plug.getDescription().getFullName()); - } - } + public FactionsServerListener(P p) { + this.p = p; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginDisable(PluginDisableEvent event) { + String name = event.getPlugin().getDescription().getName(); + if (name.equals("Spout")) { + SpoutFeatures.setAvailable(false, ""); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginEnable(PluginEnableEvent event) { + Plugin plug = event.getPlugin(); + String name = plug.getDescription().getName(); + if (name.equals("Spout")) { + SpoutFeatures.setAvailable(true, plug.getDescription().getFullName()); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/struct/ChatMode.java b/src/main/java/com/massivecraft/factions/struct/ChatMode.java index 436a1cd2..38befe2f 100644 --- a/src/main/java/com/massivecraft/factions/struct/ChatMode.java +++ b/src/main/java/com/massivecraft/factions/struct/ChatMode.java @@ -1,40 +1,34 @@ package com.massivecraft.factions.struct; -public enum ChatMode -{ - FACTION(2, "faction chat"), - ALLIANCE(1, "alliance chat"), - PUBLIC(0, "public chat"); - - public final int value; - public final String nicename; - - private ChatMode(final int value, final String nicename) - { - this.value = value; - this.nicename = nicename; - } - - public boolean isAtLeast(ChatMode role) - { - return this.value >= role.value; - } - - public boolean isAtMost(ChatMode role) - { - return this.value <= role.value; - } +public enum ChatMode { + FACTION(2, "faction chat"), + ALLIANCE(1, "alliance chat"), + PUBLIC(0, "public chat"); - @Override - public String toString() - { - return this.nicename; - } - - public ChatMode getNext() - { - if (this == PUBLIC) return ALLIANCE; - if (this == ALLIANCE)return FACTION; - return PUBLIC; - } + public final int value; + public final String nicename; + + private ChatMode(final int value, final String nicename) { + this.value = value; + this.nicename = nicename; + } + + public boolean isAtLeast(ChatMode role) { + return this.value >= role.value; + } + + public boolean isAtMost(ChatMode role) { + return this.value <= role.value; + } + + @Override + public String toString() { + return this.nicename; + } + + public ChatMode getNext() { + if (this == PUBLIC) return ALLIANCE; + if (this == ALLIANCE) return FACTION; + return PUBLIC; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Permission.java b/src/main/java/com/massivecraft/factions/struct/Permission.java index fef892c6..7b125f96 100644 --- a/src/main/java/com/massivecraft/factions/struct/Permission.java +++ b/src/main/java/com/massivecraft/factions/struct/Permission.java @@ -1,87 +1,81 @@ package com.massivecraft.factions.struct; +import com.massivecraft.factions.P; import org.bukkit.command.CommandSender; -import com.massivecraft.factions.P; +public enum Permission { + MANAGE_SAFE_ZONE("managesafezone"), + MANAGE_WAR_ZONE("managewarzone"), + OWNERSHIP_BYPASS("ownershipbypass"), + ADMIN("admin"), + ADMIN_ANY("admin.any"), + AUTOCLAIM("autoclaim"), + BYPASS("bypass"), + CHAT("chat"), + CHATSPY("chatspy"), + CLAIM("claim"), + CLAIM_RADIUS("claim.radius"), + CONFIG("config"), + CREATE("create"), + DEINVITE("deinvite"), + DESCRIPTION("description"), + DISBAND("disband"), + DISBAND_ANY("disband.any"), + HELP("help"), + HOME("home"), + INVITE("invite"), + JOIN("join"), + JOIN_ANY("join.any"), + JOIN_OTHERS("join.others"), + KICK("kick"), + KICK_ANY("kick.any"), + LEAVE("leave"), + LIST("list"), + LOCK("lock"), + MAP("map"), + MOD("mod"), + MOD_ANY("mod.any"), + MONEY_BALANCE("money.balance"), + MONEY_BALANCE_ANY("money.balance.any"), + MONEY_DEPOSIT("money.deposit"), + MONEY_WITHDRAW("money.withdraw"), + MONEY_WITHDRAW_ANY("money.withdraw.any"), + MONEY_F2F("money.f2f"), + MONEY_F2P("money.f2p"), + MONEY_P2F("money.p2f"), + NO_BOOM("noboom"), + OPEN("open"), + OWNER("owner"), + OWNERLIST("ownerlist"), + SET_PEACEFUL("setpeaceful"), + SET_PERMANENT("setpermanent"), + SET_PERMANENTPOWER("setpermanentpower"), + POWERBOOST("powerboost"), + POWER("power"), + POWER_ANY("power.any"), + RELATION("relation"), + RELOAD("reload"), + SAVE("save"), + SETHOME("sethome"), + SETHOME_ANY("sethome.any"), + SHOW("show"), + TAG("tag"), + TITLE("title"), + UNCLAIM("unclaim"), + UNCLAIM_ALL("unclaimall"), + VERSION("version"),; -public enum Permission -{ - MANAGE_SAFE_ZONE("managesafezone"), - MANAGE_WAR_ZONE("managewarzone"), - OWNERSHIP_BYPASS("ownershipbypass"), - ADMIN("admin"), - ADMIN_ANY("admin.any"), - AUTOCLAIM("autoclaim"), - BYPASS("bypass"), - CHAT("chat"), - CHATSPY("chatspy"), - CLAIM("claim"), - CLAIM_RADIUS("claim.radius"), - CONFIG("config"), - CREATE("create"), - DEINVITE("deinvite"), - DESCRIPTION("description"), - DISBAND("disband"), - DISBAND_ANY("disband.any"), - HELP("help"), - HOME("home"), - INVITE("invite"), - JOIN("join"), - JOIN_ANY("join.any"), - JOIN_OTHERS("join.others"), - KICK("kick"), - KICK_ANY("kick.any"), - LEAVE("leave"), - LIST("list"), - LOCK("lock"), - MAP("map"), - MOD("mod"), - MOD_ANY("mod.any"), - MONEY_BALANCE("money.balance"), - MONEY_BALANCE_ANY("money.balance.any"), - MONEY_DEPOSIT("money.deposit"), - MONEY_WITHDRAW("money.withdraw"), - MONEY_WITHDRAW_ANY("money.withdraw.any"), - MONEY_F2F("money.f2f"), - MONEY_F2P("money.f2p"), - MONEY_P2F("money.p2f"), - NO_BOOM("noboom"), - OPEN("open"), - OWNER("owner"), - OWNERLIST("ownerlist"), - SET_PEACEFUL("setpeaceful"), - SET_PERMANENT("setpermanent"), - SET_PERMANENTPOWER("setpermanentpower"), - POWERBOOST("powerboost"), - POWER("power"), - POWER_ANY("power.any"), - RELATION("relation"), - RELOAD("reload"), - SAVE("save"), - SETHOME("sethome"), - SETHOME_ANY("sethome.any"), - SHOW("show"), - TAG("tag"), - TITLE("title"), - UNCLAIM("unclaim"), - UNCLAIM_ALL("unclaimall"), - VERSION("version"), - ; - - public final String node; - - Permission(final String node) - { - this.node = "factions."+node; - } - - public boolean has(CommandSender sender, boolean informSenderIfNot) - { - return P.p.perm.has(sender, this.node, informSenderIfNot); - } - - public boolean has(CommandSender sender) - { - return has(sender, false); - } + public final String node; + + Permission(final String node) { + this.node = "factions." + node; + } + + public boolean has(CommandSender sender, boolean informSenderIfNot) { + return P.p.perm.has(sender, this.node, informSenderIfNot); + } + + public boolean has(CommandSender sender) { + return has(sender, false); + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Relation.java b/src/main/java/com/massivecraft/factions/struct/Relation.java index 627dff08..abf617e2 100644 --- a/src/main/java/com/massivecraft/factions/struct/Relation.java +++ b/src/main/java/com/massivecraft/factions/struct/Relation.java @@ -1,146 +1,125 @@ package com.massivecraft.factions.struct; +import com.massivecraft.factions.Conf; import org.bukkit.ChatColor; -import com.massivecraft.factions.Conf; +public enum Relation { + MEMBER(3, "member"), + ALLY(2, "ally"), + NEUTRAL(1, "neutral"), + ENEMY(0, "enemy"); -public enum Relation -{ - MEMBER(3, "member"), - ALLY(2, "ally"), - NEUTRAL(1, "neutral"), - ENEMY(0, "enemy"); - - public final int value; - public final String nicename; - - private Relation(final int value, final String nicename) - { - this.value = value; - this.nicename = nicename; - } - - @Override - public String toString() - { - return this.nicename; - } - - public boolean isMember() - { - return this == MEMBER; - } - - public boolean isAlly() - { - return this == ALLY; - } - - public boolean isNeutral() - { - return this == NEUTRAL; - } - - public boolean isEnemy() - { - return this == ENEMY; - } - - public boolean isAtLeast(Relation relation) - { - return this.value >= relation.value; - } - - public boolean isAtMost(Relation relation) - { - return this.value <= relation.value; - } - - public ChatColor getColor() - { - if (this == MEMBER) - return Conf.colorMember; - else if (this == ALLY) - return Conf.colorAlly; - else if (this == NEUTRAL) - return Conf.colorNeutral; - else - return Conf.colorEnemy; - } + public final int value; + public final String nicename; - // return appropriate Conf setting for DenyBuild based on this relation and their online status - public boolean confDenyBuild(boolean online) - { - if (isMember()) - return false; + private Relation(final int value, final String nicename) { + this.value = value; + this.nicename = nicename; + } - if (online) - { - if (isEnemy()) - return Conf.territoryEnemyDenyBuild; - else if (isAlly()) - return Conf.territoryAllyDenyBuild; - else - return Conf.territoryDenyBuild; - } - else - { - if (isEnemy()) - return Conf.territoryEnemyDenyBuildWhenOffline; - else if (isAlly()) - return Conf.territoryAllyDenyBuildWhenOffline; - else - return Conf.territoryDenyBuildWhenOffline; - } - } + @Override + public String toString() { + return this.nicename; + } - // return appropriate Conf setting for PainBuild based on this relation and their online status - public boolean confPainBuild(boolean online) - { - if (isMember()) - return false; + public boolean isMember() { + return this == MEMBER; + } - if (online) - { - if (isEnemy()) - return Conf.territoryEnemyPainBuild; - else if (isAlly()) - return Conf.territoryAllyPainBuild; - else - return Conf.territoryPainBuild; - } - else - { - if (isEnemy()) - return Conf.territoryEnemyPainBuildWhenOffline; - else if (isAlly()) - return Conf.territoryAllyPainBuildWhenOffline; - else - return Conf.territoryPainBuildWhenOffline; - } - } + public boolean isAlly() { + return this == ALLY; + } - // return appropriate Conf setting for DenyUseage based on this relation - public boolean confDenyUseage() - { - if (isMember()) - return false; - else if (isEnemy()) - return Conf.territoryEnemyDenyUseage; - else if (isAlly()) - return Conf.territoryAllyDenyUseage; - else - return Conf.territoryDenyUseage; - } - - public double getRelationCost() - { - if (isEnemy()) - return Conf.econCostEnemy; - else if (isAlly()) - return Conf.econCostAlly; - else - return Conf.econCostNeutral; - } + public boolean isNeutral() { + return this == NEUTRAL; + } + + public boolean isEnemy() { + return this == ENEMY; + } + + public boolean isAtLeast(Relation relation) { + return this.value >= relation.value; + } + + public boolean isAtMost(Relation relation) { + return this.value <= relation.value; + } + + public ChatColor getColor() { + if (this == MEMBER) + return Conf.colorMember; + else if (this == ALLY) + return Conf.colorAlly; + else if (this == NEUTRAL) + return Conf.colorNeutral; + else + return Conf.colorEnemy; + } + + // return appropriate Conf setting for DenyBuild based on this relation and their online status + public boolean confDenyBuild(boolean online) { + if (isMember()) + return false; + + if (online) { + if (isEnemy()) + return Conf.territoryEnemyDenyBuild; + else if (isAlly()) + return Conf.territoryAllyDenyBuild; + else + return Conf.territoryDenyBuild; + } else { + if (isEnemy()) + return Conf.territoryEnemyDenyBuildWhenOffline; + else if (isAlly()) + return Conf.territoryAllyDenyBuildWhenOffline; + else + return Conf.territoryDenyBuildWhenOffline; + } + } + + // return appropriate Conf setting for PainBuild based on this relation and their online status + public boolean confPainBuild(boolean online) { + if (isMember()) + return false; + + if (online) { + if (isEnemy()) + return Conf.territoryEnemyPainBuild; + else if (isAlly()) + return Conf.territoryAllyPainBuild; + else + return Conf.territoryPainBuild; + } else { + if (isEnemy()) + return Conf.territoryEnemyPainBuildWhenOffline; + else if (isAlly()) + return Conf.territoryAllyPainBuildWhenOffline; + else + return Conf.territoryPainBuildWhenOffline; + } + } + + // return appropriate Conf setting for DenyUseage based on this relation + public boolean confDenyUseage() { + if (isMember()) + return false; + else if (isEnemy()) + return Conf.territoryEnemyDenyUseage; + else if (isAlly()) + return Conf.territoryAllyDenyUseage; + else + return Conf.territoryDenyUseage; + } + + public double getRelationCost() { + if (isEnemy()) + return Conf.econCostEnemy; + else if (isAlly()) + return Conf.econCostAlly; + else + return Conf.econCostNeutral; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Role.java b/src/main/java/com/massivecraft/factions/struct/Role.java index df024a89..4ce4e69d 100644 --- a/src/main/java/com/massivecraft/factions/struct/Role.java +++ b/src/main/java/com/massivecraft/factions/struct/Role.java @@ -2,49 +2,41 @@ package com.massivecraft.factions.struct; import com.massivecraft.factions.Conf; -public enum Role -{ - ADMIN(2, "admin"), - MODERATOR(1, "moderator"), - NORMAL(0, "normal member"); - - public final int value; - public final String nicename; - - private Role(final int value, final String nicename) - { - this.value = value; - this.nicename = nicename; - } - - public boolean isAtLeast(Role role) - { - return this.value >= role.value; - } - - public boolean isAtMost(Role role) - { - return this.value <= role.value; - } +public enum Role { + ADMIN(2, "admin"), + MODERATOR(1, "moderator"), + NORMAL(0, "normal member"); - @Override - public String toString() - { - return this.nicename; - } - - public String getPrefix() - { - if (this == Role.ADMIN) - { - return Conf.prefixAdmin; - } - - if (this == Role.MODERATOR) - { - return Conf.prefixMod; - } - - return ""; - } + public final int value; + public final String nicename; + + private Role(final int value, final String nicename) { + this.value = value; + this.nicename = nicename; + } + + public boolean isAtLeast(Role role) { + return this.value >= role.value; + } + + public boolean isAtMost(Role role) { + return this.value <= role.value; + } + + @Override + public String toString() { + return this.nicename; + } + + public String getPrefix() { + if (this == Role.ADMIN) { + return Conf.prefixAdmin; + } + + if (this == Role.MODERATOR) { + return Conf.prefixMod; + } + + return ""; + } } diff --git a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java index 9d07cb8d..519d8798 100644 --- a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java +++ b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java @@ -1,97 +1,89 @@ package com.massivecraft.factions.util; -import java.util.*; - import org.bukkit.ChatColor; -public class AsciiCompass -{ - public enum Point - { - N('N'), - NE('/'), - E('E'), - SE('\\'), - S('S'), - SW('/'), - W('W'), - NW('\\'); - - public final char asciiChar; - - private Point(final char asciiChar) - { - this.asciiChar = asciiChar; - } - - @Override - public String toString() - { - return String.valueOf(this.asciiChar); - } - - public String toString(boolean isActive, ChatColor colorActive, String colorDefault) - { - return (isActive ? colorActive : colorDefault)+String.valueOf(this.asciiChar); - } - } - - public static AsciiCompass.Point getCompassPointForDirection(double inDegrees) - { - double degrees = (inDegrees - 180) % 360 ; - if (degrees < 0) - degrees += 360; - - if (0 <= degrees && degrees < 22.5) - return AsciiCompass.Point.N; - else if (22.5 <= degrees && degrees < 67.5) - return AsciiCompass.Point.NE; - else if (67.5 <= degrees && degrees < 112.5) - return AsciiCompass.Point.E; - else if (112.5 <= degrees && degrees < 157.5) - return AsciiCompass.Point.SE; - else if (157.5 <= degrees && degrees < 202.5) - return AsciiCompass.Point.S; - else if (202.5 <= degrees && degrees < 247.5) - return AsciiCompass.Point.SW; - else if (247.5 <= degrees && degrees < 292.5) - return AsciiCompass.Point.W; - else if (292.5 <= degrees && degrees < 337.5) - return AsciiCompass.Point.NW; - else if (337.5 <= degrees && degrees < 360.0) - return AsciiCompass.Point.N; - else - return null; - } - - public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) - { - ArrayList ret = new ArrayList(); - String row; - - row = ""; - row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); - row += Point.N.toString(Point.N == point, colorActive, colorDefault); - row += Point.NE.toString(Point.NE == point, colorActive, colorDefault); - ret.add(row); - - row = ""; - row += Point.W.toString(Point.W == point, colorActive, colorDefault); - row += colorDefault+"+"; - row += Point.E.toString(Point.E == point, colorActive, colorDefault); - ret.add(row); - - row = ""; - row += Point.SW.toString(Point.SW == point, colorActive, colorDefault); - row += Point.S.toString(Point.S == point, colorActive, colorDefault); - row += Point.SE.toString(Point.SE == point, colorActive, colorDefault); - ret.add(row); +import java.util.ArrayList; - return ret; - } - - public static ArrayList getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) - { - return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); - } +public class AsciiCompass { + public enum Point { + N('N'), + NE('/'), + E('E'), + SE('\\'), + S('S'), + SW('/'), + W('W'), + NW('\\'); + + public final char asciiChar; + + private Point(final char asciiChar) { + this.asciiChar = asciiChar; + } + + @Override + public String toString() { + return String.valueOf(this.asciiChar); + } + + public String toString(boolean isActive, ChatColor colorActive, String colorDefault) { + return (isActive ? colorActive : colorDefault) + String.valueOf(this.asciiChar); + } + } + + public static AsciiCompass.Point getCompassPointForDirection(double inDegrees) { + double degrees = (inDegrees - 180) % 360; + if (degrees < 0) + degrees += 360; + + if (0 <= degrees && degrees < 22.5) + return AsciiCompass.Point.N; + else if (22.5 <= degrees && degrees < 67.5) + return AsciiCompass.Point.NE; + else if (67.5 <= degrees && degrees < 112.5) + return AsciiCompass.Point.E; + else if (112.5 <= degrees && degrees < 157.5) + return AsciiCompass.Point.SE; + else if (157.5 <= degrees && degrees < 202.5) + return AsciiCompass.Point.S; + else if (202.5 <= degrees && degrees < 247.5) + return AsciiCompass.Point.SW; + else if (247.5 <= degrees && degrees < 292.5) + return AsciiCompass.Point.W; + else if (292.5 <= degrees && degrees < 337.5) + return AsciiCompass.Point.NW; + else if (337.5 <= degrees && degrees < 360.0) + return AsciiCompass.Point.N; + else + return null; + } + + public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) { + ArrayList ret = new ArrayList(); + String row; + + row = ""; + row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); + row += Point.N.toString(Point.N == point, colorActive, colorDefault); + row += Point.NE.toString(Point.NE == point, colorActive, colorDefault); + ret.add(row); + + row = ""; + row += Point.W.toString(Point.W == point, colorActive, colorDefault); + row += colorDefault + "+"; + row += Point.E.toString(Point.E == point, colorActive, colorDefault); + ret.add(row); + + row = ""; + row += Point.SW.toString(Point.SW == point, colorActive, colorDefault); + row += Point.S.toString(Point.S == point, colorActive, colorDefault); + row += Point.SE.toString(Point.SE == point, colorActive, colorDefault); + ret.add(row); + + return ret; + } + + public static ArrayList getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) { + return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); + } } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java index 1d85635a..1b48d449 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java @@ -1,94 +1,79 @@ package com.massivecraft.factions.util; +import com.massivecraft.factions.*; +import com.massivecraft.factions.struct.Role; +import org.bukkit.scheduler.BukkitRunnable; + import java.util.ArrayList; import java.util.ListIterator; -import org.bukkit.scheduler.BukkitRunnable; +public class AutoLeaveProcessTask extends BukkitRunnable { + private transient boolean readyToGo = false; + private transient boolean finished = false; + private transient ArrayList fplayers; + private transient ListIterator iterator; + private transient double toleranceMillis; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.P; -import com.massivecraft.factions.struct.Role; + public AutoLeaveProcessTask() { + fplayers = new ArrayList(FPlayers.i.get()); + this.iterator = fplayers.listIterator(); + this.toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000; + this.readyToGo = true; + this.finished = false; + } -public class AutoLeaveProcessTask extends BukkitRunnable -{ - private transient boolean readyToGo = false; - private transient boolean finished = false; - private transient ArrayList fplayers; - private transient ListIterator iterator; - private transient double toleranceMillis; + public void run() { + if (Conf.autoLeaveAfterDaysOfInactivity <= 0.0 || Conf.autoLeaveRoutineMaxMillisecondsPerTick <= 0.0) { + this.stop(); + return; + } - public AutoLeaveProcessTask() - { - fplayers = new ArrayList(FPlayers.i.get()); - this.iterator = fplayers.listIterator(); - this.toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000; - this.readyToGo = true; - this.finished = false; - } + if (!readyToGo) return; + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; + // and this is tracked to keep one iteration from dragging on too long and possibly choking the system if there are a very large number of players to go through + long loopStartTime = System.currentTimeMillis(); - public void run() - { - if (Conf.autoLeaveAfterDaysOfInactivity <= 0.0 || Conf.autoLeaveRoutineMaxMillisecondsPerTick <= 0.0) - { - this.stop(); - return; - } + while (iterator.hasNext()) { + long now = System.currentTimeMillis(); - if ( ! readyToGo) return; - // this is set so it only does one iteration at a time, no matter how frequently the timer fires - readyToGo = false; - // and this is tracked to keep one iteration from dragging on too long and possibly choking the system if there are a very large number of players to go through - long loopStartTime = System.currentTimeMillis(); + // if this iteration has been running for maximum time, stop to take a breather until next tick + if (now > loopStartTime + Conf.autoLeaveRoutineMaxMillisecondsPerTick) { + readyToGo = true; + return; + } - while(iterator.hasNext()) - { - long now = System.currentTimeMillis(); + FPlayer fplayer = iterator.next(); + if (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) { + if (Conf.logFactionLeave || Conf.logFactionKick) + P.p.log("Player " + fplayer.getName() + " was auto-removed due to inactivity."); - // if this iteration has been running for maximum time, stop to take a breather until next tick - if (now > loopStartTime + Conf.autoLeaveRoutineMaxMillisecondsPerTick) - { - readyToGo = true; - return; - } + // if player is faction admin, sort out the faction since he's going away + if (fplayer.getRole() == Role.ADMIN) { + Faction faction = fplayer.getFaction(); + if (faction != null) + fplayer.getFaction().promoteNewLeader(); + } - FPlayer fplayer = iterator.next(); - if (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) - { - if (Conf.logFactionLeave || Conf.logFactionKick) - P.p.log("Player "+fplayer.getName()+" was auto-removed due to inactivity."); + fplayer.leave(false); + iterator.remove(); // go ahead and remove this list's link to the FPlayer object + fplayer.detach(); + } + } - // if player is faction admin, sort out the faction since he's going away - if (fplayer.getRole() == Role.ADMIN) - { - Faction faction = fplayer.getFaction(); - if (faction != null) - fplayer.getFaction().promoteNewLeader(); - } + // looks like we've finished + this.stop(); + } - fplayer.leave(false); - iterator.remove(); // go ahead and remove this list's link to the FPlayer object - fplayer.detach(); - } - } + // we're done, shut down + public void stop() { + readyToGo = false; + finished = true; - // looks like we've finished - this.stop(); - } + this.cancel(); + } - // we're done, shut down - public void stop() - { - readyToGo = false; - finished = true; - - this.cancel(); - } - - public boolean isFinished() - { - return finished; - } + public boolean isFinished() { + return finished; + } } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java index e42883cb..42bf9609 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java @@ -3,26 +3,23 @@ package com.massivecraft.factions.util; import com.massivecraft.factions.Conf; import com.massivecraft.factions.P; -public class AutoLeaveTask implements Runnable -{ - private static AutoLeaveProcessTask task; - double rate; +public class AutoLeaveTask implements Runnable { + private static AutoLeaveProcessTask task; + double rate; - public AutoLeaveTask() - { - this.rate = Conf.autoLeaveRoutineRunsEveryXMinutes; - } + public AutoLeaveTask() { + this.rate = Conf.autoLeaveRoutineRunsEveryXMinutes; + } - public synchronized void run() - { - if (task != null && ! task.isFinished()) - return; + public synchronized void run() { + if (task != null && !task.isFinished()) + return; - task = new AutoLeaveProcessTask(); - task.runTaskTimer(P.p, 1, 1); + task = new AutoLeaveProcessTask(); + task.runTaskTimer(P.p, 1, 1); - // maybe setting has been changed? if so, restart this task at new rate - if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) - P.p.startAutoLeaveTask(true); - } + // maybe setting has been changed? if so, restart this task at new rate + if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) + P.p.startAutoLeaveTask(true); + } } diff --git a/src/main/java/com/massivecraft/factions/util/LazyLocation.java b/src/main/java/com/massivecraft/factions/util/LazyLocation.java index 83d748ac..eec522ce 100644 --- a/src/main/java/com/massivecraft/factions/util/LazyLocation.java +++ b/src/main/java/com/massivecraft/factions/util/LazyLocation.java @@ -9,99 +9,86 @@ import org.bukkit.World; * yet when an object of this class is created, only when the Location is first accessed. */ -public class LazyLocation -{ - private Location location = null; - private String worldName; - private double x; - private double y; - private double z; - private float pitch; - private float yaw; +public class LazyLocation { + private Location location = null; + private String worldName; + private double x; + private double y; + private double z; + private float pitch; + private float yaw; - public LazyLocation(Location loc) - { - setLocation(loc); - } + public LazyLocation(Location loc) { + setLocation(loc); + } - public LazyLocation(final String worldName, final double x, final double y, final double z) - { - this(worldName, x, y, z, 0, 0); - } + public LazyLocation(final String worldName, final double x, final double y, final double z) { + this(worldName, x, y, z, 0, 0); + } - public LazyLocation(final String worldName, final double x, final double y, final double z, final float yaw, final float pitch) - { - this.worldName = worldName; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } + public LazyLocation(final String worldName, final double x, final double y, final double z, final float yaw, final float pitch) { + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } - // This returns the actual Location - public final Location getLocation() - { - // make sure Location is initialized before returning it - initLocation(); - return location; - } + // This returns the actual Location + public final Location getLocation() { + // make sure Location is initialized before returning it + initLocation(); + return location; + } - // change the Location - public final void setLocation(Location loc) - { - this.location = loc; - this.worldName = loc.getWorld().getName(); - this.x = loc.getX(); - this.y = loc.getY(); - this.z = loc.getZ(); - this.yaw = loc.getYaw(); - this.pitch = loc.getPitch(); - } + // change the Location + public final void setLocation(Location loc) { + this.location = loc; + this.worldName = loc.getWorld().getName(); + this.x = loc.getX(); + this.y = loc.getY(); + this.z = loc.getZ(); + this.yaw = loc.getYaw(); + this.pitch = loc.getPitch(); + } - // This initializes the Location - private void initLocation() - { - // if location is already initialized, simply return - if (location != null) return; + // This initializes the Location + private void initLocation() { + // if location is already initialized, simply return + if (location != null) return; - // get World; hopefully it's initialized at this point - World world = Bukkit.getWorld(worldName); - if (world == null) return; + // get World; hopefully it's initialized at this point + World world = Bukkit.getWorld(worldName); + if (world == null) return; - // store the Location for future calls, and pass it on - location = new Location(world, x, y, z, yaw, pitch); - } + // store the Location for future calls, and pass it on + location = new Location(world, x, y, z, yaw, pitch); + } - public final String getWorldName() - { - return worldName; - } + public final String getWorldName() { + return worldName; + } - public final double getX() - { - return x; - } + public final double getX() { + return x; + } - public final double getY() - { - return y; - } + public final double getY() { + return y; + } - public final double getZ() - { - return z; - } + public final double getZ() { + return z; + } - public final double getPitch() - { - return pitch; - } + public final double getPitch() { + return pitch; + } - public final double getYaw() - { - return yaw; - } + public final double getYaw() { + return yaw; + } } diff --git a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java index 4da08843..5fd7ee85 100644 --- a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java @@ -1,128 +1,104 @@ package com.massivecraft.factions.util; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.P; +import org.bukkit.craftbukkit.libs.com.google.gson.*; + import java.lang.reflect.Type; -import java.util.concurrent.ConcurrentHashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; -import java.util.Set; -import java.util.logging.Level; import java.util.Map.Entry; - -import org.bukkit.craftbukkit.libs.com.google.gson.JsonArray; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonDeserializationContext; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonDeserializer; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonElement; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonObject; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonParseException; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonPrimitive; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonSerializationContext; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonSerializer; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.P; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; -public class MapFLocToStringSetTypeAdapter implements JsonDeserializer>>, JsonSerializer>> -{ +public class MapFLocToStringSetTypeAdapter implements JsonDeserializer>>, JsonSerializer>> { - @Override - public Map> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException - { - try { - JsonObject obj = json.getAsJsonObject(); - if (obj == null) - { - return null; - } + @Override + public Map> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } - Map> locationMap = new ConcurrentHashMap>(); - Set nameSet; - Iterator iter; - String worldName; - String[] coords; - int x, z; + Map> locationMap = new ConcurrentHashMap>(); + Set nameSet; + Iterator iter; + String worldName; + String[] coords; + int x, z; - for (Entry entry : obj.entrySet()) - { - worldName = entry.getKey(); - for (Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) - { - coords = entry2.getKey().trim().split("[,\\s]+"); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); + for (Entry entry : obj.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); - nameSet = new HashSet(); - iter = entry2.getValue().getAsJsonArray().iterator(); - while (iter.hasNext()) - { - nameSet.add(iter.next().getAsString()); - } + nameSet = new HashSet(); + iter = entry2.getValue().getAsJsonArray().iterator(); + while (iter.hasNext()) { + nameSet.add(iter.next().getAsString()); + } - locationMap.put(new FLocation(worldName, x, z), nameSet); - } - } + locationMap.put(new FLocation(worldName, x, z), nameSet); + } + } - return locationMap; + return locationMap; - } - catch (Exception ex) - { - ex.printStackTrace(); - P.p.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets."); - return null; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + P.p.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets."); + return null; + } + } - @Override - public JsonElement serialize(Map> src, Type typeOfSrc, JsonSerializationContext context) - { - JsonObject obj = new JsonObject(); + @Override + public JsonElement serialize(Map> src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); - try { - if (src != null) - { - FLocation loc; - String locWorld; - Set nameSet; - Iterator iter; - JsonArray nameArray; - JsonPrimitive nameElement; + try { + if (src != null) { + FLocation loc; + String locWorld; + Set nameSet; + Iterator iter; + JsonArray nameArray; + JsonPrimitive nameElement; - for (Entry> entry : src.entrySet()) - { - loc = entry.getKey(); - locWorld = loc.getWorldName(); - nameSet = entry.getValue(); + for (Entry> entry : src.entrySet()) { + loc = entry.getKey(); + locWorld = loc.getWorldName(); + nameSet = entry.getValue(); - if (nameSet == null || nameSet.isEmpty()) - { - continue; - } + if (nameSet == null || nameSet.isEmpty()) { + continue; + } - nameArray = new JsonArray(); - iter = nameSet.iterator(); - while (iter.hasNext()) - { - nameElement = new JsonPrimitive(iter.next()); - nameArray.add(nameElement); - } + nameArray = new JsonArray(); + iter = nameSet.iterator(); + while (iter.hasNext()) { + nameElement = new JsonPrimitive(iter.next()); + nameArray.add(nameElement); + } - if ( ! obj.has(locWorld)) - { - obj.add(locWorld, new JsonObject()); - } + if (!obj.has(locWorld)) { + obj.add(locWorld, new JsonObject()); + } - obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); - } - } - return obj; + obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); + } + } + return obj; - } - catch (Exception ex) - { - ex.printStackTrace(); - P.p.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets."); - return obj; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + P.p.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets."); + return obj; + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/MiscUtil.java b/src/main/java/com/massivecraft/factions/util/MiscUtil.java index 32067ae8..086e132f 100644 --- a/src/main/java/com/massivecraft/factions/util/MiscUtil.java +++ b/src/main/java/com/massivecraft/factions/util/MiscUtil.java @@ -1,69 +1,63 @@ package com.massivecraft.factions.util; +import org.bukkit.ChatColor; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; + import java.util.Arrays; import java.util.HashSet; -import org.bukkit.ChatColor; -import org.bukkit.entity.Creature; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Entity; +public class MiscUtil { + public static EntityType creatureTypeFromEntity(Entity entity) { + if (!(entity instanceof Creature)) { + return null; + } + + String name = entity.getClass().getSimpleName(); + name = name.substring(5); // Remove "Craft" + + return EntityType.fromName(name); + } + + // Inclusive range + public static long[] range(long start, long end) { + long[] values = new long[(int) Math.abs(end - start) + 1]; + + if (end < start) { + long oldstart = start; + start = end; + end = oldstart; + } + + for (long i = start; i <= end; i++) { + values[(int) (i - start)] = i; + } + + return values; + } + + /// TODO create tag whitelist!! + public static HashSet substanceChars = new HashSet(Arrays.asList(new String[]{ + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", + "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", + "s", "t", "u", "v", "w", "x", "y", "z" + })); + + public static String getComparisonString(String str) { + String ret = ""; + + str = ChatColor.stripColor(str); + str = str.toLowerCase(); + + for (char c : str.toCharArray()) { + if (substanceChars.contains(String.valueOf(c))) { + ret += c; + } + } + return ret.toLowerCase(); + } -public class MiscUtil -{ - public static EntityType creatureTypeFromEntity(Entity entity) - { - if ( ! (entity instanceof Creature)) - { - return null; - } - - String name = entity.getClass().getSimpleName(); - name = name.substring(5); // Remove "Craft" - - return EntityType.fromName(name); - } - - // Inclusive range - public static long[] range(long start, long end) { - long[] values = new long[(int) Math.abs(end - start) + 1]; - - if (end < start) { - long oldstart = start; - start = end; - end = oldstart; - } - - for (long i = start; i <= end; i++) { - values[(int) (i - start)] = i; - } - - return values; - } - - /// TODO create tag whitelist!! - public static HashSet substanceChars = new HashSet(Arrays.asList(new String []{ - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", - "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", - "s", "t", "u", "v", "w", "x", "y", "z" - })); - - public static String getComparisonString(String str) - { - String ret = ""; - - str = ChatColor.stripColor(str); - str = str.toLowerCase(); - - for (char c : str.toCharArray()) - { - if (substanceChars.contains(String.valueOf(c))) - { - ret += c; - } - } - return ret.toLowerCase(); - } - } diff --git a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java index cd6176d6..e7792378 100644 --- a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java @@ -1,73 +1,58 @@ package com.massivecraft.factions.util; +import com.massivecraft.factions.P; +import org.bukkit.craftbukkit.libs.com.google.gson.*; + import java.lang.reflect.Type; import java.util.logging.Level; -import com.massivecraft.factions.P; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonDeserializationContext; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonDeserializer; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonElement; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonObject; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonParseException; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonSerializationContext; -import org.bukkit.craftbukkit.libs.com.google.gson.JsonSerializer; +public class MyLocationTypeAdapter implements JsonDeserializer, JsonSerializer { + private static final String WORLD = "world"; + private static final String X = "x"; + private static final String Y = "y"; + private static final String Z = "z"; + private static final String YAW = "yaw"; + private static final String PITCH = "pitch"; + @Override + public LazyLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); -public class MyLocationTypeAdapter implements JsonDeserializer, JsonSerializer -{ - private static final String WORLD = "world"; - private static final String X = "x"; - private static final String Y = "y"; - private static final String Z = "z"; - private static final String YAW = "yaw"; - private static final String PITCH = "pitch"; - - @Override - public LazyLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException - { - try - { - JsonObject obj = json.getAsJsonObject(); + String worldName = obj.get(WORLD).getAsString(); + double x = obj.get(X).getAsDouble(); + double y = obj.get(Y).getAsDouble(); + double z = obj.get(Z).getAsDouble(); + float yaw = obj.get(YAW).getAsFloat(); + float pitch = obj.get(PITCH).getAsFloat(); - String worldName = obj.get(WORLD).getAsString(); - double x = obj.get(X).getAsDouble(); - double y = obj.get(Y).getAsDouble(); - double z = obj.get(Z).getAsDouble(); - float yaw = obj.get(YAW).getAsFloat(); - float pitch = obj.get(PITCH).getAsFloat(); + return new LazyLocation(worldName, x, y, z, yaw, pitch); - return new LazyLocation(worldName, x, y, z, yaw, pitch); + } catch (Exception ex) { + ex.printStackTrace(); + P.p.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); + return null; + } + } - } - catch (Exception ex) - { - ex.printStackTrace(); - P.p.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); - return null; - } - } + @Override + public JsonElement serialize(LazyLocation src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); - @Override - public JsonElement serialize(LazyLocation src, Type typeOfSrc, JsonSerializationContext context) { - JsonObject obj = new JsonObject(); + try { + obj.addProperty(WORLD, src.getWorldName()); + obj.addProperty(X, src.getX()); + obj.addProperty(Y, src.getY()); + obj.addProperty(Z, src.getZ()); + obj.addProperty(YAW, src.getYaw()); + obj.addProperty(PITCH, src.getPitch()); - try - { - obj.addProperty(WORLD, src.getWorldName()); - obj.addProperty(X, src.getX()); - obj.addProperty(Y, src.getY()); - obj.addProperty(Z, src.getZ()); - obj.addProperty(YAW, src.getYaw()); - obj.addProperty(PITCH, src.getPitch()); - - return obj; - } - catch (Exception ex) - { - ex.printStackTrace(); - P.p.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); - return obj; - } - } + return obj; + } catch (Exception ex) { + ex.printStackTrace(); + P.p.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); + return obj; + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/RelationUtil.java b/src/main/java/com/massivecraft/factions/util/RelationUtil.java index 05862cf4..79da7375 100644 --- a/src/main/java/com/massivecraft/factions/util/RelationUtil.java +++ b/src/main/java/com/massivecraft/factions/util/RelationUtil.java @@ -1,140 +1,110 @@ package com.massivecraft.factions.util; -import org.bukkit.ChatColor; - import com.massivecraft.factions.Conf; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.Faction; import com.massivecraft.factions.iface.RelationParticipator; import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.zcore.util.TextUtil; +import org.bukkit.ChatColor; -public class RelationUtil -{ - public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) - { - String ret = ""; +public class RelationUtil { + public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) { + String ret = ""; - Faction thatFaction = getFaction(that); - if (thatFaction == null) return "ERROR"; // ERROR + Faction thatFaction = getFaction(that); + if (thatFaction == null) return "ERROR"; // ERROR - Faction myFaction = getFaction(me); + Faction myFaction = getFaction(me); // if (myFaction == null) return that.describeTo(null); // no relation, but can show basic name or tag - if (that instanceof Faction) - { - if (me instanceof FPlayer && myFaction == thatFaction) - { - ret = "your faction"; - } - else - { - ret = thatFaction.getTag(); - } - } - else if (that instanceof FPlayer) - { - FPlayer fplayerthat = (FPlayer) that; - if (that == me) - { - ret = "you"; - } - else if (thatFaction == myFaction) - { - ret = fplayerthat.getNameAndTitle(); - } - else - { - ret = fplayerthat.getNameAndTag(); - } - } + if (that instanceof Faction) { + if (me instanceof FPlayer && myFaction == thatFaction) { + ret = "your faction"; + } else { + ret = thatFaction.getTag(); + } + } else if (that instanceof FPlayer) { + FPlayer fplayerthat = (FPlayer) that; + if (that == me) { + ret = "you"; + } else if (thatFaction == myFaction) { + ret = fplayerthat.getNameAndTitle(); + } else { + ret = fplayerthat.getNameAndTag(); + } + } - if (ucfirst) - { - ret = TextUtil.upperCaseFirst(ret); - } + if (ucfirst) { + ret = TextUtil.upperCaseFirst(ret); + } - return "" + getColorOfThatToMe(that, me) + ret; - } + return "" + getColorOfThatToMe(that, me) + ret; + } - public static String describeThatToMe(RelationParticipator that, RelationParticipator me) - { - return describeThatToMe(that, me, false); - } + public static String describeThatToMe(RelationParticipator that, RelationParticipator me) { + return describeThatToMe(that, me, false); + } - public static Relation getRelationTo(RelationParticipator me, RelationParticipator that) - { - return getRelationTo(that, me, false); - } + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that) { + return getRelationTo(that, me, false); + } - public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) - { - Faction fthat = getFaction(that); - if (fthat == null) return Relation.NEUTRAL; // ERROR + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) { + Faction fthat = getFaction(that); + if (fthat == null) return Relation.NEUTRAL; // ERROR - Faction fme = getFaction(me); - if (fme == null) return Relation.NEUTRAL; // ERROR + Faction fme = getFaction(me); + if (fme == null) return Relation.NEUTRAL; // ERROR - if (!fthat.isNormal() || !fme.isNormal()) - { - return Relation.NEUTRAL; - } + if (!fthat.isNormal() || !fme.isNormal()) { + return Relation.NEUTRAL; + } - if (fthat.equals(fme)) - { - return Relation.MEMBER; - } + if (fthat.equals(fme)) { + return Relation.MEMBER; + } - if (!ignorePeaceful && (fme.isPeaceful() || fthat.isPeaceful())) - { - return Relation.NEUTRAL; - } + if (!ignorePeaceful && (fme.isPeaceful() || fthat.isPeaceful())) { + return Relation.NEUTRAL; + } - if (fme.getRelationWish(fthat).value >= fthat.getRelationWish(fme).value) - { - return fthat.getRelationWish(fme); - } + if (fme.getRelationWish(fthat).value >= fthat.getRelationWish(fme).value) { + return fthat.getRelationWish(fme); + } - return fme.getRelationWish(fthat); - } + return fme.getRelationWish(fthat); + } - public static Faction getFaction(RelationParticipator rp) - { - if (rp instanceof Faction) - { - return (Faction) rp; - } + public static Faction getFaction(RelationParticipator rp) { + if (rp instanceof Faction) { + return (Faction) rp; + } - if (rp instanceof FPlayer) - { - return ((FPlayer) rp).getFaction(); - } + if (rp instanceof FPlayer) { + return ((FPlayer) rp).getFaction(); + } - // ERROR - return null; - } + // ERROR + return null; + } - public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) - { - Faction thatFaction = getFaction(that); - if (thatFaction != null) - { - if (thatFaction.isPeaceful() && thatFaction != getFaction(me)) - { - return Conf.colorPeaceful; - } - - if (thatFaction.isSafeZone() && thatFaction != getFaction(me)) - { - return Conf.colorPeaceful; - } - - if (thatFaction.isWarZone() && thatFaction != getFaction(me)) - { - return Conf.colorWar; - } - } - - return getRelationTo(that, me).getColor(); - } + public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) { + Faction thatFaction = getFaction(that); + if (thatFaction != null) { + if (thatFaction.isPeaceful() && thatFaction != getFaction(me)) { + return Conf.colorPeaceful; + } + + if (thatFaction.isSafeZone() && thatFaction != getFaction(me)) { + return Conf.colorPeaceful; + } + + if (thatFaction.isWarZone() && thatFaction != getFaction(me)) { + return Conf.colorWar; + } + } + + return getRelationTo(that, me).getColor(); + } } diff --git a/src/main/java/com/massivecraft/factions/util/SpiralTask.java b/src/main/java/com/massivecraft/factions/util/SpiralTask.java index 98d5927a..d8fa6374 100644 --- a/src/main/java/com/massivecraft/factions/util/SpiralTask.java +++ b/src/main/java/com/massivecraft/factions/util/SpiralTask.java @@ -1,13 +1,12 @@ package com.massivecraft.factions.util; -import java.util.logging.Level; - +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.P; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.P; +import java.util.logging.Level; /* @@ -23,78 +22,74 @@ import com.massivecraft.factions.P; * [7][<][<][<][<][<][<][7] */ -public abstract class SpiralTask implements Runnable -{ - // general task-related reference data - private transient World world = null; - private transient boolean readyToGo = false; - private transient int taskID = -1; - private transient int limit = 0; +public abstract class SpiralTask implements Runnable { + // general task-related reference data + private transient World world = null; + private transient boolean readyToGo = false; + private transient int taskID = -1; + private transient int limit = 0; - // values for the spiral pattern routine - private transient int x = 0; - private transient int z = 0; - private transient boolean isZLeg = false; - private transient boolean isNeg = false; - private transient int length = -1; - private transient int current = 0; + // values for the spiral pattern routine + private transient int x = 0; + private transient int z = 0; + private transient boolean isZLeg = false; + private transient boolean isNeg = false; + private transient int length = -1; + private transient int current = 0; - @SuppressWarnings("LeakingThisInConstructor") - public SpiralTask(FLocation fLocation, int radius) - { - // limit is determined based on spiral leg length for given radius; see insideRadius() - this.limit = (radius - 1) * 2; + @SuppressWarnings("LeakingThisInConstructor") + public SpiralTask(FLocation fLocation, int radius) { + // limit is determined based on spiral leg length for given radius; see insideRadius() + this.limit = (radius - 1) * 2; - this.world = Bukkit.getWorld(fLocation.getWorldName()); - if (this.world == null) - { - P.p.log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); - this.stop(); - return; - } + this.world = Bukkit.getWorld(fLocation.getWorldName()); + if (this.world == null) { + P.p.log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); + this.stop(); + return; + } - this.x = (int)fLocation.getX(); - this.z = (int)fLocation.getZ(); + this.x = (int) fLocation.getX(); + this.z = (int) fLocation.getZ(); - this.readyToGo = true; + this.readyToGo = true; - // get this party started - this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(P.p, this, 2, 2)); - } + // get this party started + this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(P.p, this, 2, 2)); + } -/* - * This is where the necessary work is done; you'll need to override this method with whatever you want - * done at each chunk in the spiral pattern. - * Return false if the entire task needs to be aborted, otherwise return true to continue. - */ - public abstract boolean work(); + /* + * This is where the necessary work is done; you'll need to override this method with whatever you want + * done at each chunk in the spiral pattern. + * Return false if the entire task needs to be aborted, otherwise return true to continue. + */ + public abstract boolean work(); -/* - * Returns an FLocation pointing at the current chunk X and Z values. - */ - public final FLocation currentFLocation() - { - return new FLocation(world.getName(), x, z); - } -/* - * Returns a Location pointing at the current chunk X and Z values. - * note that the Location is at the corner of the chunk, not the center. - */ - public final Location currentLocation() - { - return new Location(world, FLocation.chunkToBlock(x), 65.0, FLocation.chunkToBlock(z)); - } -/* - * Returns current chunk X and Z values. - */ - public final int getX() - { - return x; - } - public final int getZ() - { - return z; - } + /* + * Returns an FLocation pointing at the current chunk X and Z values. + */ + public final FLocation currentFLocation() { + return new FLocation(world.getName(), x, z); + } + + /* + * Returns a Location pointing at the current chunk X and Z values. + * note that the Location is at the corner of the chunk, not the center. + */ + public final Location currentLocation() { + return new Location(world, FLocation.chunkToBlock(x), 65.0, FLocation.chunkToBlock(z)); + } + + /* + * Returns current chunk X and Z values. + */ + public final int getX() { + return x; + } + + public final int getZ() { + return z; + } @@ -102,112 +97,98 @@ public abstract class SpiralTask implements Runnable * Below are the guts of the class, which you normally wouldn't need to mess with. */ - public final void setTaskID(int ID) - { - if (ID == -1) - this.stop(); - taskID = ID; - } + public final void setTaskID(int ID) { + if (ID == -1) + this.stop(); + taskID = ID; + } - public final void run() - { - if (!this.valid() || !readyToGo) return; + public final void run() { + if (!this.valid() || !readyToGo) return; - // this is set so it only does one iteration at a time, no matter how frequently the timer fires - readyToGo = false; + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; - // make sure we're still inside the specified radius - if ( ! this.insideRadius()) return; + // make sure we're still inside the specified radius + if (!this.insideRadius()) return; - // track this to keep one iteration from dragging on too long and possibly choking the system - long loopStartTime = now(); + // track this to keep one iteration from dragging on too long and possibly choking the system + long loopStartTime = now(); - // keep going until the task has been running for 20ms or more, then stop to take a breather - while (now() < loopStartTime + 20) - { - // run the primary task on the current X/Z coordinates - if ( ! this.work()) - { - this.finish(); - return; - } + // keep going until the task has been running for 20ms or more, then stop to take a breather + while (now() < loopStartTime + 20) { + // run the primary task on the current X/Z coordinates + if (!this.work()) { + this.finish(); + return; + } - // move on to next chunk in spiral - if ( ! this.moveToNext()) - return; - } + // move on to next chunk in spiral + if (!this.moveToNext()) + return; + } - // ready for the next iteration to run - readyToGo = true; - } + // ready for the next iteration to run + readyToGo = true; + } - // step through chunks in spiral pattern from center; returns false if we're done, otherwise returns true - public final boolean moveToNext() - { - if ( ! this.valid()) return false; + // step through chunks in spiral pattern from center; returns false if we're done, otherwise returns true + public final boolean moveToNext() { + if (!this.valid()) return false; - // make sure we don't need to turn down the next leg of the spiral - if (current < length) - { - current++; + // make sure we don't need to turn down the next leg of the spiral + if (current < length) { + current++; - // if we're outside the radius, we're done - if ( ! this.insideRadius()) return false; - } - else - { // one leg/side of the spiral down... - current = 0; - isZLeg ^= true; - // every second leg (between X and Z legs, negative or positive), length increases - if (isZLeg) - { - isNeg ^= true; - length++; - } - } + // if we're outside the radius, we're done + if (!this.insideRadius()) return false; + } else { // one leg/side of the spiral down... + current = 0; + isZLeg ^= true; + // every second leg (between X and Z legs, negative or positive), length increases + if (isZLeg) { + isNeg ^= true; + length++; + } + } - // move one chunk further in the appropriate direction - if (isZLeg) - z += (isNeg) ? -1 : 1; - else - x += (isNeg) ? -1 : 1; + // move one chunk further in the appropriate direction + if (isZLeg) + z += (isNeg) ? -1 : 1; + else + x += (isNeg) ? -1 : 1; - return true; - } + return true; + } - public final boolean insideRadius() - { - boolean inside = current < limit; - if (!inside) - this.finish(); - return inside; - } + public final boolean insideRadius() { + boolean inside = current < limit; + if (!inside) + this.finish(); + return inside; + } - // for successful completion - public void finish() - { + // for successful completion + public void finish() { // P.p.log("SpiralTask successfully completed!"); - this.stop(); - } + this.stop(); + } - // we're done, whether finished or cancelled - public final void stop() - { - if (!this.valid()) return; + // we're done, whether finished or cancelled + public final void stop() { + if (!this.valid()) return; - readyToGo = false; - Bukkit.getServer().getScheduler().cancelTask(taskID); - taskID = -1; - } + readyToGo = false; + Bukkit.getServer().getScheduler().cancelTask(taskID); + taskID = -1; + } - // is this task still valid/workable? - public final boolean valid() - { - return taskID != -1; - } + // is this task still valid/workable? + public final boolean valid() { + return taskID != -1; + } - private static long now() - { - return System.currentTimeMillis(); - } + private static long now() { + return System.currentTimeMillis(); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java b/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java index f63964be..87d78688 100644 --- a/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java +++ b/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java @@ -1,9 +1,8 @@ package com.massivecraft.factions.zcore; -public enum CommandVisibility -{ - VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type. - SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands. - INVISIBLE, // Invisible commands are invisible to everyone, even those who can use the command. - ; +public enum CommandVisibility { + VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type. + SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands. + INVISIBLE, // Invisible commands are invisible to everyone, even those who can use the command. + ; } diff --git a/src/main/java/com/massivecraft/factions/zcore/Lang.java b/src/main/java/com/massivecraft/factions/zcore/Lang.java index 5605f9ce..7f946461 100644 --- a/src/main/java/com/massivecraft/factions/zcore/Lang.java +++ b/src/main/java/com/massivecraft/factions/zcore/Lang.java @@ -1,11 +1,10 @@ package com.massivecraft.factions.zcore; -public class Lang -{ - public static final String permForbidden = "You don't have permission to %s."; - public static final String permDoThat = "do that"; - - public static final String commandSenderMustBePlayer = "This command can only be used by ingame players."; - public static final String commandToFewArgs = "Too few arguments. Use like this:"; - public static final String commandToManyArgs = "Strange argument \"

%s\". Use the command like this:"; +public class Lang { + public static final String permForbidden = "You don't have permission to %s."; + public static final String permDoThat = "do that"; + + public static final String commandSenderMustBePlayer = "This command can only be used by ingame players."; + public static final String commandToFewArgs = "Too few arguments. Use like this:"; + public static final String commandToManyArgs = "Strange argument \"

%s\". Use the command like this:"; } diff --git a/src/main/java/com/massivecraft/factions/zcore/MCommand.java b/src/main/java/com/massivecraft/factions/zcore/MCommand.java index 905b936d..93dad59f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MCommand.java +++ b/src/main/java/com/massivecraft/factions/zcore/MCommand.java @@ -1,471 +1,409 @@ package com.massivecraft.factions.zcore; -import java.util.*; -import java.util.Map.Entry; - +import com.massivecraft.factions.zcore.util.TextUtil; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import com.massivecraft.factions.zcore.MCommand; -import com.massivecraft.factions.zcore.MPlugin; -import com.massivecraft.factions.zcore.util.TextUtil; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map.Entry; -public abstract class MCommand -{ - public T p; - - // The sub-commands to this command - public List> subCommands; - public void addSubCommand(MCommand subCommand) - { - subCommand.commandChain.addAll(this.commandChain); - subCommand.commandChain.add(this); - this.subCommands.add(subCommand); - } - - // The different names this commands will react to - public List aliases; - public boolean allowNoSlashAccess; - - // Information on the args - public List requiredArgs; - public LinkedHashMap optionalArgs; - public boolean errorOnToManyArgs = true; - - // FIELD: Help Short - // This field may be left blank and will in such case be loaded from the permissions node instead. - // Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff". - private String helpShort; - public void setHelpShort(String val) { this.helpShort = val; } - public String getHelpShort() - { - if (this.helpShort == null) - { - String pdesc = p.perm.getPermissionDescription(this.permission); - if (pdesc != null) - { - return pdesc; - } - return "*info unavailable*"; - } - return this.helpShort; - } - - public List helpLong; - public CommandVisibility visibility; - - // Some information on permissions - public boolean senderMustBePlayer; - public String permission; - - // Information available on execution of the command - public CommandSender sender; // Will always be set - public Player me; // Will only be set when the sender is a player - public boolean senderIsConsole; - public List args; // Will contain the arguments, or and empty list if there are none. - public List> commandChain = new ArrayList>(); // The command chain used to execute this command - - public MCommand(T p) - { - this.p = p; - - this.permission = null; - - this.allowNoSlashAccess = false; - - this.subCommands = new ArrayList>(); - this.aliases = new ArrayList(); - - this.requiredArgs = new ArrayList(); - this.optionalArgs = new LinkedHashMap(); - - this.helpShort = null; - this.helpLong = new ArrayList(); - this.visibility = CommandVisibility.VISIBLE; - } - - // The commandChain is a list of the parent command chain used to get to this command. - public void execute(CommandSender sender, List args, List> commandChain) - { - // Set the execution-time specific variables - this.sender = sender; - if (sender instanceof Player) - { - this.me = (Player)sender; - this.senderIsConsole = false; - } - else - { - this.me = null; - this.senderIsConsole = true; - } - this.args = args; - this.commandChain = commandChain; +public abstract class MCommand { + public T p; - // Is there a matching sub command? - if (args.size() > 0 ) - { - for (MCommand subCommand: this.subCommands) - { - if (subCommand.aliases.contains(args.get(0))) - { - args.remove(0); - commandChain.add(this); - subCommand.execute(sender, args, commandChain); - return; - } - } - } - - if ( ! validCall(this.sender, this.args)) return; - - if ( ! this.isEnabled()) return; - - perform(); - } - - public void execute(CommandSender sender, List args) - { - execute(sender, args, new ArrayList>()); - } - - // This is where the command action is performed. - public abstract void perform(); - - - // -------------------------------------------- // - // Call Validation - // -------------------------------------------- // - - /** - * In this method we validate that all prerequisites to perform this command has been met. - */ - // TODO: There should be a boolean for silence - public boolean validCall(CommandSender sender, List args) - { - if ( ! validSenderType(sender, true)) - { - return false; - } - - if ( ! validSenderPermissions(sender, true)) - { - return false; - } - - if ( ! validArgs(args, sender)) - { - return false; - } - - return true; - } - - public boolean isEnabled() - { - return true; - } - - public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) - { - if (this.senderMustBePlayer && ! (sender instanceof Player)) - { - if (informSenderIfNot) - { - msg(Lang.commandSenderMustBePlayer); - } - return false; - } - return true; - } - - public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) - { - if (this.permission == null) return true; - return p.perm.has(sender, this.permission, informSenderIfNot); - } - - public boolean validArgs(List args, CommandSender sender) - { - if (args.size() < this.requiredArgs.size()) - { - if (sender != null) - { - msg(Lang.commandToFewArgs); - sender.sendMessage(this.getUseageTemplate()); - } - return false; - } - - if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs) - { - if (sender != null) - { - // Get the to many string slice - List theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); - msg(Lang.commandToManyArgs, TextUtil.implode(theToMany, " ")); - sender.sendMessage(this.getUseageTemplate()); - } - return false; - } - return true; - } - public boolean validArgs(List args) - { - return this.validArgs(args, null); - } - - // -------------------------------------------- // - // Help and Usage information - // -------------------------------------------- // - - public String getUseageTemplate(List> commandChain, boolean addShortHelp) - { - StringBuilder ret = new StringBuilder(); - ret.append(p.txt.parseTags("")); - ret.append('/'); - - for (MCommand mc : commandChain) - { - ret.append(TextUtil.implode(mc.aliases, ",")); - ret.append(' '); - } - - ret.append(TextUtil.implode(this.aliases, ",")); - - List args = new ArrayList(); - - for (String requiredArg : this.requiredArgs) - { - args.add("<"+requiredArg+">"); - } - - for (Entry optionalArg : this.optionalArgs.entrySet()) - { - String val = optionalArg.getValue(); - if (val == null) - { - val = ""; - } - else - { - val = "="+val; - } - args.add("["+optionalArg.getKey()+val+"]"); - } - - if (args.size() > 0) - { - ret.append(p.txt.parseTags("

")); - ret.append(TextUtil.implode(args, " ")); - } - - if (addShortHelp) - { - ret.append(p.txt.parseTags(" ")); - ret.append(this.getHelpShort()); - } - - return ret.toString(); - } - - public String getUseageTemplate(boolean addShortHelp) - { - return getUseageTemplate(this.commandChain, addShortHelp); - } - - public String getUseageTemplate() - { - return getUseageTemplate(false); - } - - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // - - public void msg(String str, Object... args) - { - sender.sendMessage(p.txt.parse(str, args)); - } - - public void sendMessage(String msg) - { - sender.sendMessage(msg); - } - - public void sendMessage(List msgs) - { - for(String msg : msgs) - { - this.sendMessage(msg); - } - } - - // -------------------------------------------- // - // Argument Readers - // -------------------------------------------- // - - // Is set? ====================== - public boolean argIsSet(int idx) - { - if (this.args.size() < idx+1) - { - return false; - } - return true; - } - - // STRING ====================== - public String argAsString(int idx, String def) - { - if (this.args.size() < idx+1) - { - return def; - } - return this.args.get(idx); - } - public String argAsString(int idx) - { - return this.argAsString(idx, null); - } - - // INT ====================== - public Integer strAsInt(String str, Integer def) - { - if (str == null) return def; - try - { - Integer ret = Integer.parseInt(str); - return ret; - } - catch (Exception e) - { - return def; - } - } - public Integer argAsInt(int idx, Integer def) - { - return strAsInt(this.argAsString(idx), def); - } - public Integer argAsInt(int idx) - { - return this.argAsInt(idx, null); - } - - // Double ====================== - public Double strAsDouble(String str, Double def) - { - if (str == null) return def; - try - { - Double ret = Double.parseDouble(str); - return ret; - } - catch (Exception e) - { - return def; - } - } - public Double argAsDouble(int idx, Double def) - { - return strAsDouble(this.argAsString(idx), def); - } - public Double argAsDouble(int idx) - { - return this.argAsDouble(idx, null); - } - - // TODO: Go through the str conversion for the other arg-readers as well. - // Boolean ====================== - public Boolean strAsBool(String str) - { - str = str.toLowerCase(); - if (str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1")) - { - return true; - } - return false; - } - public Boolean argAsBool(int idx, boolean def) - { - String str = this.argAsString(idx); - if (str == null) return def; - - return strAsBool(str); - } - public Boolean argAsBool(int idx) - { - return this.argAsBool(idx, false); - } - - // PLAYER ====================== - public Player strAsPlayer(String name, Player def, boolean msg) - { - Player ret = def; - - if (name != null) - { - Player player = Bukkit.getServer().getPlayer(name); - if (player != null) - { - ret = player; - } - } - - if (msg && ret == null) - { - this.msg("No player \"

%s\" could not be found.", name); - } - - return ret; - } - - public Player argAsPlayer(int idx, Player def, boolean msg) - { - return this.strAsPlayer(this.argAsString(idx), def, msg); - } - public Player argAsPlayer(int idx, Player def) - { - return this.argAsPlayer(idx, def, true); - } - public Player argAsPlayer(int idx) - { - return this.argAsPlayer(idx, null); - } - - // BEST PLAYER MATCH ====================== - public Player strAsBestPlayerMatch(String name, Player def, boolean msg) - { - Player ret = def; - - if (name != null) - { - List players = Bukkit.getServer().matchPlayer(name); - if (players.size() > 0) - { - ret = players.get(0); - } - } - - if (msg && ret == null) - { - this.msg("No player match found for \"

%s\".", name); - } - - return ret; - } - public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) - { - return this.strAsBestPlayerMatch(this.argAsString(idx), def, msg); - } - public Player argAsBestPlayerMatch(int idx, Player def) - { - return this.argAsBestPlayerMatch(idx, def, true); - } - public Player argAsBestPlayerMatch(int idx) - { - return this.argAsPlayer(idx, null); - } + // The sub-commands to this command + public List> subCommands; + + public void addSubCommand(MCommand subCommand) { + subCommand.commandChain.addAll(this.commandChain); + subCommand.commandChain.add(this); + this.subCommands.add(subCommand); + } + + // The different names this commands will react to + public List aliases; + public boolean allowNoSlashAccess; + + // Information on the args + public List requiredArgs; + public LinkedHashMap optionalArgs; + public boolean errorOnToManyArgs = true; + + // FIELD: Help Short + // This field may be left blank and will in such case be loaded from the permissions node instead. + // Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff". + private String helpShort; + + public void setHelpShort(String val) { + this.helpShort = val; + } + + public String getHelpShort() { + if (this.helpShort == null) { + String pdesc = p.perm.getPermissionDescription(this.permission); + if (pdesc != null) { + return pdesc; + } + return "*info unavailable*"; + } + return this.helpShort; + } + + public List helpLong; + public CommandVisibility visibility; + + // Some information on permissions + public boolean senderMustBePlayer; + public String permission; + + // Information available on execution of the command + public CommandSender sender; // Will always be set + public Player me; // Will only be set when the sender is a player + public boolean senderIsConsole; + public List args; // Will contain the arguments, or and empty list if there are none. + public List> commandChain = new ArrayList>(); // The command chain used to execute this command + + public MCommand(T p) { + this.p = p; + + this.permission = null; + + this.allowNoSlashAccess = false; + + this.subCommands = new ArrayList>(); + this.aliases = new ArrayList(); + + this.requiredArgs = new ArrayList(); + this.optionalArgs = new LinkedHashMap(); + + this.helpShort = null; + this.helpLong = new ArrayList(); + this.visibility = CommandVisibility.VISIBLE; + } + + // The commandChain is a list of the parent command chain used to get to this command. + public void execute(CommandSender sender, List args, List> commandChain) { + // Set the execution-time specific variables + this.sender = sender; + if (sender instanceof Player) { + this.me = (Player) sender; + this.senderIsConsole = false; + } else { + this.me = null; + this.senderIsConsole = true; + } + this.args = args; + this.commandChain = commandChain; + + // Is there a matching sub command? + if (args.size() > 0) { + for (MCommand subCommand : this.subCommands) { + if (subCommand.aliases.contains(args.get(0))) { + args.remove(0); + commandChain.add(this); + subCommand.execute(sender, args, commandChain); + return; + } + } + } + + if (!validCall(this.sender, this.args)) return; + + if (!this.isEnabled()) return; + + perform(); + } + + public void execute(CommandSender sender, List args) { + execute(sender, args, new ArrayList>()); + } + + // This is where the command action is performed. + public abstract void perform(); + + + // -------------------------------------------- // + // Call Validation + // -------------------------------------------- // + + /** + * In this method we validate that all prerequisites to perform this command has been met. + */ + // TODO: There should be a boolean for silence + public boolean validCall(CommandSender sender, List args) { + if (!validSenderType(sender, true)) { + return false; + } + + if (!validSenderPermissions(sender, true)) { + return false; + } + + if (!validArgs(args, sender)) { + return false; + } + + return true; + } + + public boolean isEnabled() { + return true; + } + + public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { + if (this.senderMustBePlayer && !(sender instanceof Player)) { + if (informSenderIfNot) { + msg(Lang.commandSenderMustBePlayer); + } + return false; + } + return true; + } + + public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) { + if (this.permission == null) return true; + return p.perm.has(sender, this.permission, informSenderIfNot); + } + + public boolean validArgs(List args, CommandSender sender) { + if (args.size() < this.requiredArgs.size()) { + if (sender != null) { + msg(Lang.commandToFewArgs); + sender.sendMessage(this.getUseageTemplate()); + } + return false; + } + + if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs) { + if (sender != null) { + // Get the to many string slice + List theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); + msg(Lang.commandToManyArgs, TextUtil.implode(theToMany, " ")); + sender.sendMessage(this.getUseageTemplate()); + } + return false; + } + return true; + } + + public boolean validArgs(List args) { + return this.validArgs(args, null); + } + + // -------------------------------------------- // + // Help and Usage information + // -------------------------------------------- // + + public String getUseageTemplate(List> commandChain, boolean addShortHelp) { + StringBuilder ret = new StringBuilder(); + ret.append(p.txt.parseTags("")); + ret.append('/'); + + for (MCommand mc : commandChain) { + ret.append(TextUtil.implode(mc.aliases, ",")); + ret.append(' '); + } + + ret.append(TextUtil.implode(this.aliases, ",")); + + List args = new ArrayList(); + + for (String requiredArg : this.requiredArgs) { + args.add("<" + requiredArg + ">"); + } + + for (Entry optionalArg : this.optionalArgs.entrySet()) { + String val = optionalArg.getValue(); + if (val == null) { + val = ""; + } else { + val = "=" + val; + } + args.add("[" + optionalArg.getKey() + val + "]"); + } + + if (args.size() > 0) { + ret.append(p.txt.parseTags("

")); + ret.append(TextUtil.implode(args, " ")); + } + + if (addShortHelp) { + ret.append(p.txt.parseTags(" ")); + ret.append(this.getHelpShort()); + } + + return ret.toString(); + } + + public String getUseageTemplate(boolean addShortHelp) { + return getUseageTemplate(this.commandChain, addShortHelp); + } + + public String getUseageTemplate() { + return getUseageTemplate(false); + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public void msg(String str, Object... args) { + sender.sendMessage(p.txt.parse(str, args)); + } + + public void sendMessage(String msg) { + sender.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // + + // Is set? ====================== + public boolean argIsSet(int idx) { + if (this.args.size() < idx + 1) { + return false; + } + return true; + } + + // STRING ====================== + public String argAsString(int idx, String def) { + if (this.args.size() < idx + 1) { + return def; + } + return this.args.get(idx); + } + + public String argAsString(int idx) { + return this.argAsString(idx, null); + } + + // INT ====================== + public Integer strAsInt(String str, Integer def) { + if (str == null) return def; + try { + Integer ret = Integer.parseInt(str); + return ret; + } catch (Exception e) { + return def; + } + } + + public Integer argAsInt(int idx, Integer def) { + return strAsInt(this.argAsString(idx), def); + } + + public Integer argAsInt(int idx) { + return this.argAsInt(idx, null); + } + + // Double ====================== + public Double strAsDouble(String str, Double def) { + if (str == null) return def; + try { + Double ret = Double.parseDouble(str); + return ret; + } catch (Exception e) { + return def; + } + } + + public Double argAsDouble(int idx, Double def) { + return strAsDouble(this.argAsString(idx), def); + } + + public Double argAsDouble(int idx) { + return this.argAsDouble(idx, null); + } + + // TODO: Go through the str conversion for the other arg-readers as well. + // Boolean ====================== + public Boolean strAsBool(String str) { + str = str.toLowerCase(); + if (str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1")) { + return true; + } + return false; + } + + public Boolean argAsBool(int idx, boolean def) { + String str = this.argAsString(idx); + if (str == null) return def; + + return strAsBool(str); + } + + public Boolean argAsBool(int idx) { + return this.argAsBool(idx, false); + } + + // PLAYER ====================== + public Player strAsPlayer(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + Player player = Bukkit.getServer().getPlayer(name); + if (player != null) { + ret = player; + } + } + + if (msg && ret == null) { + this.msg("No player \"

%s\" could not be found.", name); + } + + return ret; + } + + public Player argAsPlayer(int idx, Player def, boolean msg) { + return this.strAsPlayer(this.argAsString(idx), def, msg); + } + + public Player argAsPlayer(int idx, Player def) { + return this.argAsPlayer(idx, def, true); + } + + public Player argAsPlayer(int idx) { + return this.argAsPlayer(idx, null); + } + + // BEST PLAYER MATCH ====================== + public Player strAsBestPlayerMatch(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + List players = Bukkit.getServer().matchPlayer(name); + if (players.size() > 0) { + ret = players.get(0); + } + } + + if (msg && ret == null) { + this.msg("No player match found for \"

%s\".", name); + } + + return ret; + } + + public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { + return this.strAsBestPlayerMatch(this.argAsString(idx), def, msg); + } + + public Player argAsBestPlayerMatch(int idx, Player def) { + return this.argAsBestPlayerMatch(idx, def, true); + } + + public Player argAsBestPlayerMatch(int idx) { + return this.argAsPlayer(idx, null); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java index fa685c6a..256299b0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java @@ -1,280 +1,260 @@ package com.massivecraft.factions.zcore; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.zcore.persist.EM; +import com.massivecraft.factions.zcore.persist.SaveTask; +import com.massivecraft.factions.zcore.util.LibLoader; +import com.massivecraft.factions.zcore.util.PermUtil; +import com.massivecraft.factions.zcore.util.Persist; +import com.massivecraft.factions.zcore.util.TextUtil; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.libs.com.google.gson.Gson; +import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder; +import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; +import org.bukkit.plugin.java.JavaPlugin; + import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.craftbukkit.libs.com.google.gson.Gson; -import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder; -import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken; -import com.massivecraft.factions.zcore.persist.EM; -import com.massivecraft.factions.zcore.persist.SaveTask; -import com.massivecraft.factions.zcore.util.LibLoader; -import com.massivecraft.factions.zcore.util.PermUtil; -import com.massivecraft.factions.zcore.util.Persist; -import com.massivecraft.factions.zcore.util.TextUtil; +public abstract class MPlugin extends JavaPlugin { + // Some utils + public Persist persist; + public TextUtil txt; + public LibLoader lib; + public PermUtil perm; -import com.massivecraft.factions.Conf; + // Persist related + public Gson gson; + private Integer saveTask = null; + private boolean autoSave = true; + protected boolean loadSuccessful = false; + public boolean getAutoSave() { + return this.autoSave; + } -public abstract class MPlugin extends JavaPlugin -{ - // Some utils - public Persist persist; - public TextUtil txt; - public LibLoader lib; - public PermUtil perm; - - // Persist related - public Gson gson; - private Integer saveTask = null; - private boolean autoSave = true; - protected boolean loadSuccessful = false; - public boolean getAutoSave() {return this.autoSave;} - public void setAutoSave(boolean val) {this.autoSave = val;} - public String refCommand = ""; - - // Listeners - private MPluginSecretPlayerListener mPluginSecretPlayerListener; - private MPluginSecretServerListener mPluginSecretServerListener; - - // Our stored base commands - private List> baseCommands = new ArrayList>(); - public List> getBaseCommands() { return this.baseCommands; } + public void setAutoSave(boolean val) { + this.autoSave = val; + } - // -------------------------------------------- // - // ENABLE - // -------------------------------------------- // - private long timeEnableStart; - public boolean preEnable() - { - log("=== ENABLE START ==="); - timeEnableStart = System.currentTimeMillis(); - - // Ensure basefolder exists! - this.getDataFolder().mkdirs(); - - // Create Utility Instances - this.perm = new PermUtil(this); - this.persist = new Persist(this); - this.lib = new LibLoader(this); + public String refCommand = ""; - // GSON 2.1 is now embedded in CraftBukkit, used by the auto-updater: https://github.com/Bukkit/CraftBukkit/commit/0ed1d1fdbb1e0bc09a70bc7bfdf40c1de8411665 + // Listeners + private MPluginSecretPlayerListener mPluginSecretPlayerListener; + private MPluginSecretServerListener mPluginSecretServerListener; + + // Our stored base commands + private List> baseCommands = new ArrayList>(); + + public List> getBaseCommands() { + return this.baseCommands; + } + + // -------------------------------------------- // + // ENABLE + // -------------------------------------------- // + private long timeEnableStart; + + public boolean preEnable() { + log("=== ENABLE START ==="); + timeEnableStart = System.currentTimeMillis(); + + // Ensure basefolder exists! + this.getDataFolder().mkdirs(); + + // Create Utility Instances + this.perm = new PermUtil(this); + this.persist = new Persist(this); + this.lib = new LibLoader(this); + + // GSON 2.1 is now embedded in CraftBukkit, used by the auto-updater: https://github.com/Bukkit/CraftBukkit/commit/0ed1d1fdbb1e0bc09a70bc7bfdf40c1de8411665 // if ( ! lib.require("gson.jar", "http://search.maven.org/remotecontent?filepath=com/google/code/gson/gson/2.1/gson-2.1.jar")) return false; - this.gson = this.getGsonBuilder().create(); - - this.txt = new TextUtil(); - initTXT(); + this.gson = this.getGsonBuilder().create(); - // attempt to get first command defined in plugin.yml as reference command, if any commands are defined in there - // reference command will be used to prevent "unknown command" console messages - try - { - Map> refCmd = this.getDescription().getCommands(); - if (refCmd != null && !refCmd.isEmpty()) - this.refCommand = (String)(refCmd.keySet().toArray()[0]); - } - catch (ClassCastException ex) {} + this.txt = new TextUtil(); + initTXT(); - // Create and register listeners - this.mPluginSecretPlayerListener = new MPluginSecretPlayerListener(this); - this.mPluginSecretServerListener = new MPluginSecretServerListener(this); - getServer().getPluginManager().registerEvents(this.mPluginSecretPlayerListener, this); - getServer().getPluginManager().registerEvents(this.mPluginSecretServerListener, this); - - - // Register recurring tasks - if (saveTask == null && Conf.saveToFileEveryXMinutes > 0.0) - { - long saveTicks = (long)(20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default - saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); - } + // attempt to get first command defined in plugin.yml as reference command, if any commands are defined in there + // reference command will be used to prevent "unknown command" console messages + try { + Map> refCmd = this.getDescription().getCommands(); + if (refCmd != null && !refCmd.isEmpty()) + this.refCommand = (String) (refCmd.keySet().toArray()[0]); + } catch (ClassCastException ex) { + } - loadSuccessful = true; - return true; - } - - public void postEnable() - { - log("=== ENABLE DONE (Took "+(System.currentTimeMillis()-timeEnableStart)+"ms) ==="); - } - - public void onDisable() - { - if (saveTask != null) - { - this.getServer().getScheduler().cancelTask(saveTask); - saveTask = null; - } - // only save data if plugin actually loaded successfully - if (loadSuccessful) - EM.saveAllToDisc(); - log("Disabled"); - } - - public void suicide() - { - log("Now I suicide!"); - this.getServer().getPluginManager().disablePlugin(this); - } + // Create and register listeners + this.mPluginSecretPlayerListener = new MPluginSecretPlayerListener(this); + this.mPluginSecretServerListener = new MPluginSecretServerListener(this); + getServer().getPluginManager().registerEvents(this.mPluginSecretPlayerListener, this); + getServer().getPluginManager().registerEvents(this.mPluginSecretServerListener, this); - // -------------------------------------------- // - // Some inits... - // You are supposed to override these in the plugin if you aren't satisfied with the defaults - // The goal is that you always will be satisfied though. - // -------------------------------------------- // - public GsonBuilder getGsonBuilder() - { - return new GsonBuilder() - .setPrettyPrinting() - .disableHtmlEscaping() - .serializeNulls() - .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); - } - - // -------------------------------------------- // - // LANG AND TAGS - // -------------------------------------------- // - - // These are not supposed to be used directly. - // They are loaded and used through the TextUtil instance for the plugin. - public Map rawTags = new LinkedHashMap(); - - public void addRawTags() - { - this.rawTags.put("l", ""); // logo - this.rawTags.put("a", ""); // art - this.rawTags.put("n", ""); // notice - this.rawTags.put("i", ""); // info - this.rawTags.put("g", ""); // good - this.rawTags.put("b", ""); // bad - this.rawTags.put("h", ""); // highligh - this.rawTags.put("c", ""); // command - this.rawTags.put("p", ""); // parameter - } - - public void initTXT() - { - this.addRawTags(); - - Type type = new TypeToken>(){}.getType(); - - Map tagsFromFile = this.persist.load(type, "tags"); - if (tagsFromFile != null) this.rawTags.putAll(tagsFromFile); - this.persist.save(this.rawTags, "tags"); - - for (Entry rawTag : this.rawTags.entrySet()) - { - this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); - } - } - - // -------------------------------------------- // - // COMMAND HANDLING - // -------------------------------------------- // + // Register recurring tasks + if (saveTask == null && Conf.saveToFileEveryXMinutes > 0.0) { + long saveTicks = (long) (20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default + saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); + } - // can be overridden by P method, to provide option - public boolean logPlayerCommands() - { - return true; - } + loadSuccessful = true; + return true; + } - public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) - { - return handleCommand(sender, commandString, testOnly, false); - } + public void postEnable() { + log("=== ENABLE DONE (Took " + (System.currentTimeMillis() - timeEnableStart) + "ms) ==="); + } - public boolean handleCommand(final CommandSender sender, String commandString, boolean testOnly, boolean async) - { - boolean noSlash = true; - if (commandString.startsWith("/")) - { - noSlash = false; - commandString = commandString.substring(1); - } - - for (final MCommand command : this.getBaseCommands()) - { - if (noSlash && ! command.allowNoSlashAccess) continue; - - for (String alias : command.aliases) - { - // disallow double-space after alias, so specific commands can be prevented (preventing "f home" won't prevent "f home") - if (commandString.startsWith(alias+" ")) return false; + public void onDisable() { + if (saveTask != null) { + this.getServer().getScheduler().cancelTask(saveTask); + saveTask = null; + } + // only save data if plugin actually loaded successfully + if (loadSuccessful) + EM.saveAllToDisc(); + log("Disabled"); + } - if (commandString.startsWith(alias+" ") || commandString.equals(alias)) - { - final List args = new ArrayList(Arrays.asList(commandString.split("\\s+"))); - args.remove(0); + public void suicide() { + log("Now I suicide!"); + this.getServer().getPluginManager().disablePlugin(this); + } - if (testOnly) return true; + // -------------------------------------------- // + // Some inits... + // You are supposed to override these in the plugin if you aren't satisfied with the defaults + // The goal is that you always will be satisfied though. + // -------------------------------------------- // - if (async) - { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - @Override - public void run() - { - command.execute(sender, args); - } - }); - } - else - command.execute(sender, args); + public GsonBuilder getGsonBuilder() { + return new GsonBuilder() + .setPrettyPrinting() + .disableHtmlEscaping() + .serializeNulls() + .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); + } - return true; - } - } - } - return false; - } - - public boolean handleCommand(CommandSender sender, String commandString) - { - return this.handleCommand(sender, commandString, false); - } - - // -------------------------------------------- // - // HOOKS - // -------------------------------------------- // - public void preAutoSave() - { - - } - - public void postAutoSave() - { - - } - - // -------------------------------------------- // - // LOGGING - // -------------------------------------------- // - public void log(Object msg) - { - log(Level.INFO, msg); - } + // -------------------------------------------- // + // LANG AND TAGS + // -------------------------------------------- // - public void log(String str, Object... args) - { - log(Level.INFO, this.txt.parse(str, args)); - } + // These are not supposed to be used directly. + // They are loaded and used through the TextUtil instance for the plugin. + public Map rawTags = new LinkedHashMap(); - public void log(Level level, String str, Object... args) - { - log(level, this.txt.parse(str, args)); - } + public void addRawTags() { + this.rawTags.put("l", ""); // logo + this.rawTags.put("a", ""); // art + this.rawTags.put("n", ""); // notice + this.rawTags.put("i", ""); // info + this.rawTags.put("g", ""); // good + this.rawTags.put("b", ""); // bad + this.rawTags.put("h", ""); // highligh + this.rawTags.put("c", ""); // command + this.rawTags.put("p", ""); // parameter + } - public void log(Level level, Object msg) - { - Bukkit.getLogger().log(level, "["+this.getDescription().getFullName()+"] "+msg); - } + public void initTXT() { + this.addRawTags(); + + Type type = new TypeToken>() { + }.getType(); + + Map tagsFromFile = this.persist.load(type, "tags"); + if (tagsFromFile != null) this.rawTags.putAll(tagsFromFile); + this.persist.save(this.rawTags, "tags"); + + for (Entry rawTag : this.rawTags.entrySet()) { + this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); + } + } + + // -------------------------------------------- // + // COMMAND HANDLING + // -------------------------------------------- // + + // can be overridden by P method, to provide option + public boolean logPlayerCommands() { + return true; + } + + public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { + return handleCommand(sender, commandString, testOnly, false); + } + + public boolean handleCommand(final CommandSender sender, String commandString, boolean testOnly, boolean async) { + boolean noSlash = true; + if (commandString.startsWith("/")) { + noSlash = false; + commandString = commandString.substring(1); + } + + for (final MCommand command : this.getBaseCommands()) { + if (noSlash && !command.allowNoSlashAccess) continue; + + for (String alias : command.aliases) { + // disallow double-space after alias, so specific commands can be prevented (preventing "f home" won't prevent "f home") + if (commandString.startsWith(alias + " ")) return false; + + if (commandString.startsWith(alias + " ") || commandString.equals(alias)) { + final List args = new ArrayList(Arrays.asList(commandString.split("\\s+"))); + args.remove(0); + + if (testOnly) return true; + + if (async) { + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + @Override + public void run() { + command.execute(sender, args); + } + }); + } else + command.execute(sender, args); + + return true; + } + } + } + return false; + } + + public boolean handleCommand(CommandSender sender, String commandString) { + return this.handleCommand(sender, commandString, false); + } + + // -------------------------------------------- // + // HOOKS + // -------------------------------------------- // + public void preAutoSave() { + + } + + public void postAutoSave() { + + } + + // -------------------------------------------- // + // LOGGING + // -------------------------------------------- // + public void log(Object msg) { + log(Level.INFO, msg); + } + + public void log(String str, Object... args) { + log(Level.INFO, this.txt.parse(str, args)); + } + + public void log(Level level, String str, Object... args) { + log(level, this.txt.parse(str, args)); + } + + public void log(Level level, Object msg) { + Bukkit.getLogger().log(level, "[" + this.getDescription().getFullName() + "] " + msg); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java index c3acf52b..7863b6ac 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java @@ -1,5 +1,9 @@ package com.massivecraft.factions.zcore; +import com.massivecraft.factions.zcore.persist.EM; +import com.massivecraft.factions.zcore.persist.Entity; +import com.massivecraft.factions.zcore.persist.EntityCollection; +import com.massivecraft.factions.zcore.persist.PlayerEntityCollection; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -8,54 +12,41 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerLoginEvent; -import com.massivecraft.factions.zcore.persist.EM; -import com.massivecraft.factions.zcore.persist.Entity; -import com.massivecraft.factions.zcore.persist.EntityCollection; -import com.massivecraft.factions.zcore.persist.PlayerEntityCollection; +public class MPluginSecretPlayerListener implements Listener { + private MPlugin p; -public class MPluginSecretPlayerListener implements Listener -{ - private MPlugin p; - public MPluginSecretPlayerListener(MPlugin p) - { - this.p = p; - } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) - { - if (event.isCancelled()) return; + public MPluginSecretPlayerListener(MPlugin p) { + this.p = p; + } - if (p.handleCommand(event.getPlayer(), event.getMessage())) - { - if (p.logPlayerCommands()) - Bukkit.getLogger().info("[PLAYER_COMMAND] "+event.getPlayer().getName()+": "+event.getMessage()); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerChat(AsyncPlayerChatEvent event) - { - if (event.isCancelled()) return; - - if (p.handleCommand(event.getPlayer(), event.getMessage(), false, true)) - { - if (p.logPlayerCommands()) - Bukkit.getLogger().info("[PLAYER_COMMAND] "+event.getPlayer().getName()+": "+event.getMessage()); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerPreLogin(PlayerLoginEvent event) - { - for (EntityCollection ecoll : EM.class2Entities.values()) - { - if (ecoll instanceof PlayerEntityCollection) - { - ecoll.get(event.getPlayer().getName()); - } - } - } + @EventHandler(priority = EventPriority.LOW) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + if (event.isCancelled()) return; + + if (p.handleCommand(event.getPlayer(), event.getMessage())) { + if (p.logPlayerCommands()) + Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerChat(AsyncPlayerChatEvent event) { + if (event.isCancelled()) return; + + if (p.handleCommand(event.getPlayer(), event.getMessage(), false, true)) { + if (p.logPlayerCommands()) + Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerPreLogin(PlayerLoginEvent event) { + for (EntityCollection ecoll : EM.class2Entities.values()) { + if (ecoll instanceof PlayerEntityCollection) { + ecoll.get(event.getPlayer().getName()); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretServerListener.java b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretServerListener.java index 004b85da..ee43b002 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretServerListener.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretServerListener.java @@ -5,24 +5,20 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.server.ServerCommandEvent; -public class MPluginSecretServerListener implements Listener -{ - private MPlugin p; +public class MPluginSecretServerListener implements Listener { + private MPlugin p; + + public MPluginSecretServerListener(MPlugin p) { + this.p = p; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onServerCommand(ServerCommandEvent event) { + if (event.getCommand().length() == 0) return; + + if (p.handleCommand(event.getSender(), event.getCommand())) { + event.setCommand(p.refCommand); + } + } - public MPluginSecretServerListener(MPlugin p) - { - this.p = p; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onServerCommand(ServerCommandEvent event) - { - if (event.getCommand().length() == 0) return; - - if (p.handleCommand(event.getSender(), event.getCommand())) - { - event.setCommand(p.refCommand); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/EM.java b/src/main/java/com/massivecraft/factions/zcore/persist/EM.java index fada416b..6f10687a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/EM.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/EM.java @@ -1,74 +1,61 @@ package com.massivecraft.factions.zcore.persist; -import java.util.*; +import java.util.LinkedHashMap; +import java.util.Map; -import com.massivecraft.factions.zcore.persist.Entity; -import com.massivecraft.factions.zcore.persist.EntityCollection; +public class EM { + public static Map, EntityCollection> class2Entities = new LinkedHashMap, EntityCollection>(); -public class EM -{ - public static Map, EntityCollection> class2Entities = new LinkedHashMap, EntityCollection>(); - - @SuppressWarnings("unchecked") - public static EntityCollection getEntitiesCollectionForEntityClass(Class entityClass) - { - return (EntityCollection) class2Entities.get(entityClass); - } - - public static void setEntitiesCollectionForEntityClass(Class entityClass, EntityCollection entities) - { - class2Entities.put(entityClass, entities); - } - - // -------------------------------------------- // - // ATTACH AND DETACH - // -------------------------------------------- // - - @SuppressWarnings("unchecked") - public static void attach(T entity) - { - EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); - ec.attach(entity); - } - - @SuppressWarnings("unchecked") - public static void detach(T entity) - { - EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); - ec.detach(entity); - } - - @SuppressWarnings("unchecked") - public static boolean attached(T entity) - { - EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); - return ec.attached(entity); - } - - @SuppressWarnings("unchecked") - public static boolean detached(T entity) - { - EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); - return ec.detached(entity); - } - - // -------------------------------------------- // - // DISC - // -------------------------------------------- // - - public static void saveAllToDisc() - { - for (EntityCollection ec : class2Entities.values()) - { - ec.saveToDisc(); - } - } - - public static void loadAllFromDisc() - { - for (EntityCollection ec : class2Entities.values()) - { - ec.loadFromDisc(); - } - } + @SuppressWarnings("unchecked") + public static EntityCollection getEntitiesCollectionForEntityClass(Class entityClass) { + return (EntityCollection) class2Entities.get(entityClass); + } + + public static void setEntitiesCollectionForEntityClass(Class entityClass, EntityCollection entities) { + class2Entities.put(entityClass, entities); + } + + // -------------------------------------------- // + // ATTACH AND DETACH + // -------------------------------------------- // + + @SuppressWarnings("unchecked") + public static void attach(T entity) { + EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); + ec.attach(entity); + } + + @SuppressWarnings("unchecked") + public static void detach(T entity) { + EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); + ec.detach(entity); + } + + @SuppressWarnings("unchecked") + public static boolean attached(T entity) { + EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); + return ec.attached(entity); + } + + @SuppressWarnings("unchecked") + public static boolean detached(T entity) { + EntityCollection ec = (EntityCollection) getEntitiesCollectionForEntityClass(entity.getClass()); + return ec.detached(entity); + } + + // -------------------------------------------- // + // DISC + // -------------------------------------------- // + + public static void saveAllToDisc() { + for (EntityCollection ec : class2Entities.values()) { + ec.saveToDisc(); + } + } + + public static void loadAllFromDisc() { + for (EntityCollection ec : class2Entities.values()) { + ec.loadFromDisc(); + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/Entity.java b/src/main/java/com/massivecraft/factions/zcore/persist/Entity.java index 1b800361..7e5b1030 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/Entity.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/Entity.java @@ -1,65 +1,54 @@ package com.massivecraft.factions.zcore.persist; -public abstract class Entity -{ - public Entity() - { - - } - - protected transient String id = null; - - public String getId() - { - return id; - } - - protected void setId(String id) - { - this.id = id; - } - - public boolean shouldBeSaved() - { - return true; - } - - // -------------------------------------------- // - // ATTACH AND DETACH - // -------------------------------------------- // - - public void attach() - { - EM.attach(this); - } - - public void detach() - { - EM.detach(this); - } - - public boolean attached() - { - return EM.attached(this); - } - - public boolean detached() - { - return EM.detached(this); - } - - // -------------------------------------------- // - // EVENTS - // -------------------------------------------- // - - public void preDetach() - { - - } - - public void postDetach() - { - - } - +public abstract class Entity { + public Entity() { + + } + + protected transient String id = null; + + public String getId() { + return id; + } + + protected void setId(String id) { + this.id = id; + } + + public boolean shouldBeSaved() { + return true; + } + + // -------------------------------------------- // + // ATTACH AND DETACH + // -------------------------------------------- // + + public void attach() { + EM.attach(this); + } + + public void detach() { + EM.detach(this); + } + + public boolean attached() { + return EM.attached(this); + } + + public boolean detached() { + return EM.detached(this); + } + + // -------------------------------------------- // + // EVENTS + // -------------------------------------------- // + + public void preDetach() { + + } + + public void postDetach() { + + } + } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java b/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java index 73b8b170..46026b60 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java @@ -1,297 +1,281 @@ package com.massivecraft.factions.zcore.persist; +import com.massivecraft.factions.zcore.util.DiscUtil; +import com.massivecraft.factions.zcore.util.TextUtil; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.libs.com.google.gson.Gson; + import java.io.File; import java.lang.reflect.Type; -import java.util.*; -import java.util.logging.Level; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import java.util.Map.Entry; +import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.libs.com.google.gson.Gson; -import com.massivecraft.factions.zcore.util.DiscUtil; -import com.massivecraft.factions.zcore.util.TextUtil; +public abstract class EntityCollection { + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // -public abstract class EntityCollection -{ - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // - - // These must be instantiated in order to allow for different configuration (orders, comparators etc) - private Collection entities; - protected Map id2entity; - - // If the entities are creative they will create a new instance if a non existent id was requested - private boolean creative; - public boolean isCreative() { return creative; } - public void setCreative(boolean creative) { this.creative = creative; } + // These must be instantiated in order to allow for different configuration (orders, comparators etc) + private Collection entities; + protected Map id2entity; - // This is the auto increment for the primary key "id" - private int nextId; - - // This ugly crap is necessary due to java type erasure - private Class entityClass; - public abstract Type getMapType(); // This is special stuff for GSON. - - // Info on how to persist - private Gson gson; - public Gson getGson() { return gson; } - public void setGson(Gson gson) { this.gson = gson; } + // If the entities are creative they will create a new instance if a non existent id was requested + private boolean creative; - private File file; - public File getFile() { return file; } - public void setFile(File file) { this.file = file; } - - // -------------------------------------------- // - // CONSTRUCTORS - // -------------------------------------------- // + public boolean isCreative() { + return creative; + } - public EntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson, boolean creative) - { - this.entityClass = entityClass; - this.entities = entities; - this.id2entity = id2entity; - this.file = file; - this.gson = gson; - this.creative = creative; - this.nextId = 1; - - EM.setEntitiesCollectionForEntityClass(this.entityClass, this); - } - - public EntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson) - { - this(entityClass, entities, id2entity, file, gson, false); - } - - // -------------------------------------------- // - // GET - // -------------------------------------------- // + public void setCreative(boolean creative) { + this.creative = creative; + } - public Collection get() - { - return entities; - } - - public Map getMap() - { - return this.id2entity; - } - - public E get(String id) - { - if (this.creative) return this.getCreative(id); - return id2entity.get(id); - } - - public E getCreative(String id) - { - E e = id2entity.get(id); - if (e != null) return e; - return this.create(id); - } - - public boolean exists(String id) - { - if (id == null) return false; - return id2entity.get(id) != null; - } - - public E getBestIdMatch(String pattern) - { - String id = TextUtil.getBestStartWithCI(this.id2entity.keySet(), pattern); - if (id == null) return null; - return this.id2entity.get(id); - } - - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // - - public synchronized E create() - { - return this.create(this.getNextId()); - } - - public synchronized E create(String id) - { - if ( ! this.isIdFree(id)) return null; - - E e = null; - try - { - e = this.entityClass.newInstance(); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - - e.setId(id); - this.entities.add(e); - this.id2entity.put(e.getId(), e); - this.updateNextIdForId(id); - return e; - } - - // -------------------------------------------- // - // ATTACH AND DETACH - // -------------------------------------------- // - - public void attach(E entity) - { - if (entity.getId() != null) return; - entity.setId(this.getNextId()); - this.entities.add(entity); - this.id2entity.put(entity.getId(), entity); - } - - public void detach(E entity) - { - entity.preDetach(); - this.entities.remove(entity); - this.id2entity.remove(entity.getId()); - entity.postDetach(); - } - - public void detach(String id) - { - E entity = this.id2entity.get(id); - if (entity == null) return; - this.detach(entity); - } - - public boolean attached(E entity) - { - return this.entities.contains(entity); - } - - public boolean detached(E entity) - { - return ! this.attached(entity); - } - - // -------------------------------------------- // - // DISC - // -------------------------------------------- // + // This is the auto increment for the primary key "id" + private int nextId; - // we don't want to let saveToDisc() run multiple iterations simultaneously - private boolean saveIsRunning = false; + // This ugly crap is necessary due to java type erasure + private Class entityClass; - public boolean saveToDisc() - { - if (saveIsRunning) return true; - saveIsRunning = true; + public abstract Type getMapType(); // This is special stuff for GSON. - Map entitiesThatShouldBeSaved = new HashMap(); - for (E entity : this.entities) - { - if (entity.shouldBeSaved()) - { - entitiesThatShouldBeSaved.put(entity.getId(), entity); - } - } + // Info on how to persist + private Gson gson; - saveIsRunning = false; - return this.saveCore(entitiesThatShouldBeSaved); - } - - private boolean saveCore(Map entities) - { - return DiscUtil.writeCatch(this.file, this.gson.toJson(entities)); - } - - public boolean loadFromDisc() - { - Map id2entity = this.loadCore(); - if (id2entity == null) return false; - this.entities.clear(); - this.entities.addAll(id2entity.values()); - this.id2entity.clear(); - this.id2entity.putAll(id2entity); - this.fillIds(); - return true; - } - - private Map loadCore() - { - if ( ! this.file.exists()) - { - return new HashMap(); - } - - String content = DiscUtil.readCatch(this.file); - if (content == null) - { - return null; - } - - Type type = this.getMapType(); - try - { - return this.gson.fromJson(content, type); - } - catch(Exception ex) - { - Bukkit.getLogger().log(Level.WARNING, "JSON error encountered loading \"" + file + "\": " + ex.getLocalizedMessage()); + public Gson getGson() { + return gson; + } - // backup bad file, so user can attempt to recover something from it - File backup = new File(file.getPath()+"_bad"); - if (backup.exists()) backup.delete(); - Bukkit.getLogger().log(Level.WARNING, "Backing up copy of bad file to: "+backup); - file.renameTo(backup); + public void setGson(Gson gson) { + this.gson = gson; + } - return null; - } - } - - // -------------------------------------------- // - // ID MANAGEMENT - // -------------------------------------------- // - - public String getNextId() - { - while ( ! isIdFree(this.nextId) ) - { - this.nextId += 1; - } - return Integer.toString(this.nextId); - } - - public boolean isIdFree(String id) - { - return ! this.id2entity.containsKey(id); - } - public boolean isIdFree(int id) - { - return this.isIdFree(Integer.toString(id)); - } - - protected synchronized void fillIds() - { - this.nextId = 1; - for(Entry entry : this.id2entity.entrySet()) - { - String id = entry.getKey(); - E entity = entry.getValue(); - entity.id = id; - this.updateNextIdForId(id); - } - } - - protected synchronized void updateNextIdForId(int id) - { - if (this.nextId < id) - { - this.nextId = id + 1; - } - } - - protected void updateNextIdForId(String id) - { - try - { - int idAsInt = Integer.parseInt(id); - this.updateNextIdForId(idAsInt); - } - catch (Exception ignored) { } - } + private File file; + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + // -------------------------------------------- // + // CONSTRUCTORS + // -------------------------------------------- // + + public EntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson, boolean creative) { + this.entityClass = entityClass; + this.entities = entities; + this.id2entity = id2entity; + this.file = file; + this.gson = gson; + this.creative = creative; + this.nextId = 1; + + EM.setEntitiesCollectionForEntityClass(this.entityClass, this); + } + + public EntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson) { + this(entityClass, entities, id2entity, file, gson, false); + } + + // -------------------------------------------- // + // GET + // -------------------------------------------- // + + public Collection get() { + return entities; + } + + public Map getMap() { + return this.id2entity; + } + + public E get(String id) { + if (this.creative) return this.getCreative(id); + return id2entity.get(id); + } + + public E getCreative(String id) { + E e = id2entity.get(id); + if (e != null) return e; + return this.create(id); + } + + public boolean exists(String id) { + if (id == null) return false; + return id2entity.get(id) != null; + } + + public E getBestIdMatch(String pattern) { + String id = TextUtil.getBestStartWithCI(this.id2entity.keySet(), pattern); + if (id == null) return null; + return this.id2entity.get(id); + } + + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // + + public synchronized E create() { + return this.create(this.getNextId()); + } + + public synchronized E create(String id) { + if (!this.isIdFree(id)) return null; + + E e = null; + try { + e = this.entityClass.newInstance(); + } catch (Exception ignored) { + ignored.printStackTrace(); + } + + e.setId(id); + this.entities.add(e); + this.id2entity.put(e.getId(), e); + this.updateNextIdForId(id); + return e; + } + + // -------------------------------------------- // + // ATTACH AND DETACH + // -------------------------------------------- // + + public void attach(E entity) { + if (entity.getId() != null) return; + entity.setId(this.getNextId()); + this.entities.add(entity); + this.id2entity.put(entity.getId(), entity); + } + + public void detach(E entity) { + entity.preDetach(); + this.entities.remove(entity); + this.id2entity.remove(entity.getId()); + entity.postDetach(); + } + + public void detach(String id) { + E entity = this.id2entity.get(id); + if (entity == null) return; + this.detach(entity); + } + + public boolean attached(E entity) { + return this.entities.contains(entity); + } + + public boolean detached(E entity) { + return !this.attached(entity); + } + + // -------------------------------------------- // + // DISC + // -------------------------------------------- // + + // we don't want to let saveToDisc() run multiple iterations simultaneously + private boolean saveIsRunning = false; + + public boolean saveToDisc() { + if (saveIsRunning) return true; + saveIsRunning = true; + + Map entitiesThatShouldBeSaved = new HashMap(); + for (E entity : this.entities) { + if (entity.shouldBeSaved()) { + entitiesThatShouldBeSaved.put(entity.getId(), entity); + } + } + + saveIsRunning = false; + return this.saveCore(entitiesThatShouldBeSaved); + } + + private boolean saveCore(Map entities) { + return DiscUtil.writeCatch(this.file, this.gson.toJson(entities)); + } + + public boolean loadFromDisc() { + Map id2entity = this.loadCore(); + if (id2entity == null) return false; + this.entities.clear(); + this.entities.addAll(id2entity.values()); + this.id2entity.clear(); + this.id2entity.putAll(id2entity); + this.fillIds(); + return true; + } + + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap(); + } + + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } + + Type type = this.getMapType(); + try { + return this.gson.fromJson(content, type); + } catch (Exception ex) { + Bukkit.getLogger().log(Level.WARNING, "JSON error encountered loading \"" + file + "\": " + ex.getLocalizedMessage()); + + // backup bad file, so user can attempt to recover something from it + File backup = new File(file.getPath() + "_bad"); + if (backup.exists()) backup.delete(); + Bukkit.getLogger().log(Level.WARNING, "Backing up copy of bad file to: " + backup); + file.renameTo(backup); + + return null; + } + } + + // -------------------------------------------- // + // ID MANAGEMENT + // -------------------------------------------- // + + public String getNextId() { + while (!isIdFree(this.nextId)) { + this.nextId += 1; + } + return Integer.toString(this.nextId); + } + + public boolean isIdFree(String id) { + return !this.id2entity.containsKey(id); + } + + public boolean isIdFree(int id) { + return this.isIdFree(Integer.toString(id)); + } + + protected synchronized void fillIds() { + this.nextId = 1; + for (Entry entry : this.id2entity.entrySet()) { + String id = entry.getKey(); + E entity = entry.getValue(); + entity.id = id; + this.updateNextIdForId(id); + } + } + + protected synchronized void updateNextIdForId(int id) { + if (this.nextId < id) { + this.nextId = id + 1; + } + } + + protected void updateNextIdForId(String id) { + try { + int idAsInt = Integer.parseInt(id); + this.updateNextIdForId(idAsInt); + } catch (Exception ignored) { + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java index c79bc0b2..25722f56 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java @@ -1,51 +1,43 @@ package com.massivecraft.factions.zcore.persist; -import java.util.List; - import org.bukkit.Bukkit; import org.bukkit.entity.Player; -public class PlayerEntity extends Entity -{ - public Player getPlayer() - { - return Bukkit.getPlayerExact(this.getId()); - } - - public boolean isOnline() - { - return this.getPlayer() != null; - } +import java.util.List; - // make sure target player should be able to detect that this player is online - public boolean isOnlineAndVisibleTo(Player player) - { - Player target = this.getPlayer(); - return target != null && player.canSee(target); - } +public class PlayerEntity extends Entity { + public Player getPlayer() { + return Bukkit.getPlayerExact(this.getId()); + } + + public boolean isOnline() { + return this.getPlayer() != null; + } + + // make sure target player should be able to detect that this player is online + public boolean isOnlineAndVisibleTo(Player player) { + Player target = this.getPlayer(); + return target != null && player.canSee(target); + } + + public boolean isOffline() { + return !isOnline(); + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public void sendMessage(String msg) { + Player player = this.getPlayer(); + if (player == null) return; + player.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } - public boolean isOffline() - { - return ! isOnline(); - } - - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // - - public void sendMessage(String msg) - { - Player player = this.getPlayer(); - if (player == null) return; - player.sendMessage(msg); - } - - public void sendMessage(List msgs) - { - for(String msg : msgs) - { - this.sendMessage(msg); - } - } - } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java index 41278225..f3af64e0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java @@ -1,45 +1,38 @@ package com.massivecraft.factions.zcore.persist; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.libs.com.google.gson.Gson; +import org.bukkit.entity.Player; + import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import org.bukkit.craftbukkit.libs.com.google.gson.Gson; - /** - * The PlayerEntityCollection is an EntityCollection with the extra features - * a player skin usually requires. - * - * This entity collection is not only creative. It even creates the instance for the player - * when the player logs in to the server. - * - * This way we can be sure that PlayerEntityCollection.get() will contain - * all entities in PlayerEntityCollection.getOnline() + * The PlayerEntityCollection is an EntityCollection with the extra features a player skin usually requires. + *

+ * This entity collection is not only creative. It even creates the instance for the player when the player logs in to + * the server. + *

+ * This way we can be sure that PlayerEntityCollection.get() will contain all entities in + * PlayerEntityCollection.getOnline() */ -public abstract class PlayerEntityCollection extends EntityCollection -{ - public PlayerEntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson) - { - super(entityClass, entities, id2entity, file, gson, true); - } - - public E get(Player player) - { - return this.get(player.getName()); - } - - public Set getOnline() - { - Set entities = new HashSet(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) - { - entities.add(this.get(player)); - } - return entities; - } +public abstract class PlayerEntityCollection extends EntityCollection { + public PlayerEntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson) { + super(entityClass, entities, id2entity, file, gson, true); + } + + public E get(Player player) { + return this.get(player.getName()); + } + + public Set getOnline() { + Set entities = new HashSet(); + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + entities.add(this.get(player)); + } + return entities; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java index c3833470..10ca14ba 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java @@ -2,23 +2,21 @@ package com.massivecraft.factions.zcore.persist; import com.massivecraft.factions.zcore.MPlugin; -public class SaveTask implements Runnable -{ - static private boolean running = false; +public class SaveTask implements Runnable { + static private boolean running = false; - MPlugin p; - public SaveTask(MPlugin p) - { - this.p = p; - } - - public void run() - { - if ( ! p.getAutoSave() || running) return; - running = true; - p.preAutoSave(); - EM.saveAllToDisc(); - p.postAutoSave(); - running = false; - } + MPlugin p; + + public SaveTask(MPlugin p) { + this.p = p; + } + + public void run() { + if (!p.getAutoSave() || running) return; + running = true; + p.preAutoSave(); + EM.saveAllToDisc(); + p.postAutoSave(); + running = false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/ClassLoadHack.java b/src/main/java/com/massivecraft/factions/zcore/util/ClassLoadHack.java index d478cc5f..4c896810 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/ClassLoadHack.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/ClassLoadHack.java @@ -7,45 +7,35 @@ import java.net.URL; import java.net.URLClassLoader; public class ClassLoadHack { - - private static URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader(); - - public static boolean load(String filename) - { - return load(new File(filename)); - } - - public static boolean load(File file) - { - try - { - return load(file.toURI().toURL()); - } - catch (MalformedURLException e) - { - return false; - } - } - - public static boolean load(URL url) - { - // If the file already is loaded we can skip it - for (URL otherUrl : sysloader.getURLs()) - { - if (otherUrl.sameFile(url)) return true; - } - - try - { - Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class }); - addURLMethod.setAccessible(true); - addURLMethod.invoke(sysloader, new Object[]{ url }); - return true; - } - catch (Exception e) - { - return false; - } - } - + + private static URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); + + public static boolean load(String filename) { + return load(new File(filename)); + } + + public static boolean load(File file) { + try { + return load(file.toURI().toURL()); + } catch (MalformedURLException e) { + return false; + } + } + + public static boolean load(URL url) { + // If the file already is loaded we can skip it + for (URL otherUrl : sysloader.getURLs()) { + if (otherUrl.sameFile(url)) return true; + } + + try { + Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); + addURLMethod.setAccessible(true); + addURLMethod.invoke(sysloader, new Object[]{url}); + return true; + } catch (Exception e) { + return false; + } + } + } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java index 344be452..ff5ed5f6 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java @@ -5,154 +5,124 @@ import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; -public class DiscUtil -{ - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // - - private final static String UTF8 = "UTF-8"; - - // -------------------------------------------- // - // BYTE - // -------------------------------------------- // - - public static byte[] readBytes(File file) throws IOException - { - int length = (int) file.length(); - byte[] output = new byte[length]; - InputStream in = new FileInputStream(file); - int offset = 0; - while (offset < length) - { - offset += in.read(output, offset, (length - offset)); - } - in.close(); - return output; - } - - public static void writeBytes(File file, byte[] bytes) throws IOException - { - FileOutputStream out = new FileOutputStream(file); - out.write(bytes); - out.close(); - } +public class DiscUtil { + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // - // -------------------------------------------- // - // STRING - // -------------------------------------------- // - - public static void write(File file, String content) throws IOException - { - writeBytes(file, utf8(content)); - } - - public static String read(File file) throws IOException - { - return utf8(readBytes(file)); - } - - // -------------------------------------------- // - // CATCH - // -------------------------------------------- // - - public static boolean writeCatch(File file, String content) - { - try - { - write(file, content); - return true; - } - catch (Exception e) - { - return false; - } - } - - public static String readCatch(File file) - { - try - { - return read(file); - } - catch (IOException e) - { - return null; - } - } - - // -------------------------------------------- // - // DOWNLOAD - // -------------------------------------------- // - - public static boolean downloadUrl(String urlstring, File file) - { - try - { - URL url = new URL(urlstring); - ReadableByteChannel rbc = Channels.newChannel(url.openStream()); - FileOutputStream fos = new FileOutputStream(file); - fos.getChannel().transferFrom(rbc, 0, 1 << 24); - return true; - } - catch (Exception e) - { - e.printStackTrace(); - return false; - } - } - - public static boolean downloadUrl(String urlstring, String filename) - { - return downloadUrl(urlstring, new File(filename)); - } - - // -------------------------------------------- // - // FILE DELETION - // -------------------------------------------- // - - public static boolean deleteRecursive(File path) throws FileNotFoundException - { - if ( ! path.exists()) throw new FileNotFoundException(path.getAbsolutePath()); + private final static String UTF8 = "UTF-8"; + + // -------------------------------------------- // + // BYTE + // -------------------------------------------- // + + public static byte[] readBytes(File file) throws IOException { + int length = (int) file.length(); + byte[] output = new byte[length]; + InputStream in = new FileInputStream(file); + int offset = 0; + while (offset < length) { + offset += in.read(output, offset, (length - offset)); + } + in.close(); + return output; + } + + public static void writeBytes(File file, byte[] bytes) throws IOException { + FileOutputStream out = new FileOutputStream(file); + out.write(bytes); + out.close(); + } + + // -------------------------------------------- // + // STRING + // -------------------------------------------- // + + public static void write(File file, String content) throws IOException { + writeBytes(file, utf8(content)); + } + + public static String read(File file) throws IOException { + return utf8(readBytes(file)); + } + + // -------------------------------------------- // + // CATCH + // -------------------------------------------- // + + public static boolean writeCatch(File file, String content) { + try { + write(file, content); + return true; + } catch (Exception e) { + return false; + } + } + + public static String readCatch(File file) { + try { + return read(file); + } catch (IOException e) { + return null; + } + } + + // -------------------------------------------- // + // DOWNLOAD + // -------------------------------------------- // + + public static boolean downloadUrl(String urlstring, File file) { + try { + URL url = new URL(urlstring); + ReadableByteChannel rbc = Channels.newChannel(url.openStream()); + FileOutputStream fos = new FileOutputStream(file); + fos.getChannel().transferFrom(rbc, 0, 1 << 24); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public static boolean downloadUrl(String urlstring, String filename) { + return downloadUrl(urlstring, new File(filename)); + } + + // -------------------------------------------- // + // FILE DELETION + // -------------------------------------------- // + + public static boolean deleteRecursive(File path) throws FileNotFoundException { + if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath()); boolean ret = true; - if (path.isDirectory()) - { - for (File f : path.listFiles()) - { + if (path.isDirectory()) { + for (File f : path.listFiles()) { ret = ret && deleteRecursive(f); } } return ret && path.delete(); } - - // -------------------------------------------- // - // UTF8 ENCODE AND DECODE - // -------------------------------------------- // - - public static byte[] utf8(String string) - { - try - { - return string.getBytes(UTF8); - } - catch (UnsupportedEncodingException e) - { - e.printStackTrace(); - return null; - } - } - - public static String utf8(byte[] bytes) - { - try - { - return new String(bytes, UTF8); - } - catch (UnsupportedEncodingException e) - { - e.printStackTrace(); - return null; - } - } + + // -------------------------------------------- // + // UTF8 ENCODE AND DECODE + // -------------------------------------------- // + + public static byte[] utf8(String string) { + try { + return string.getBytes(UTF8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + } + + public static String utf8(byte[] bytes) { + try { + return new String(bytes, UTF8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/LibLoader.java b/src/main/java/com/massivecraft/factions/zcore/util/LibLoader.java index 63bafc77..a08e17b8 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/LibLoader.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/LibLoader.java @@ -1,49 +1,42 @@ package com.massivecraft.factions.zcore.util; -import java.io.File; - import com.massivecraft.factions.zcore.MPlugin; -public class LibLoader -{ - MPlugin p; - public LibLoader(MPlugin p) - { - this.p = p; - new File("./lib").mkdirs(); - } - - public boolean require(String filename, String url) - { - if ( ! include(filename, url)) - { - p.log("Failed to load the required library "+filename); - p.suicide(); - return false; - } - return true; - } - - public boolean include (String filename, String url) - { - File file = getFile(filename); - if ( ! file.exists()) - { - p.log("Downloading library "+filename); - if ( ! DiscUtil.downloadUrl(url, file)) - { - p.log("Failed to download "+filename); - return false; - } - } - - return ClassLoadHack.load(file); - } - - private static File getFile(String filename) - { - return new File("./lib/"+filename); - } +import java.io.File; + +public class LibLoader { + MPlugin p; + + public LibLoader(MPlugin p) { + this.p = p; + new File("./lib").mkdirs(); + } + + public boolean require(String filename, String url) { + if (!include(filename, url)) { + p.log("Failed to load the required library " + filename); + p.suicide(); + return false; + } + return true; + } + + public boolean include(String filename, String url) { + File file = getFile(filename); + if (!file.exists()) { + p.log("Downloading library " + filename); + if (!DiscUtil.downloadUrl(url, file)) { + p.log("Failed to download " + filename); + return false; + } + } + + return ClassLoadHack.load(file); + } + + private static File getFile(String filename) { + return new File("./lib/" + filename); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java index da74645d..2cc449b1 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java @@ -1,95 +1,80 @@ package com.massivecraft.factions.zcore.util; -import java.util.*; -import java.util.Map.Entry; - +import com.massivecraft.factions.zcore.Lang; +import com.massivecraft.factions.zcore.MPlugin; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; -import com.massivecraft.factions.zcore.Lang; -import com.massivecraft.factions.zcore.MPlugin; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; public class PermUtil { - public Map permissionDescriptions = new HashMap(); - - protected MPlugin p; - - public PermUtil(MPlugin p) - { - this.p = p; - this.setup(); - } - - public String getForbiddenMessage(String perm) - { - return p.txt.parse(Lang.permForbidden, getPermissionDescription(perm)); - } - - /** - * This method hooks into all permission plugins we are supporting - */ - public final void setup() - { - for(Permission permission : p.getDescription().getPermissions()) - { - //p.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); - this.permissionDescriptions.put(permission.getName(), permission.getDescription()); - } - } + public Map permissionDescriptions = new HashMap(); - public String getPermissionDescription (String perm) - { - String desc = permissionDescriptions.get(perm); - if (desc == null) - { - return Lang.permDoThat; - } - return desc; - } - - /** - * This method tests if me has a certain permission and returns - * true if me has. Otherwise false - */ - public boolean has (CommandSender me, String perm) - { - if (me == null) return false; - - if ( ! (me instanceof Player)) - { - return me.hasPermission(perm); - } + protected MPlugin p; + + public PermUtil(MPlugin p) { + this.p = p; + this.setup(); + } + + public String getForbiddenMessage(String perm) { + return p.txt.parse(Lang.permForbidden, getPermissionDescription(perm)); + } + + /** + * This method hooks into all permission plugins we are supporting + */ + public final void setup() { + for (Permission permission : p.getDescription().getPermissions()) { + //p.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); + this.permissionDescriptions.put(permission.getName(), permission.getDescription()); + } + } + + public String getPermissionDescription(String perm) { + String desc = permissionDescriptions.get(perm); + if (desc == null) { + return Lang.permDoThat; + } + return desc; + } + + /** + * This method tests if me has a certain permission and returns true if me has. Otherwise false + */ + public boolean has(CommandSender me, String perm) { + if (me == null) return false; + + if (!(me instanceof Player)) { + return me.hasPermission(perm); + } + + return me.hasPermission(perm); + } + + public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { + if (has(me, perm)) { + return true; + } else if (informSenderIfNot && me != null) { + me.sendMessage(this.getForbiddenMessage(perm)); + } + return false; + } + + public T pickFirstVal(CommandSender me, Map perm2val) { + if (perm2val == null) return null; + T ret = null; + + for (Entry entry : perm2val.entrySet()) { + ret = entry.getValue(); + if (has(me, entry.getKey())) break; + } + + return ret; + } - return me.hasPermission(perm); - } - - public boolean has (CommandSender me, String perm, boolean informSenderIfNot) - { - if (has(me, perm)) - { - return true; - } - else if (informSenderIfNot && me != null) - { - me.sendMessage(this.getForbiddenMessage(perm)); - } - return false; - } - - public T pickFirstVal(CommandSender me, Map perm2val) - { - if (perm2val == null) return null; - T ret = null; - - for ( Entry entry : perm2val.entrySet()) - { - ret = entry.getValue(); - if (has(me, entry.getKey())) break; - } - - return ret; - } - } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java index 56ba920d..cc670b36 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java @@ -1,179 +1,152 @@ package com.massivecraft.factions.zcore.util; +import com.massivecraft.factions.zcore.MPlugin; + import java.io.File; import java.lang.reflect.Type; import java.util.logging.Level; -import com.massivecraft.factions.zcore.MPlugin; - // TODO: Give better name and place to differenciate from the entity-orm-ish system in "com.massivecraft.core.persist". public class Persist { - - private MPlugin p; - public Persist(MPlugin p) - { - this.p = p; - } - - // ------------------------------------------------------------ // - // GET NAME - What should we call this type of object? - // ------------------------------------------------------------ // - - public static String getName(Class clazz) - { - return clazz.getSimpleName().toLowerCase(); - } - - public static String getName(Object o) - { - return getName(o.getClass()); - } - - public static String getName(Type type) - { - return getName(type.getClass()); - } - - // ------------------------------------------------------------ // - // GET FILE - In which file would we like to store this object? - // ------------------------------------------------------------ // - - public File getFile(String name) - { - return new File(p.getDataFolder(), name+".json"); - } - - public File getFile(Class clazz) - { - return getFile(getName(clazz)); - } - - public File getFile(Object obj) - { - return getFile(getName(obj)); - } - - public File getFile(Type type) - { - return getFile(getName(type)); - } - - - // NICE WRAPPERS - - public T loadOrSaveDefault(T def, Class clazz) - { - return loadOrSaveDefault(def, clazz, getFile(clazz)); - } - - public T loadOrSaveDefault(T def, Class clazz, String name) - { - return loadOrSaveDefault(def, clazz, getFile(name)); - } - - public T loadOrSaveDefault(T def, Class clazz, File file) - { - if ( ! file.exists()) - { - p.log("Creating default: "+file); - this.save(def, file); - return def; - } - - T loaded = this.load(clazz, file); - - if (loaded == null) - { - p.log(Level.WARNING, "Using default as I failed to load: "+file); - // backup bad file, so user can attempt to recover their changes from it - File backup = new File(file.getPath()+"_bad"); - if (backup.exists()) backup.delete(); - p.log(Level.WARNING, "Backing up copy of bad file to: "+backup); - file.renameTo(backup); + private MPlugin p; - return def; - } - - return loaded; - } - - // SAVE - - public boolean save(Object instance) - { - return save(instance, getFile(instance)); - } - - public boolean save(Object instance, String name) - { - return save(instance, getFile(name)); - } - - public boolean save(Object instance, File file) - { - return DiscUtil.writeCatch(file, p.gson.toJson(instance)); - } - - // LOAD BY CLASS - - public T load(Class clazz) - { - return load(clazz, getFile(clazz)); - } - - public T load(Class clazz, String name) - { - return load(clazz, getFile(name)); - } - - public T load(Class clazz, File file) - { - String content = DiscUtil.readCatch(file); - if (content == null) - { - return null; - } + public Persist(MPlugin p) { + this.p = p; + } - try - { - T instance = p.gson.fromJson(content, clazz); - return instance; - } - catch (Exception ex) - { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + // ------------------------------------------------------------ // + // GET NAME - What should we call this type of object? + // ------------------------------------------------------------ // - return null; - } - - - // LOAD BY TYPE - @SuppressWarnings("unchecked") - public T load(Type typeOfT, String name) - { - return (T) load(typeOfT, getFile(name)); - } - - @SuppressWarnings("unchecked") - public T load(Type typeOfT, File file) - { - String content = DiscUtil.readCatch(file); - if (content == null) { - return null; - } + public static String getName(Class clazz) { + return clazz.getSimpleName().toLowerCase(); + } - try - { - return (T) p.gson.fromJson(content, typeOfT); - } - catch (Exception ex) - { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + public static String getName(Object o) { + return getName(o.getClass()); + } - return null; - } + public static String getName(Type type) { + return getName(type.getClass()); + } + + // ------------------------------------------------------------ // + // GET FILE - In which file would we like to store this object? + // ------------------------------------------------------------ // + + public File getFile(String name) { + return new File(p.getDataFolder(), name + ".json"); + } + + public File getFile(Class clazz) { + return getFile(getName(clazz)); + } + + public File getFile(Object obj) { + return getFile(getName(obj)); + } + + public File getFile(Type type) { + return getFile(getName(type)); + } + + + // NICE WRAPPERS + + public T loadOrSaveDefault(T def, Class clazz) { + return loadOrSaveDefault(def, clazz, getFile(clazz)); + } + + public T loadOrSaveDefault(T def, Class clazz, String name) { + return loadOrSaveDefault(def, clazz, getFile(name)); + } + + public T loadOrSaveDefault(T def, Class clazz, File file) { + if (!file.exists()) { + p.log("Creating default: " + file); + this.save(def, file); + return def; + } + + T loaded = this.load(clazz, file); + + if (loaded == null) { + p.log(Level.WARNING, "Using default as I failed to load: " + file); + + // backup bad file, so user can attempt to recover their changes from it + File backup = new File(file.getPath() + "_bad"); + if (backup.exists()) backup.delete(); + p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); + file.renameTo(backup); + + return def; + } + + return loaded; + } + + // SAVE + + public boolean save(Object instance) { + return save(instance, getFile(instance)); + } + + public boolean save(Object instance, String name) { + return save(instance, getFile(name)); + } + + public boolean save(Object instance, File file) { + return DiscUtil.writeCatch(file, p.gson.toJson(instance)); + } + + // LOAD BY CLASS + + public T load(Class clazz) { + return load(clazz, getFile(clazz)); + } + + public T load(Class clazz, String name) { + return load(clazz, getFile(name)); + } + + public T load(Class clazz, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } + + try { + T instance = p.gson.fromJson(content, clazz); + return instance; + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } + + return null; + } + + + // LOAD BY TYPE + @SuppressWarnings("unchecked") + public T load(Type typeOfT, String name) { + return (T) load(typeOfT, getFile(name)); + } + + @SuppressWarnings("unchecked") + public T load(Type typeOfT, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } + + try { + return (T) p.gson.fromJson(content, typeOfT); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } + + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java index 05f718ef..985c9108 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java @@ -1,11 +1,11 @@ package com.massivecraft.factions.zcore.util; -import java.util.Collection; -import java.util.Random; - import org.bukkit.Effect; import org.bukkit.Location; +import java.util.Collection; +import java.util.Random; + // http://mc.kev009.com/Protocol // ----------------------------- // Smoke Directions @@ -22,70 +22,58 @@ import org.bukkit.Location; // 8 North - West //----------------------------- -public class SmokeUtil -{ - public static Random random = new Random(); - - // -------------------------------------------- // - // Spawn once - // -------------------------------------------- // - - // Single ======== - public static void spawnSingle(Location location, int direction) - { - if (location == null) return; - location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); - } - - public static void spawnSingle(Location location) - { - spawnSingle(location, 4); - } - - public static void spawnSingleRandom(Location location) - { - spawnSingle(location, random.nextInt(9)); - } - - // Simple Cloud ======== - public static void spawnCloudSimple(Location location) - { - for (int i = 0; i <= 8; i++) - { - spawnSingle(location, i); - } - } - - public static void spawnCloudSimple(Collection locations) - { - for (Location location : locations) - { - spawnCloudSimple(location); - } - } - - // Random Cloud ======== - public static void spawnCloudRandom(Location location, float thickness) - { - int singles = (int) Math.floor(thickness*9); - for (int i = 0; i < singles; i++) - { - spawnSingleRandom(location.clone()); - } - } - - public static void spawnCloudRandom(Collection locations, float thickness) - { - for (Location location : locations) - { - spawnCloudRandom(location, thickness); - } - } - - // -------------------------------------------- // - // Attach continuous effects to or locations - // -------------------------------------------- // - - // TODO - +public class SmokeUtil { + public static Random random = new Random(); + + // -------------------------------------------- // + // Spawn once + // -------------------------------------------- // + + // Single ======== + public static void spawnSingle(Location location, int direction) { + if (location == null) return; + location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); + } + + public static void spawnSingle(Location location) { + spawnSingle(location, 4); + } + + public static void spawnSingleRandom(Location location) { + spawnSingle(location, random.nextInt(9)); + } + + // Simple Cloud ======== + public static void spawnCloudSimple(Location location) { + for (int i = 0; i <= 8; i++) { + spawnSingle(location, i); + } + } + + public static void spawnCloudSimple(Collection locations) { + for (Location location : locations) { + spawnCloudSimple(location); + } + } + + // Random Cloud ======== + public static void spawnCloudRandom(Location location, float thickness) { + int singles = (int) Math.floor(thickness * 9); + for (int i = 0; i < singles; i++) { + spawnSingleRandom(location.clone()); + } + } + + public static void spawnCloudRandom(Collection locations, float thickness) { + for (Location location : locations) { + spawnCloudRandom(location, thickness); + } + } + + // -------------------------------------------- // + // Attach continuous effects to or locations + // -------------------------------------------- // + + // TODO + } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java index b8716031..60d4c570 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java @@ -1,290 +1,249 @@ package com.massivecraft.factions.zcore.util; +import org.bukkit.ChatColor; +import org.bukkit.Material; + import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.bukkit.ChatColor; -import org.bukkit.Material; +public class TextUtil { + public Map tags; -public class TextUtil -{ - public Map tags; - public TextUtil() - { - this.tags = new HashMap(); - } - - // -------------------------------------------- // - // Top-level parsing functions. - // -------------------------------------------- // - - public String parse(String str, Object... args) - { - return String.format(this.parse(str), args); - } - - public String parse(String str) - { - return this.parseTags(parseColor(str)); - } - - // -------------------------------------------- // - // Tag parsing - // -------------------------------------------- // - - public String parseTags(String str) - { - return replaceTags(str, this.tags); - } - - public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); - public static String replaceTags(String str, Map tags) - { - StringBuffer ret = new StringBuffer(); - Matcher matcher = patternTag.matcher(str); - while (matcher.find()) - { - String tag = matcher.group(1); - String repl = tags.get(tag); - if (repl == null) - { - matcher.appendReplacement(ret, "<"+tag+">"); - } - else - { - matcher.appendReplacement(ret, repl); - } - } - matcher.appendTail(ret); - return ret.toString(); - } - - // -------------------------------------------- // - // Color parsing - // -------------------------------------------- // - - public static String parseColor(String string) - { - string = parseColorAmp(string); - string = parseColorAcc(string); - string = parseColorTags(string); - return string; - } - - public static String parseColorAmp(String string) - { - string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); - string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); - string = string.replace("&&", "&"); - return string; - } - - public static String parseColorAcc(String string) - { - return string.replace("`e", "") - .replace("`r", ChatColor.RED.toString()) .replace("`R", ChatColor.DARK_RED.toString()) - .replace("`y", ChatColor.YELLOW.toString()) .replace("`Y", ChatColor.GOLD.toString()) - .replace("`g", ChatColor.GREEN.toString()) .replace("`G", ChatColor.DARK_GREEN.toString()) - .replace("`a", ChatColor.AQUA.toString()) .replace("`A", ChatColor.DARK_AQUA.toString()) - .replace("`b", ChatColor.BLUE.toString()) .replace("`B", ChatColor.DARK_BLUE.toString()) - .replace("`p", ChatColor.LIGHT_PURPLE.toString()) .replace("`P", ChatColor.DARK_PURPLE.toString()) - .replace("`k", ChatColor.BLACK.toString()) .replace("`s", ChatColor.GRAY.toString()) - .replace("`S", ChatColor.DARK_GRAY.toString()) .replace("`w", ChatColor.WHITE.toString()); - } - - public static String parseColorTags(String string) - { - return string.replace("", "") - .replace("", "\u00A70") - .replace("", "\u00A71") - .replace("", "\u00A72") - .replace("", "\u00A73") - .replace("", "\u00A74") - .replace("", "\u00A75") - .replace("", "\u00A76") - .replace("", "\u00A77") - .replace("", "\u00A78") - .replace("", "\u00A79") - .replace("", "\u00A7a") - .replace("", "\u00A7b") - .replace("", "\u00A7c") - .replace("", "\u00A7d") - .replace("", "\u00A7e") - .replace("", "\u00A7f"); - } - - // -------------------------------------------- // - // Standard utils like UCFirst, implode and repeat. - // -------------------------------------------- // - - public static String upperCaseFirst(String string) - { - return string.substring(0, 1).toUpperCase()+string.substring(1); - } - - public static String implode(List list, String glue) - { - StringBuilder ret = new StringBuilder(); - for (int i=0; i") + str + parseTags("")+ " ]."; - int centerlen = ChatColor.stripColor(center).length(); - int pivot = titleizeLine.length() / 2; - int eatLeft = (centerlen / 2) - titleizeBalance; - int eatRight = (centerlen - eatLeft) + titleizeBalance; + public TextUtil() { + this.tags = new HashMap(); + } + + // -------------------------------------------- // + // Top-level parsing functions. + // -------------------------------------------- // + + public String parse(String str, Object... args) { + return String.format(this.parse(str), args); + } + + public String parse(String str) { + return this.parseTags(parseColor(str)); + } + + // -------------------------------------------- // + // Tag parsing + // -------------------------------------------- // + + public String parseTags(String str) { + return replaceTags(str, this.tags); + } + + public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); + + public static String replaceTags(String str, Map tags) { + StringBuffer ret = new StringBuffer(); + Matcher matcher = patternTag.matcher(str); + while (matcher.find()) { + String tag = matcher.group(1); + String repl = tags.get(tag); + if (repl == null) { + matcher.appendReplacement(ret, "<" + tag + ">"); + } else { + matcher.appendReplacement(ret, repl); + } + } + matcher.appendTail(ret); + return ret.toString(); + } + + // -------------------------------------------- // + // Color parsing + // -------------------------------------------- // + + public static String parseColor(String string) { + string = parseColorAmp(string); + string = parseColorAcc(string); + string = parseColorTags(string); + return string; + } + + public static String parseColorAmp(String string) { + string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); + string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); + string = string.replace("&&", "&"); + return string; + } + + public static String parseColorAcc(String string) { + return string.replace("`e", "") + .replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()) + .replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()) + .replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()) + .replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()) + .replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()) + .replace("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()) + .replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()) + .replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); + } + + public static String parseColorTags(String string) { + return string.replace("", "") + .replace("", "\u00A70") + .replace("", "\u00A71") + .replace("", "\u00A72") + .replace("", "\u00A73") + .replace("", "\u00A74") + .replace("", "\u00A75") + .replace("", "\u00A76") + .replace("", "\u00A77") + .replace("", "\u00A78") + .replace("", "\u00A79") + .replace("", "\u00A7a") + .replace("", "\u00A7b") + .replace("", "\u00A7c") + .replace("", "\u00A7d") + .replace("", "\u00A7e") + .replace("", "\u00A7f"); + } + + // -------------------------------------------- // + // Standard utils like UCFirst, implode and repeat. + // -------------------------------------------- // + + public static String upperCaseFirst(String string) { + return string.substring(0, 1).toUpperCase() + string.substring(1); + } + + public static String implode(List list, String glue) { + StringBuilder ret = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + if (i != 0) { + ret.append(glue); + } + ret.append(list.get(i)); + } + return ret.toString(); + } + + public static String repeat(String s, int times) { + if (times <= 0) return ""; + else return s + repeat(s, times - 1); + } + + // -------------------------------------------- // + // Material name tools + // -------------------------------------------- // + + public static String getMaterialName(Material material) { + return material.toString().replace('_', ' ').toLowerCase(); + } + + public static String getMaterialName(int materialId) { + return getMaterialName(Material.getMaterial(materialId)); + } + + // -------------------------------------------- // + // Paging and chrome-tools like titleize + // -------------------------------------------- // + + private final static String titleizeLine = repeat("_", 52); + private final static int titleizeBalance = -1; + + public String titleize(String str) { + String center = ".[ " + parseTags("") + str + parseTags("") + " ]."; + int centerlen = ChatColor.stripColor(center).length(); + int pivot = titleizeLine.length() / 2; + int eatLeft = (centerlen / 2) - titleizeBalance; + int eatRight = (centerlen - eatLeft) + titleizeBalance; + + if (eatLeft < pivot) + return parseTags("") + titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight); + else + return parseTags("") + center; + } + + public ArrayList getPage(List lines, int pageHumanBased, String title) { + ArrayList ret = new ArrayList(); + int pageZeroBased = pageHumanBased - 1; + int pageheight = 9; + int pagecount = (lines.size() / pageheight) + 1; + + ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); + + if (pagecount == 0) { + ret.add(this.parseTags("Sorry. No Pages available.")); + return ret; + } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { + ret.add(this.parseTags("Invalid page. Must be between 1 and " + pagecount)); + return ret; + } + + int from = pageZeroBased * pageheight; + int to = from + pageheight; + if (to > lines.size()) { + to = lines.size(); + } + + ret.addAll(lines.subList(from, to)); + + return ret; + } + + // -------------------------------------------- // + // Describing Time + // -------------------------------------------- // + + /** + * Using this function you transform a delta in milliseconds to a String like "2 weeks from now" or "7 days ago". + */ + public static final long millisPerSecond = 1000; + public static final long millisPerMinute = 60 * millisPerSecond; + public static final long millisPerHour = 60 * millisPerMinute; + public static final long millisPerDay = 24 * millisPerHour; + public static final long millisPerWeek = 7 * millisPerDay; + public static final long millisPerMonth = 31 * millisPerDay; + public static final long millisPerYear = 365 * millisPerDay; + + public static String getTimeDeltaDescriptionRelNow(long millis) { + double absmillis = (double) Math.abs(millis); + String agofromnow = "from now"; + String unit; + long num; + if (millis <= 0) { + agofromnow = "ago"; + } + + // We use a factor 3 below for a reason... why do you think? + // Answer: it is a way to make our round of error smaller. + if (absmillis < 3 * millisPerSecond) { + unit = "milliseconds"; + num = (long) (absmillis); + } else if (absmillis < 3 * millisPerMinute) { + unit = "seconds"; + num = (long) (absmillis / millisPerSecond); + } else if (absmillis < 3 * millisPerHour) { + unit = "minutes"; + num = (long) (absmillis / millisPerMinute); + } else if (absmillis < 3 * millisPerDay) { + unit = "hours"; + num = (long) (absmillis / millisPerHour); + } else if (absmillis < 3 * millisPerWeek) { + unit = "days"; + num = (long) (absmillis / millisPerDay); + } else if (absmillis < 3 * millisPerMonth) { + unit = "weeks"; + num = (long) (absmillis / millisPerWeek); + } else if (absmillis < 3 * millisPerYear) { + unit = "months"; + num = (long) (absmillis / millisPerMonth); + } else { + unit = "years"; + num = (long) (absmillis / millisPerYear); + } + + return "" + num + " " + unit + " " + agofromnow; + } + + // -------------------------------------------- // + // String comparison + // -------------------------------------------- // - if (eatLeft < pivot) - return parseTags("")+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight); - else - return parseTags("")+center; - } - - public ArrayList getPage(List lines, int pageHumanBased, String title) - { - ArrayList ret = new ArrayList(); - int pageZeroBased = pageHumanBased - 1; - int pageheight = 9; - int pagecount = (lines.size() / pageheight)+1; - - ret.add(this.titleize(title+" "+pageHumanBased+"/"+pagecount)); - - if (pagecount == 0) - { - ret.add(this.parseTags("Sorry. No Pages available.")); - return ret; - } - else if (pageZeroBased < 0 || pageHumanBased > pagecount) - { - ret.add(this.parseTags("Invalid page. Must be between 1 and "+pagecount)); - return ret; - } - - int from = pageZeroBased * pageheight; - int to = from+pageheight; - if (to > lines.size()) - { - to = lines.size(); - } - - ret.addAll(lines.subList(from, to)); - - return ret; - } - - // -------------------------------------------- // - // Describing Time - // -------------------------------------------- // - - /** - * Using this function you transform a delta in milliseconds - * to a String like "2 weeks from now" or "7 days ago". - */ - public static final long millisPerSecond = 1000; - public static final long millisPerMinute = 60 * millisPerSecond; - public static final long millisPerHour = 60 * millisPerMinute; - public static final long millisPerDay = 24 * millisPerHour; - public static final long millisPerWeek = 7 * millisPerDay; - public static final long millisPerMonth = 31 * millisPerDay; - public static final long millisPerYear = 365 * millisPerDay; - public static String getTimeDeltaDescriptionRelNow(long millis) - { - double absmillis = (double) Math.abs(millis); - String agofromnow = "from now"; - String unit; - long num; - if (millis <= 0) - { - agofromnow = "ago"; - } - - // We use a factor 3 below for a reason... why do you think? - // Answer: it is a way to make our round of error smaller. - if (absmillis < 3 * millisPerSecond) - { - unit = "milliseconds"; - num = (long) (absmillis); - } - else if (absmillis < 3 * millisPerMinute) - { - unit = "seconds"; - num = (long) (absmillis / millisPerSecond); - } - else if (absmillis < 3 * millisPerHour) - { - unit = "minutes"; - num = (long) (absmillis / millisPerMinute); - } - else if (absmillis < 3 * millisPerDay) - { - unit = "hours"; - num = (long) (absmillis / millisPerHour); - } - else if (absmillis < 3 * millisPerWeek) - { - unit = "days"; - num = (long) (absmillis / millisPerDay); - } - else if (absmillis < 3 * millisPerMonth) - { - unit = "weeks"; - num = (long) (absmillis / millisPerWeek); - } - else if (absmillis < 3 * millisPerYear) - { - unit = "months"; - num = (long) (absmillis / millisPerMonth); - } - else - { - unit = "years"; - num = (long) (absmillis / millisPerYear); - } - - return ""+num+" "+unit+" "+agofromnow; - } - - // -------------------------------------------- // - // String comparison - // -------------------------------------------- // - /*private static int commonStartLength(String a, String b) { int len = a.length() < b.length() ? a.length() : b.length(); @@ -295,31 +254,27 @@ public class TextUtil } return i; }*/ - - public static String getBestStartWithCI(Collection candidates, String start) - { - String ret = null; - int best = 0; - - start = start.toLowerCase(); - int minlength = start.length(); - for (String candidate : candidates) - { - if (candidate.length() < minlength) continue; - if ( ! candidate.toLowerCase().startsWith(start)) continue; - - // The closer to zero the better - int lendiff = candidate.length() - minlength; - if (lendiff == 0) - { - return candidate; - } - if (lendiff < best ||best == 0) - { - best = lendiff; - ret = candidate; - } - } - return ret; - } + + public static String getBestStartWithCI(Collection candidates, String start) { + String ret = null; + int best = 0; + + start = start.toLowerCase(); + int minlength = start.length(); + for (String candidate : candidates) { + if (candidate.length() < minlength) continue; + if (!candidate.toLowerCase().startsWith(start)) continue; + + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return candidate; + } + if (lendiff < best || best == 0) { + best = lendiff; + ret = candidate; + } + } + return ret; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/WorldUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/WorldUtil.java index 4e451cde..5778ee82 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/WorldUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/WorldUtil.java @@ -1,14 +1,13 @@ package com.massivecraft.factions.zcore.util; -import java.io.File; - import org.bukkit.Bukkit; -public class WorldUtil -{ - // Previously We had crappy support for multiworld management. - // This should however be handled by an external plugin! - /*public static boolean load(String name) { +import java.io.File; + +public class WorldUtil { + // Previously We had crappy support for multiworld management. + // This should however be handled by an external plugin! + /*public static boolean load(String name) { if (isWorldLoaded(name)) { return true; } @@ -26,14 +25,12 @@ public class WorldUtil P.p.getServer().createWorld(name, env); return true; }*/ - - public static boolean isWorldLoaded(String name) - { - return Bukkit.getServer().getWorld(name) != null; - } - - public static boolean doesWorldExist(String name) - { - return new File(name, "level.dat").exists(); - } + + public static boolean isWorldLoaded(String name) { + return Bukkit.getServer().getWorld(name) != null; + } + + public static boolean doesWorldExist(String name) { + return new File(name, "level.dat").exists(); + } }