Compare commits

...

84 Commits

Author SHA1 Message Date
Driftay
ce9038742f Code Optimizations 2020-06-09 06:28:34 -04:00
Driftay
7f927189ea Alts Can No Longer Be Promoted 2020-05-25 14:16:49 -04:00
Driftay
6f293dce17 Fixed Kicked Player Staying In Fly Map & FPerms GUI Returning Only Black Stained Glass Pane 2020-05-24 09:35:10 -04:00
Driftay
2676f048d6 Alt Limit Fix 2020-05-24 05:58:35 -04:00
Driftay
7e6646b4df Config Fix for default worlds 2020-05-19 06:28:05 -04:00
Driftay
0d08ff4cec Wild Updates 2020-05-19 06:27:20 -04:00
Driftay
cf3ce62023 Merge pull request #120 from SaberLLC/1.6.x
Merging
2020-05-19 06:25:42 -04:00
Driftay
30d6b3c248 Merge pull request #119 from SaberLLC/beta
F Show Async Calling
2020-05-19 06:24:02 -04:00
Driftay
c22e3a5227 F Show Async Calling 2020-05-19 06:22:09 -04:00
Driftay
cf71603eeb Merge pull request #117 from SaberLLC/beta
Beta
2020-05-18 04:31:06 -04:00
Driftay
c45b68a95f Merge pull request #116 from Aeris1One/patch-1
Fix
2020-05-18 04:29:42 -04:00
Aeris One
67a9a6db28 Update ja_JP.yml 2020-05-16 12:07:53 +02:00
DroppingAnvil
0ea56fe5d2 World now per range instead of global + CmdWild cleanup 2020-05-12 14:41:12 -05:00
DroppingAnvil
7d3c4d6e33 Merge pull request #115 from Stefan923/1.6.x
Fixed a JSON issue.
2020-05-11 16:47:08 -05:00
Stefan923
4d05b4a376 Fixed "RESET is not a style/color" error. 2020-05-10 17:18:48 +03:00
Driftay
c29850eaaa Fixes NPE on Saving Task onDisable MPlugin, removed Async Throw for 1.15 in F Show 2020-05-09 14:04:17 -04:00
Driftay
ece5dd0bb7 Merge pull request #113 from Stefan923/1.6.x
Fixed issues
2020-05-09 14:01:55 -04:00
Driftay
bbaee8ab06 Merge pull request #114 from Stefan923/1.6.x
Fixed issues
2020-05-09 13:39:51 -04:00
Stefan923
c42949ec59 Fixed a bug: people were able to move banned items in /f chest by using hotbar keys. 2020-05-09 17:37:06 +03:00
Stefan923
f5f8e6aad2 Edited some translation messages. 2020-05-09 16:22:16 +03:00
Stefan923
447bfedbb1 Fixed an internal error caused by some unhandled cases. 2020-05-09 15:51:14 +03:00
Stefan923
1d4a1c2a1a Avoid disabling player's flight mode if it's not enabled. 2020-05-09 14:53:53 +03:00
Stefan923
31b8f0be25 Fixed internal error caused by trying to demote a player who already has the lowest rank 2020-05-09 14:53:02 +03:00
Driftay
e2d85d83f3 Merge pull request #111 from Stefan923/1.6.x
Fixed AutoFly issue
2020-05-08 20:22:33 -04:00
Driftay
66f2fd22f6 Merge pull request #112 from SaberLLC/beta
Beta
2020-05-08 20:21:55 -04:00
Stefan923
842eb097c6 Fixed issue. If the player does not have the fly activated when he joins another teritory, it skips the checks and his flight is activated. 2020-05-09 00:30:03 +03:00
DroppingAnvil
2f18da3cfb Merge pull request #110 from Stefan923/1.6.x
Fixed issues
2020-05-08 15:57:02 -05:00
Stefan923
5fb8d06d98 Fixed the asynchronous command dispatch issue. The issue was being thrown on PaperSpigot and its forks. 2020-05-08 20:29:54 +03:00
Stefan923
868e7f4102 Method weren't formatting both color and style to the same text. 2020-05-08 20:27:03 +03:00
Popescu Ștefan
d8b08ef6d7 Merge pull request #1 from SaberLLC/beta
Beta
2020-05-07 23:06:20 +03:00
DroppingAnvil
7bffed2d34 Merge pull request #108 from Stefan923/1.6.x
Fixed an issue with disband GUI
2020-05-07 14:44:15 -05:00
BrowkS
541e1fc69b Fixed issue - ignoring "useDisbandGui" if the player is not an OP 2020-05-07 22:36:39 +03:00
Driftay
07dce634af Addressed Config Properly 2020-05-07 12:23:32 -04:00
Driftay
75faaa4bb5 More Radius Claiming Changes 2020-05-07 07:07:40 -04:00
Driftay
17e2a86717 Cleaned Up Double Message With Fly & Double Message With Radius Claim System When Claiming A Single Claim 2020-05-07 05:56:12 -04:00
Driftay
f384100925 Fixed Small Issue With Owner List In Replacement Of TL Translation 2020-05-07 05:26:08 -04:00
Driftay
b8c695c2f4 Grace Check in checkForExplosion Method & Added a Async Task On Show.
NOTE: Ran 100 Alts Running /f who every second whilst all being in my faction with 0 lag or errors with LuckPerms
2020-05-07 05:11:28 -04:00
Driftay
78a5e65e5c Merge pull request #106 from Stefan923/1.6.x
Fixed some internal errors caused by using /f wild and a placeholder issue
2020-05-07 01:57:05 -04:00
Driftay
33761fee2b Radius Claiming Finalized, Few Fixes With Econ & Essentials & Fly Performance 2020-05-07 01:55:24 -04:00
BrowkS
bf23521309 Sending join message to faction members after setting player's faction and role. 2020-05-06 22:32:40 +03:00
BrowkS
55fd5ffdfd Added {player-role} placeholder. 2020-05-06 13:07:16 +03:00
BrowkS
04273de995 Removed an unnecessary check 2020-05-06 12:36:24 +03:00
Stefan923
7fc1ad19ad Fixed an internal error. Trying to send a message without enough arguments. 2020-05-05 18:32:50 +03:00
Stefan923
01913e7286 Fixed an internal error. Player wasn't being removed from teleportRange after a failed teleportation. 2020-05-05 18:30:09 +03:00
Driftay
ae7bb670d7 Reverted Back To Old Fly Mechanics 2020-05-05 07:20:06 -04:00
Driftay
499d41dea0 Radius Claiming & Alt Limit Fix 2020-05-04 20:27:39 -04:00
DroppingAnvil
e0d2e6b4db Version change for fly changes 2020-04-30 14:40:59 -05:00
DroppingAnvil
e37745eff9 Fixed a few known issues with F Fly 2020-04-30 14:27:26 -05:00
DroppingAnvil
86cba0e24c PlaceholderAPI expansion revamp 2020-04-29 16:31:47 -05:00
droppinganvil
69a4651e23 Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-26 12:54:03 -05:00
DroppingAnvil
f2c6d0b9da Even more fly changes 2020-04-26 12:53:48 -05:00
Driftay
8f343a5344 FIXED MASSIVE BUG WITH SAVING 2020-04-21 21:39:28 -04:00
Driftay
8665d92476 FIXED MASSIVE BUG WITH SAVING 2020-04-21 20:25:44 -04:00
droppinganvil
b89db7b082 Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-21 16:04:39 -05:00
DroppingAnvil
00cb78fd9b Set a world for /f wild 2020-04-21 16:04:18 -05:00
Driftay
aca075b5c7 Version Change 2020-04-13 20:30:02 -04:00
Driftay
03886aa84e Merge pull request #92 from CanardConfit/1.6.x
Fix issue #84
2020-04-13 20:26:17 -04:00
CanardConfit
22472f63f1 Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-14 01:05:17 +02:00
CanardConfit
6d72e5d167 Fix issue #84 2020-04-14 01:04:33 +02:00
CanardConfit
69765e472c Fix issue #84 2020-04-14 01:01:05 +02:00
Driftay
4f55b10c7d Fixed Faction Claiming Over Themselves 2020-04-13 18:44:17 -04:00
Driftay
0395280a9e Addressed Issue #72 2020-04-13 16:12:46 -04:00
Driftay
d1252df3ba Addressed Issue: 70 Some Blocks may be missing, but they are 100% configurable in conf.json I don't want to hardcode item names that people want to block by default. ex: crafting tables 2020-04-13 15:28:37 -04:00
Driftay
9707226762 Addressed Issue: #90 & Added Configurable removePlayerDataWhenBanned message 2020-04-13 15:20:46 -04:00
Driftay
cf075c270e Addressed Issue: #81 2020-04-13 13:35:27 -04:00
Driftay
f088b42bbe Added uneeded comment 2020-04-13 13:29:01 -04:00
Driftay
baee5d2158 Addressed Issue: #77 & #68 2020-04-13 13:24:30 -04:00
Driftay
f871787b0c Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-13 13:18:27 -04:00
Driftay
749fca0690 Merge pull request #91 from CanardConfit/1.6.x
Fix Issue #75
2020-04-13 13:17:59 -04:00
CanardConfit
319940d9b3 Fix Issue #75 2020-04-13 19:12:11 +02:00
Driftay
7ea81a6c10 Addressed Issue: https://github.com/SaberLLC/Saber-Factions/issues/69 2020-04-13 13:09:15 -04:00
Driftay
6205bbca9f Added a bunch of fixes from github requests 2020-04-13 05:03:41 -04:00
Driftay
241a16bc2a Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-12 06:26:45 -04:00
Driftay
3aa98121e5 Factions Fly Cache on Startup, Attempt At SaveSync Fix 2020-04-12 06:26:27 -04:00
DroppingAnvil
144798b2dd Fixed message given to WaitExecutor causing F Wild to constantly say "You are already teleporting somewhere" 2020-04-11 15:02:17 -05:00
droppinganvil
dac07178e5 Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-11 14:52:12 -05:00
DroppingAnvil
f8421c09cf Option to load chunk before /f wild teleport. 2020-04-11 14:51:57 -05:00
Driftay
932a5768b0 Fixed Small NPE With Grace if GraceSystem was set to false 2020-04-09 17:53:05 -04:00
droppinganvil
861f88a916 Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-08 12:59:51 -05:00
DroppingAnvil
5b7f3b0f0e Fixed fly no permission issue 2020-04-08 12:59:41 -05:00
Driftay
304662fa9b Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-08 09:19:14 -04:00
Driftay
5a6c660f7f Fixed Small Error With Money Format If Econ is Off 2020-04-08 09:18:50 -04:00
Driftay
0fc736cdf5 Update README.md 2020-04-08 06:22:34 -04:00
Driftay
ef7db546a3 Update README.md 2020-04-08 06:22:14 -04:00
105 changed files with 1097 additions and 1462 deletions

View File

@@ -1,6 +1,7 @@
# SaberFactions # SaberFactions
![Downloads](https://img.shields.io/github/downloads/driftay/saber-factions/total.svg) [![CodeFactor](https://www.codefactor.io/repository/github/driftay/saber-factions/badge)](https://www.codefactor.io/repository/github/driftay/saber-factions) [![License](https://img.shields.io/badge/license-GNU%20General%20Public%20License%20v3.0-brightgreen)](https://github.com/SaberLLC/Saber-Factions/blob/1.6.x/LICENSE) ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/SaberLLC/Saber-Factions) ![Downloads](https://img.shields.io/github/downloads/driftay/saber-factions/total.svg) [![CodeFactor](https://www.codefactor.io/repository/github/driftay/saber-factions/badge)](https://www.codefactor.io/repository/github/driftay/saber-factions) [![License](https://img.shields.io/badge/license-GNU%20General%20Public%20License%20v3.0-brightgreen)](https://github.com/SaberLLC/Saber-Factions/blob/1.6.x/LICENSE) ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/SaberLLC/Saber-Factions) [![](https://jitpack.io/v/SaberLLC/Saber-Factions.svg)](https://jitpack.io/#SaberLLC/Saber-Factions)
SaberFactions is an exotic, performance optimized, and feature rich factions plugin that focuses on not only making the player experience as great as possibly but maintaining this aspect with the cost of NOTHING! We strive to continue development for SaberFactions as the factions community is strongly growing and seeking new players every day. SaberFactions is an exotic, performance optimized, and feature rich factions plugin that focuses on not only making the player experience as great as possibly but maintaining this aspect with the cost of NOTHING! We strive to continue development for SaberFactions as the factions community is strongly growing and seeking new players every day.
@@ -32,7 +33,7 @@ Some of our features include the following
<dependency> <dependency>
<groupId>com.github.SaberLLC</groupId> <groupId>com.github.SaberLLC</groupId>
<artifactId>Saber-Factions</artifactId> <artifactId>Saber-Factions</artifactId>
<version>2.2.7-STABLE</version> <version>2.3.3-STABLE</version>
</dependency> </dependency>
``` ```
## Moving Forward ## Moving Forward

View File

@@ -4,7 +4,7 @@
<groupId>com.massivecraft</groupId> <groupId>com.massivecraft</groupId>
<artifactId>Factions</artifactId> <artifactId>Factions</artifactId>
<version>1.6.9.5-2.3.3-RC</version> <version>1.6.9.5-2.3.7-RC</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>SaberFactions</name> <name>SaberFactions</name>
@@ -108,7 +108,7 @@
<dependency> <dependency>
<groupId>com.github.stefvanschie.inventoryframework</groupId> <groupId>com.github.stefvanschie.inventoryframework</groupId>
<artifactId>IF</artifactId> <artifactId>IF</artifactId>
<version>0.5.8</version> <version>0.5.19</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>

View File

@@ -98,10 +98,14 @@ public class Conf {
public static double autoLeaveRoutineRunsEveryXMinutes = 5.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 int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick
public static boolean removePlayerDataWhenBanned = true; public static boolean removePlayerDataWhenBanned = true;
public static String removePlayerDataWhenBannedReason = "Banned by admin.";
public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction.
public static boolean worldGuardChecking = false; public static boolean worldGuardChecking = false;
public static boolean worldGuardBuildPriority = false; public static boolean worldGuardBuildPriority = false;
//RADIUS CLAIMING
public static boolean useRadiusClaimSystem = true;
//FRIENDLY FIRE //FRIENDLY FIRE
public static boolean friendlyFireFPlayersCommand = false; public static boolean friendlyFireFPlayersCommand = false;
@@ -122,7 +126,7 @@ public class Conf {
public static boolean useDisbandGUI = true; public static boolean useDisbandGUI = true;
//SEALTH //SEALTH
public static boolean useSealthSystem = true; public static boolean useStealthSystem = true;
//STRIKES //STRIKES
public static boolean useStrikeSystem = true; public static boolean useStrikeSystem = true;
@@ -264,7 +268,6 @@ public class Conf {
public static boolean ownedMessageInsideTerritory = true; public static boolean ownedMessageInsideTerritory = true;
public static boolean ownedMessageByChunk = false; public static boolean ownedMessageByChunk = false;
public static boolean pistonProtectionThroughDenyBuild = true; public static boolean pistonProtectionThroughDenyBuild = true;
public static Set<Material> loggableMaterials = EnumSet.noneOf(Material.class);
public static Set<Material> territoryProtectedMaterials = EnumSet.noneOf(Material.class); public static Set<Material> territoryProtectedMaterials = EnumSet.noneOf(Material.class);
public static Set<Material> territoryDenyUsageMaterials = EnumSet.noneOf(Material.class); public static Set<Material> territoryDenyUsageMaterials = EnumSet.noneOf(Material.class);
public static Set<Material> territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); public static Set<Material> territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class);
@@ -275,8 +278,7 @@ public class Conf {
/// Useful for HCF features. /// Useful for HCF features.
/// </summary> /// </summary>
public static Set<Material> territoryBypassProtectedMaterials = EnumSet.noneOf(Material.class); public static Set<Material> territoryBypassProtectedMaterials = EnumSet.noneOf(Material.class);
// Dependency check
public static boolean dependencyCheck = true;
public static boolean enableClickToClaim = true; public static boolean enableClickToClaim = true;
public static Set<Material> territoryCancelAndAllowItemUseMaterial = new HashSet<>(); public static Set<Material> territoryCancelAndAllowItemUseMaterial = new HashSet<>();
@@ -423,6 +425,10 @@ public class Conf {
public static HashMap<String, DefaultPermissions> defaultFactionPermissions = new HashMap<>(); public static HashMap<String, DefaultPermissions> defaultFactionPermissions = new HashMap<>();
public static HashSet<PermissableAction> lockedPermissions = new HashSet<>(); public static HashSet<PermissableAction> lockedPermissions = new HashSet<>();
public static boolean useComplexFly = true;
public static boolean wildLoadChunkBeforeTeleport = true;
private static transient Conf i = new Conf(); private static transient Conf i = new Conf();
static { static {
@@ -553,7 +559,6 @@ public class Conf {
territoryDenyUsageMaterials.add(Material.ARMOR_STAND); territoryDenyUsageMaterials.add(Material.ARMOR_STAND);
} }
territoryProtectedMaterialsWhenOffline.add(Material.BEACON); territoryProtectedMaterialsWhenOffline.add(Material.BEACON);
territoryDenyUsageMaterialsWhenOffline.add(XMaterial.FIRE_CHARGE.parseMaterial()); territoryDenyUsageMaterialsWhenOffline.add(XMaterial.FIRE_CHARGE.parseMaterial());

View File

@@ -21,7 +21,6 @@ import com.massivecraft.factions.integration.Worldguard;
import com.massivecraft.factions.integration.dynmap.EngineDynmap; import com.massivecraft.factions.integration.dynmap.EngineDynmap;
import com.massivecraft.factions.listeners.*; import com.massivecraft.factions.listeners.*;
import com.massivecraft.factions.missions.MissionHandler; import com.massivecraft.factions.missions.MissionHandler;
import com.massivecraft.factions.struct.ChatMode;
import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.*; import com.massivecraft.factions.util.*;
@@ -39,15 +38,15 @@ import me.lucko.commodore.CommodoreProvider;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission; import net.milkbowl.vault.permission.Permission;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.*; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
@@ -66,6 +65,7 @@ public class FactionsPlugin extends MPlugin {
// Our single plugin instance. // Our single plugin instance.
// Single 4 life. // Single 4 life.
public static FactionsPlugin instance; public static FactionsPlugin instance;
public static boolean cachedRadiusClaim;
public static Permission perms = null; public static Permission perms = null;
// This plugin sets the boolean true when fully enabled. // This plugin sets the boolean true when fully enabled.
// Plugins can check this boolean while hooking in have // Plugins can check this boolean while hooking in have
@@ -82,7 +82,6 @@ public class FactionsPlugin extends MPlugin {
public boolean mc114 = false; public boolean mc114 = false;
public boolean mc115 = false; public boolean mc115 = false;
public boolean useNonPacketParticles = false; public boolean useNonPacketParticles = false;
public boolean factionsFlight = false;
public List<String> itemList = getConfig().getStringList("fchest.Items-Not-Allowed"); public List<String> itemList = getConfig().getStringList("fchest.Items-Not-Allowed");
SkriptAddon skriptAddon; SkriptAddon skriptAddon;
private FactionsPlayerListener factionsPlayerListener; private FactionsPlayerListener factionsPlayerListener;
@@ -129,28 +128,20 @@ public class FactionsPlugin extends MPlugin {
this.setAutoSave(val); this.setAutoSave(val);
} }
public void playSoundForAll(String sound) {
for (Player pl : Bukkit.getOnlinePlayers()) playSound(pl, sound);
}
public void playSoundForAll(List<String> sounds) {
for (Player pl : Bukkit.getOnlinePlayers()) playSound(pl, sounds);
}
public void playSound(Player p, List<String> sounds) {
for (String sound : sounds) playSound(p, sound);
}
public void playSound(Player p, String sound) {
float pitch = Float.parseFloat(sound.split(":")[1]);
sound = sound.split(":")[0];
p.playSound(p.getLocation(), Sound.valueOf(sound), pitch, 5.0F);
}
@Override @Override
public void onEnable() { public void onEnable() {
log("==== Setup ===="); log("==== Setup ====");
if (getServer().getPluginManager().getPlugin("Vault") == null) {
divider();
System.out.println("You are missing dependencies!");
System.out.println("Please verify [Vault] is installed!");
Conf.save();
Bukkit.getPluginManager().disablePlugin(instance);
divider();
return;
}
int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]);
switch (version) { switch (version) {
case 7: case 7:
@@ -176,42 +167,31 @@ public class FactionsPlugin extends MPlugin {
FactionsPlugin.instance.log("Minecraft Version 1.15 found."); FactionsPlugin.instance.log("Minecraft Version 1.15 found.");
mc115 = true; mc115 = true;
break; break;
default:
throw new IllegalStateException("Unexpected value: " + version);
} }
migrateFPlayerLeaders(); migrateFPlayerLeaders();
log("==== End Setup ===="); log("==== End Setup ====");
int pluginId = 7013; int pluginId = 7013;
Metrics metrics = new Metrics(this, pluginId); new Metrics(this, pluginId);
if (!preEnable()) {
if (!preEnable()) return; this.loadSuccessful = false;
this.loadSuccessful = false; return;
if (!new File(this.getDataFolder() + "/config.yml").exists()) {
this.saveResource("config.yml", false);
this.reloadConfig();
} }
saveDefaultConfig();
//Start wait task executor //Start wait task executor
WaitExecutor.startTask(); WaitExecutor.startTask();
// Load Conf from disk // Load Conf from disk
fileManager = new FileManager();
getFileManager().setupFiles();
Conf.load(); Conf.load();
fileManager = new FileManager();
fileManager.setupFiles();
fLogManager = new FLogManager(); fLogManager = new FLogManager();
//Dependency checks
if (Conf.dependencyCheck && (!Bukkit.getPluginManager().isPluginEnabled("Vault"))) {
divider();
System.out.println("You are missing dependencies!");
System.out.println("Please verify [Vault] is installed!");
Conf.save();
Bukkit.getPluginManager().disablePlugin(instance);
divider();
return;
}
//Update their config if needed
// Updater.updateIfNeeded(getConfig());
RegisteredServiceProvider<Economy> rsp = FactionsPlugin.this.getServer().getServicesManager().getRegistration(Economy.class);
com.massivecraft.factions.integration.Essentials.setup(); com.massivecraft.factions.integration.Essentials.setup();
hookedPlayervaults = setupPlayervaults(); hookedPlayervaults = setupPlayervaults();
FPlayers.getInstance().load(); FPlayers.getInstance().load();
@@ -228,6 +208,12 @@ public class FactionsPlugin extends MPlugin {
else faction.addFPlayer(fPlayer); else faction.addFPlayer(fPlayer);
} }
Factions.getInstance().getAllFactions().forEach(Faction::refreshFPlayers);
if (getConfig().getBoolean("enable-faction-flight", true)) {
UtilFly.run();
}
Board.getInstance().load(); Board.getInstance().load();
Board.getInstance().clean(); Board.getInstance().clean();
@@ -247,15 +233,15 @@ public class FactionsPlugin extends MPlugin {
// start up task which runs the autoLeaveAfterDaysOfInactivity routine // start up task which runs the autoLeaveAfterDaysOfInactivity routine
startAutoLeaveTask(false); startAutoLeaveTask(false);
cachedRadiusClaim = Conf.useRadiusClaimSystem;
if (version > 8) { if (version > 8) {
useNonPacketParticles = true; useNonPacketParticles = true;
log("Minecraft Version 1.9 or higher found, using non packet based particle API"); log("Minecraft Version 1.9 or higher found, using non packet based particle API");
} }
if (getConfig().getBoolean("enable-faction-flight")) factionsFlight = true;
if (getServer().getPluginManager().getPlugin("Skript") != null) { if (getServer().getPluginManager().getPlugin("Skript") != null) {
log("Skript was found! Registering FactionsPlugin Addon..."); log("Skript was found! Registering SaberFactions Addon...");
skriptAddon = Skript.registerAddon(this); skriptAddon = Skript.registerAddon(this);
try { try {
skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions"); skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions");
@@ -264,6 +250,7 @@ public class FactionsPlugin extends MPlugin {
} }
log("Skript addon registered!"); log("Skript addon registered!");
} }
if (Conf.useCheckSystem) { if (Conf.useCheckSystem) {
int minute = 1200; int minute = 1200;
this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 3), 0L, minute * 3); this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 3), 0L, minute * 3);
@@ -295,16 +282,20 @@ public class FactionsPlugin extends MPlugin {
new MissionHandler(this), new MissionHandler(this),
new FChestListener(), new FChestListener(),
new MenuListener(), new MenuListener(),
timerManager.graceTimer,
new AntiChestListener() new AntiChestListener()
}; };
for (Listener eventListener : eventsListener) for (Listener eventListener : eventsListener)
getServer().getPluginManager().registerEvents(eventListener, this); getServer().getPluginManager().registerEvents(eventListener, this);
if (Conf.useGraceSystem) {
getServer().getPluginManager().registerEvents(timerManager.graceTimer, this);
}
this.getCommand(refCommand).setExecutor(cmdBase); this.getCommand(refCommand).setExecutor(cmdBase);
if (!CommodoreProvider.isSupported()) this.getCommand(refCommand).setTabCompleter(this); if (!CommodoreProvider.isSupported()) this.getCommand(refCommand).setTabCompleter(this);
reserveObjects = new ArrayList<>(); reserveObjects = new ArrayList<>();
String path = Paths.get(this.getDataFolder().getAbsolutePath()).toAbsolutePath().toString() + File.separator + "reserves.json"; String path = Paths.get(this.getDataFolder().getAbsolutePath()).toAbsolutePath().toString() + File.separator + "reserves.json";
File file = new File(path); File file = new File(path);
@@ -340,10 +331,6 @@ public class FactionsPlugin extends MPlugin {
FactionsPlugin.startupFinished = true; FactionsPlugin.startupFinished = true;
} }
public SkriptAddon getSkriptAddon() {
return skriptAddon;
}
private void setupPlaceholderAPI() { private void setupPlaceholderAPI() {
Plugin clip = getServer().getPluginManager().getPlugin("PlaceholderAPI"); Plugin clip = getServer().getPluginManager().getPlugin("PlaceholderAPI");
@@ -409,14 +396,12 @@ public class FactionsPlugin extends MPlugin {
return this.mvdwPlaceholderAPIManager; return this.mvdwPlaceholderAPIManager;
} }
private boolean setupPermissions() { private void setupPermissions() {
try { try {
RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class); RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
if (rsp != null) perms = rsp.getProvider(); if (rsp != null) perms = rsp.getProvider();
} catch (NoClassDefFoundError ex) { } catch (NoClassDefFoundError ignored) {
return false;
} }
return perms != null;
} }
private boolean setupPlayervaults() { private boolean setupPlayervaults() {
@@ -450,8 +435,19 @@ public class FactionsPlugin extends MPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
super.onDisable(); if (this.AutoLeaveTask != null) {
getServer().getScheduler().cancelTask(this.AutoLeaveTask);
this.AutoLeaveTask = null;
}
Conf.saveSync();
timerManager.saveTimerData(); timerManager.saveTimerData();
DiscordListener.saveGuilds();
if (Discord.jda != null) Discord.jda.shutdownNow();
fLogManager.saveLogs();
try { try {
String path = Paths.get(getDataFolder().getAbsolutePath()).toAbsolutePath().toString() + File.separator + "reserves.json"; String path = Paths.get(getDataFolder().getAbsolutePath()).toAbsolutePath().toString() + File.separator + "reserves.json";
File file = new File(path); File file = new File(path);
@@ -464,23 +460,7 @@ public class FactionsPlugin extends MPlugin {
e.printStackTrace(); e.printStackTrace();
} }
// only save data if plugin actually completely loaded successfully super.onDisable();
if (this.loadSuccessful) Conf.saveSync();
if (AutoLeaveTask != null) {
this.getServer().getScheduler().cancelTask(AutoLeaveTask);
AutoLeaveTask = null;
}
DiscordListener.saveGuilds();
if (Discord.jda != null) {
Discord.jda.shutdownNow();
}
try {
fLogManager.saveLogs();
} catch (Exception e) {
e.printStackTrace();
}
} }
public void startAutoLeaveTask(boolean restartIfRunning) { public void startAutoLeaveTask(boolean restartIfRunning) {
@@ -501,26 +481,9 @@ public class FactionsPlugin extends MPlugin {
Conf.save(); Conf.save();
} }
public ItemStack createItem(Material material, int amount, short datavalue, String name, List<String> lore) {
ItemStack item = new ItemStack(XMaterial.matchXMaterial(material.toString()).get().parseMaterial(), amount, datavalue);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(color(name));
meta.setLore(colorList(lore));
item.setItemMeta(meta);
return item;
}
public ItemStack createLazyItem(Material material, int amount, short datavalue, String name, String lore) {
ItemStack item = new ItemStack(material, amount, datavalue);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(color(FactionsPlugin.instance.getConfig().getString(name)));
meta.setLore(colorList(FactionsPlugin.instance.getConfig().getStringList(lore)));
item.setItemMeta(meta);
return item;
}
public Economy getEcon() { public Economy getEcon() {
RegisteredServiceProvider<Economy> rsp = FactionsPlugin.instance.getServer().getServicesManager().getRegistration(Economy.class); RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
return rsp.getProvider(); return rsp.getProvider();
} }
@@ -545,7 +508,6 @@ public class FactionsPlugin extends MPlugin {
List<FCommand> commandsList = cmdBase.subCommands; List<FCommand> commandsList = cmdBase.subCommands;
FCommand commandsEx = cmdBase; FCommand commandsEx = cmdBase;
List<String> completions = new ArrayList<>(); List<String> completions = new ArrayList<>();
// Check for "" first arg because spigot is mangled. // Check for "" first arg because spigot is mangled.
if (context.args.get(0).equals("")) { if (context.args.get(0).equals("")) {
for (FCommand subCommand : commandsEx.subCommands) { for (FCommand subCommand : commandsEx.subCommands) {
@@ -593,70 +555,11 @@ public class FactionsPlugin extends MPlugin {
// 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;
}
// If another plugin is handling insertion of chat tags, this should be used to notify Factions // If another plugin is handling insertion of chat tags, this should be used to notify Factions
public void handleFactionTagExternally(boolean notByFactions) { public void handleFactionTagExternally(boolean notByFactions) {
Conf.chatTagHandledByAnotherPlugin = 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()
public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) {
return event != null && (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.getInstance().getByPlayer(player);
return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE);
}
// 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) {
return !(check == null || check.isEmpty()) && this.handleCommand(null, check, true);
}
// 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);
}
// Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag
public String getPlayerFactionTagRelation(Player speaker, Player listener) {
String tag = "~";
if (speaker == null) return tag;
FPlayer me = FPlayers.getInstance().getByPlayer(speaker);
if (me == null) return tag;
// 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.getInstance().getByPlayer(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 tag;
}
public FLogManager getFlogManager() { public FLogManager getFlogManager() {
return fLogManager; return fLogManager;
} }
@@ -665,14 +568,6 @@ public class FactionsPlugin extends MPlugin {
this.fLogManager.log(faction, type, arguments); this.fLogManager.log(faction, type, arguments);
} }
// 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.getInstance().getByPlayer(player);
if (me == null) return "";
return me.getTitle().trim();
}
public String color(String line) { public String color(String line) {
line = ChatColor.translateAlternateColorCodes('&', line); line = ChatColor.translateAlternateColorCodes('&', line);
return line; return line;
@@ -684,38 +579,10 @@ public class FactionsPlugin extends MPlugin {
return lore; return lore;
} }
// Get a list of all faction tags (names)
public Set<String> getFactionTags() {
return Factions.getInstance().getFactionTags();
}
public List<ReserveObject> getFactionReserves() { public List<ReserveObject> getFactionReserves() {
return this.reserveObjects; return this.reserveObjects;
} }
// Get a list of all players in the specified faction
public Set<String> getPlayersInFaction(String factionTag) {
Set<String> players = new HashSet<>();
Faction faction = Factions.getInstance().getByTag(factionTag);
if (faction != null) {
for (FPlayer fplayer : faction.getFPlayers()) players.add(fplayer.getName());
}
return players;
}
// Get a list of all online players in the specified faction
public Set<String> getOnlinePlayersInFaction(String factionTag) {
Set<String> players = new HashSet<>();
Faction faction = Factions.getInstance().getByTag(factionTag);
if (faction != null) {
for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) players.add(fplayer.getName());
}
return players;
}
public boolean isHookedPlayervaults() {
return hookedPlayervaults;
}
public String getPrimaryGroup(OfflinePlayer player) { public String getPrimaryGroup(OfflinePlayer player) {
return perms == null || !perms.hasGroupSupport() ? " " : perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player); return perms == null || !perms.hasGroupSupport() ? " " : perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player);
@@ -737,7 +604,4 @@ public class FactionsPlugin extends MPlugin {
debug(Level.INFO, s); debug(Level.INFO, s);
} }
public Worldguard getWg() {
return wg;
}
} }

View File

@@ -57,6 +57,10 @@ public class CmdAdmin extends FCommand {
return; return;
} }
if(fyou.isAlt()){
return;
}
// only perform a FPlayerJoinEvent when newLeader isn't actually in the faction // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction
if (fyou.getFaction() != targetFaction) { if (fyou.getFaction() != targetFaction) {
FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER);
@@ -86,24 +90,20 @@ public class CmdAdmin extends FCommand {
FactionsPlugin.instance.getFlogManager().log(targetFaction, FLogType.RANK_EDIT, context.fPlayer.getName(), fyou.getName(), ChatColor.RED + "Admin"); FactionsPlugin.instance.getFlogManager().log(targetFaction, FLogType.RANK_EDIT, context.fPlayer.getName(), fyou.getName(), ChatColor.RED + "Admin");
// Inform all players // Inform all players
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { if(FactionsPlugin.instance.getConfig().getBoolean("faction-leader-broadcast")) {
fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) {
context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer));
fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); }
} }
}); });
} }
private void setRole(FPlayer fp, Role r) { private void setRole(FPlayer fp, Role r) {
FactionsPlugin.getInstance().getServer().getScheduler().runTask(FactionsPlugin.instance, () -> { FactionsPlugin.getInstance().getServer().getScheduler().runTask(FactionsPlugin.instance, () -> fp.setRole(r));
fp.setRole(r);
});
} }
private void promoteNewLeader(Faction f) { private void promoteNewLeader(Faction f) {
FactionsPlugin.getInstance().getServer().getScheduler().runTask(FactionsPlugin.instance, () -> { FactionsPlugin.getInstance().getServer().getScheduler().runTask(FactionsPlugin.instance, (Runnable) f::promoteNewLeader);
f.promoteNewLeader();
});
} }
public TL getUsageTranslation() { public TL getUsageTranslation() {

View File

@@ -50,7 +50,7 @@ public class CmdAnnounce extends FCommand {
return TL.COMMAND_ANNOUNCE_DESCRIPTION; return TL.COMMAND_ANNOUNCE_DESCRIPTION;
} }
protected class AnnounceBrigadier implements BrigadierProvider { protected static class AnnounceBrigadier implements BrigadierProvider {
@Override @Override
public ArgumentBuilder<Object, ?> get(ArgumentBuilder<Object, ?> parent) { public ArgumentBuilder<Object, ?> get(ArgumentBuilder<Object, ?> parent) {
return parent.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString())); return parent.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString()));

View File

@@ -60,7 +60,6 @@ public class CmdBanner extends FCommand {
@Deprecated @Deprecated
public void takeMoney(FPlayer fme, int amt) { public void takeMoney(FPlayer fme, int amt) {
if (this.hasMoney(fme, amt)) { if (this.hasMoney(fme, amt)) {
Economy econ = FactionsPlugin.getInstance().getEcon();
fme.sendMessage(TL.COMMAND_BANNER_MONEYTAKE.toString().replace("{amount}", amt + "")); fme.sendMessage(TL.COMMAND_BANNER_MONEYTAKE.toString().replace("{amount}", amt + ""));
} }
} }

View File

@@ -14,7 +14,6 @@ public class CmdBoom extends FCommand {
super(); super();
this.aliases.addAll(Aliases.boom); this.aliases.addAll(Aliases.boom);
//this.requiredArgs.add("");
this.optionalArgs.put("on/off", "flip"); this.optionalArgs.put("on/off", "flip");
this.requirements = new CommandRequirements.Builder(Permission.NO_BOOM) this.requirements = new CommandRequirements.Builder(Permission.NO_BOOM)

View File

@@ -14,7 +14,6 @@ public class CmdBypass extends FCommand {
super(); super();
this.aliases.addAll(Aliases.bypass); this.aliases.addAll(Aliases.bypass);
//this.requiredArgs.add("");
this.optionalArgs.put("on/off", "flip"); this.optionalArgs.put("on/off", "flip");
this.requirements = new CommandRequirements.Builder(Permission.BYPASS) this.requirements = new CommandRequirements.Builder(Permission.BYPASS)

View File

@@ -18,7 +18,6 @@ public class CmdChat extends FCommand {
super(); super();
this.aliases.addAll(Aliases.chat); this.aliases.addAll(Aliases.chat);
//this.requiredArgs.add("");
this.optionalArgs.put("mode", "next"); this.optionalArgs.put("mode", "next");
this.requirements = new CommandRequirements.Builder(Permission.CHAT) this.requirements = new CommandRequirements.Builder(Permission.CHAT)
@@ -86,7 +85,7 @@ public class CmdChat extends FCommand {
return TL.COMMAND_CHAT_DESCRIPTION; return TL.COMMAND_CHAT_DESCRIPTION;
} }
protected class ChatBrigadier implements BrigadierProvider { protected static class ChatBrigadier implements BrigadierProvider {
@Override @Override
public ArgumentBuilder<Object, ?> get(ArgumentBuilder<Object, ?> parent) { public ArgumentBuilder<Object, ?> get(ArgumentBuilder<Object, ?> parent) {
return parent.then(LiteralArgumentBuilder.literal("public")) return parent.then(LiteralArgumentBuilder.literal("public"))

View File

@@ -35,11 +35,10 @@ public class CmdCheckpoint extends FCommand {
if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) {
context.faction.setCheckpoint(context.player.getLocation()); context.faction.setCheckpoint(context.player.getLocation());
context.msg(TL.COMMAND_CHECKPOINT_SET); context.msg(TL.COMMAND_CHECKPOINT_SET);
return;
} else { } else {
context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION);
return;
} }
return;
} }
if (context.faction.getCheckpoint() == null) { if (context.faction.getCheckpoint() == null) {
context.msg(TL.COMMAND_CHECKPOINT_NOT_SET); context.msg(TL.COMMAND_CHECKPOINT_NOT_SET);

View File

@@ -55,6 +55,10 @@ public class CmdColeader extends FCommand {
return; return;
} }
if(you.isAlt()){
return;
}
if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) {
context.msg(TL.COMMAND_COLEADER_NOTADMIN); context.msg(TL.COMMAND_COLEADER_NOTADMIN);
return; return;

View File

@@ -66,7 +66,7 @@ public class CmdCreate extends FCommand {
} }
ArrayList<String> tagValidationErrors = MiscUtil.validateTag(tag); ArrayList<String> tagValidationErrors = MiscUtil.validateTag(tag);
if (tagValidationErrors.size() > 0) { if (tagValidationErrors.isEmpty()) {
context.sendMessage(tagValidationErrors); context.sendMessage(tagValidationErrors);
return; return;
} }

View File

@@ -25,36 +25,17 @@ public class CmdDeinvite extends FCommand {
this.optionalArgs.put("player name", "name"); this.optionalArgs.put("player name", "name");
this.requirements = new CommandRequirements.Builder(Permission.DEINVITE) this.requirements = new CommandRequirements.Builder(Permission.DEINVITE)
.withAction(PermissableAction.INVITE)
.memberOnly() .memberOnly()
.build(); .build();
} }
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
if (context.args.size() == 0) {
FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD);
for (String id : context.faction.getInvites()) {
FPlayer fp = FPlayers.getInstance().getById(id);
String name = fp != null ? fp.getName() : id;
msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name);
}
context.sendFancyMessage(msg);
return;
}
FPlayer you = context.argAsBestFPlayerMatch(0); FPlayer you = context.argAsBestFPlayerMatch(0);
if (!context.fPlayer.isAdminBypassing()) {
Access access = context.faction.getAccess(context.fPlayer, PermissableAction.INVITE);
if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) {
context.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites");
return;
}
}
if (you == null) { if (you == null) {
FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD);
for (String id : context.faction.getInvites()) { for (String id : context.faction.getInvites()) {
if (context.faction.getInvites().isEmpty()) return;
FPlayer fp = FPlayers.getInstance().getById(id); FPlayer fp = FPlayers.getInstance().getById(id);
String name = fp != null ? fp.getName() : id; String name = fp != null ? fp.getName() : id;
msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name);
@@ -65,15 +46,16 @@ public class CmdDeinvite extends FCommand {
if (you.getFaction() == context.faction) { if (you.getFaction() == context.faction) {
context.msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), context.faction.getTag()); context.msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), context.faction.getTag());
context.msg(TL.COMMAND_DEINVITE_MIGHTWANT, FactionsPlugin.getInstance().cmdBase.cmdKick.getUsageTemplate(context)); context.msg(TL.COMMAND_DEINVITE_MIGHTWANT, FCmdRoot.instance.cmdKick.getUsageTemplate(context));
return; return;
} }
context.faction.deinvite(you); context.faction.deinvite(you);
you.msg(TL.COMMAND_DEINVITE_REVOKED, context.fPlayer.describeTo(you), context.faction.describeTo(you)); you.msg(TL.COMMAND_DEINVITE_REVOKED, context.fPlayer.describeTo(you), context.faction.describeTo(you));
context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction)); context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction));
} }
@Override @Override
public TL getUsageTranslation() { public TL getUsageTranslation() {
return TL.COMMAND_DEINVITE_DESCRIPTION; return TL.COMMAND_DEINVITE_DESCRIPTION;

View File

@@ -39,7 +39,7 @@ public class CmdDescription extends FCommand {
// since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up
// And replace all the % because it messes with string formatting and this is easy way around that. // And replace all the % because it messes with string formatting and this is easy way around that.
String desc = TextUtil.implode(context.args, " ").replaceAll("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2"); String desc = TextUtil.implode(context.args, " ").replace("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2");
context.faction.setDescription(desc); context.faction.setDescription(desc);
Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> FactionsPlugin.instance.logFactionEvent(context.faction, FLogType.FDESC_EDIT, context.fPlayer.getName(), desc)); Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> FactionsPlugin.instance.logFactionEvent(context.faction, FLogType.FDESC_EDIT, context.fPlayer.getName(), desc));
if (!Conf.broadcastDescriptionChanges) { if (!Conf.broadcastDescriptionChanges) {

View File

@@ -42,8 +42,8 @@ public class CmdDisband extends FCommand {
boolean isMyFaction = context.fPlayer != null && faction == context.faction; boolean isMyFaction = context.fPlayer != null && faction == context.faction;
if (!isMyFaction) { if (!isMyFaction && !Permission.DISBAND_ANY.has(context.sender, true)) {
if (!Permission.DISBAND_ANY.has(context.sender, true)) return; return;
} }
@@ -70,7 +70,7 @@ public class CmdDisband extends FCommand {
return; return;
} }
if(Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "disbandCooldown") && !context.fPlayer.isAdminBypassing()){ if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "disbandCooldown") && !context.fPlayer.isAdminBypassing()) {
context.msg(TL.COMMAND_COOLDOWN); context.msg(TL.COMMAND_COOLDOWN);
return; return;
} }
@@ -81,13 +81,9 @@ public class CmdDisband extends FCommand {
access = true; access = true;
} }
if (!access) { if (!access && Conf.useDisbandGUI && (!context.fPlayer.isAdminBypassing() || !context.player.isOp()) && !disbandMap.containsKey(context.player.getUniqueId().toString())) {
if (Conf.useDisbandGUI && !context.fPlayer.isAdminBypassing() || !context.player.isOp()) { new FDisbandFrame(context.faction).buildGUI(context.fPlayer);
if (!disbandMap.containsKey(context.player.getUniqueId().toString())) { return;
new FDisbandFrame(context.faction).buildGUI(context.fPlayer);
return;
}
}
} }
// check for tnt before disbanding. // check for tnt before disbanding.
@@ -101,27 +97,15 @@ public class CmdDisband extends FCommand {
String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower); String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower);
if (follower.getFaction() == faction) { if (follower.getFaction() == faction) {
follower.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, amountString); follower.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, amountString);
if (!follower.canFlyAtLocation() && FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) {
follower.setFFlying(false, false);
}
} else { } else {
follower.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, amountString, faction.getTag(follower)); follower.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, amountString, faction.getTag(follower));
} }
} }
if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) {
faction.disband(context.player, PlayerDisbandReason.COMMAND);
context.fPlayer.setFFlying(false, false);
Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband"));
return;
}
} else { } else {
context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER));
} }
faction.disband(context.player, PlayerDisbandReason.COMMAND); faction.disband(context.player, PlayerDisbandReason.COMMAND);
Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband")); Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband"));
if (!context.fPlayer.canFlyAtLocation() && FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) {
context.fPlayer.setFFlying(false, false);
}
} }
} }

View File

@@ -26,8 +26,8 @@ public class CmdFly extends FCommand {
public static ConcurrentHashMap<String, Boolean> flyMap = new ConcurrentHashMap<>(); public static ConcurrentHashMap<String, Boolean> flyMap = new ConcurrentHashMap<>();
public static BukkitTask particleTask = null; public static BukkitTask particleTask = null;
public static BukkitTask flyTask = null;
public static boolean autoenable = FactionsPlugin.instance.getConfig().getBoolean("ffly.AutoEnable"); public static final boolean fly = FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight");
public CmdFly() { public CmdFly() {
@@ -42,15 +42,12 @@ public class CmdFly extends FCommand {
} }
public static void startParticles() { public static void startParticles() {
particleTask = Bukkit.getScheduler().runTaskTimerAsynchronously(FactionsPlugin.instance, () -> { particleTask = Bukkit.getScheduler().runTaskTimerAsynchronously(FactionsPlugin.instance, () -> {
for (String name : flyMap.keySet()) { for (String name : flyMap.keySet()) {
Player player = Bukkit.getPlayer(name); Player player = Bukkit.getPlayer(name);
if (player == null) continue; if (player == null) continue;
if (!player.isFlying()) continue; if (!player.isFlying()) continue;
if (!FactionsPlugin.getInstance().mc17) { if (!FactionsPlugin.getInstance().mc17 && player.getGameMode() == GameMode.SPECTATOR) continue;
if (player.getGameMode() == GameMode.SPECTATOR) continue;
}
FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); FPlayer fplayer = FPlayers.getInstance().getByPlayer(player);
fplayer.isVanished(); fplayer.isVanished();
@@ -62,75 +59,44 @@ public class CmdFly extends FCommand {
}, 10L, 3L); }, 10L, 3L);
} }
public static void startFlyCheck() { public static boolean checkBypassPerms(FPlayer fme, Player me, Faction toFac, boolean sendMessage) {
flyTask = Bukkit.getScheduler().runTaskTimerAsynchronously(FactionsPlugin.instance, () -> { if (Conf.denyFlightIfInNoClaimingWorld && !Conf.worldsNoClaiming.isEmpty() && Conf.worldsNoClaiming.stream().anyMatch(me.getWorld().getName()::equalsIgnoreCase))
checkTaskState(); return false;
if (flyMap.keySet().size() != 0) {
for (String name : flyMap.keySet()) {
if (name == null) {
continue;
}
Player player = Bukkit.getPlayer(name);
if (player == null
|| !player.isFlying()
|| player.getGameMode() == GameMode.CREATIVE
|| !FactionsPlugin.getInstance().mc17 && player.getGameMode() == GameMode.SPECTATOR) {
continue;
}
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
if (fPlayer.isAdminBypassing()) continue;
if (!player.hasPermission("factions.fly.bypassnearbyenemycheck")) {
if (fPlayer.hasEnemiesNearby()) {
disableFlightSync(fPlayer);
continue;
}
checkEnemiesSync(fPlayer);
}
FLocation myFloc = new FLocation(player.getLocation());
if (!checkFly(fPlayer, player, Board.getInstance().getFactionAt(myFloc))) {
disableFlightSync(fPlayer);
}
} if (toFac != fme.getFaction()) {
if (!me.hasPermission(Permission.FLY_WILDERNESS.node) && toFac.isWilderness() || !me.hasPermission(Permission.FLY_SAFEZONE.node) && toFac.isSafeZone() || !me.hasPermission(Permission.FLY_WARZONE.node) && toFac.isWarZone()) {
if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
}
Access access = toFac.getAccess(fme, PermissableAction.FLY);
if ((!(me.hasPermission(Permission.FLY_ENEMY.node) || access == Access.ALLOW)) && toFac.getRelationTo(fme.getFaction()) == Relation.ENEMY) {
if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
}
if (!(me.hasPermission(Permission.FLY_ALLY.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.ALLY) {
if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
}
if (!(me.hasPermission(Permission.FLY_TRUCE.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.TRUCE) {
if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
} }
}, 20L, 15L); if (!(me.hasPermission(Permission.FLY_NEUTRAL.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.NEUTRAL && !toFac.isSystemFaction()) {
} if(sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
public static boolean checkFly(FPlayer fme, Player me, Faction toFac) { }
if ((Conf.denyFlightIfInNoClaimingWorld && !Conf.worldsNoClaiming.isEmpty() && Conf.worldsNoClaiming.stream().anyMatch(me.getWorld().getName()::equalsIgnoreCase)) || me.hasPermission(Permission.FLY_FLY.node)) return me.hasPermission(Permission.FLY_FLY.node) && (access != Access.DENY || toFac.isSystemFaction());
return false;
if (toFac.getAccess(fme, PermissableAction.FLY) == Access.ALLOW) return true;
if (fme.getFaction().isWilderness()) return false;
if (toFac.isSystemFaction())
return me.hasPermission(toFac.isWilderness() ? Permission.FLY_WILDERNESS.node : toFac.isSafeZone() ? Permission.FLY_SAFEZONE.node : Permission.FLY_WARZONE.node);
Relation relationTo = toFac.getRelationTo(fme.getFaction());
if (!relationTo.isEnemy() && !relationTo.isMember())
return me.hasPermission(Permission.valueOf("FLY_" + relationTo.name()).node);
return false;
}
public static void checkTaskState() {
if (flyMap.isEmpty()) {
flyTask.cancel();
flyTask = null;
} }
return true;
} }
public static void disableFlight(final FPlayer fme) { public static void disableFlight(final FPlayer fme) {
fme.setFlying(false); fme.setFlying(false);
flyMap.remove(fme.getPlayer().getName()); flyMap.remove(fme.getPlayer().getName());
} }
private static void disableFlightSync(FPlayer fme) {
Bukkit.getScheduler().runTask(FactionsPlugin.instance, () -> fme.setFFlying(false, false));
flyMap.remove(fme.getName());
}
private static void checkEnemiesSync(FPlayer fp) {
Bukkit.getScheduler().runTask(FactionsPlugin.instance, fp::checkIfNearbyEnemies);
}
public boolean isInFlightChecker(Player player) { public boolean isInFlightChecker(Player player) {
return flyMap.containsKey(player.getName()); return flyMap.containsKey(player.getName());
@@ -155,7 +121,7 @@ public class CmdFly extends FCommand {
FLocation myfloc = new FLocation(context.player.getLocation()); FLocation myfloc = new FLocation(context.player.getLocation());
Faction toFac = Board.getInstance().getFactionAt(myfloc); Faction toFac = Board.getInstance().getFactionAt(myfloc);
if (!checkFly(context.fPlayer, context.player, toFac)) { if (!checkBypassPerms(context.fPlayer, context.player, toFac, false)) {
context.fPlayer.sendMessage(TL.COMMAND_FLY_NO_ACCESS.format(toFac.getTag())); context.fPlayer.sendMessage(TL.COMMAND_FLY_NO_ACCESS.format(toFac.getTag()));
return; return;
} }
@@ -175,17 +141,15 @@ public class CmdFly extends FCommand {
return; return;
} }
context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> { if (fme.canFlyAtLocation()) {
fme.setFlying(true); context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> {
flyMap.put(fme.getPlayer().getName(), true); fme.setFlying(true);
if (particleTask == null) { flyMap.put(fme.getPlayer().getName(), true);
startParticles(); if (particleTask == null) startParticles();
} }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-fly", 0));
} else {
if (flyTask == null) { fme.msg(TL.COMMAND_FLY_NO_ACCESS, Board.getInstance().getFactionAt(fme.getLastStoodAt()).getTag());
startFlyCheck(); }
}
}, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-fly", 0));
} }
@Override @Override

View File

@@ -2,10 +2,10 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.util.ItemBuilder;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class CmdGetVault extends FCommand { public class CmdGetVault extends FCommand {
@@ -30,9 +30,13 @@ public class CmdGetVault extends FCommand {
context.fPlayer.msg(TL.GENERIC_DISABLED, "Faction Vaults"); context.fPlayer.msg(TL.GENERIC_DISABLED, "Faction Vaults");
return; return;
} }
Location vaultLocation = context.faction.getVault();
ItemStack vault = FactionsPlugin.getInstance().createItem(Material.CHEST, 1, (short) 0, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name")), FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fvault.Item.Lore")));
Location vaultLocation = context.faction.getVault();
ItemStack vault = new ItemBuilder(Material.CHEST)
.amount(1)
.name(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name"))
.lore(FactionsPlugin.getInstance().getConfig().getStringList("fvault.Item.Lore"))
.build();
//check if vault is set //check if vault is set
if (vaultLocation != null) { if (vaultLocation != null) {
@@ -40,36 +44,19 @@ public class CmdGetVault extends FCommand {
return; return;
} }
//has enough money? //has enough money?
int amount = FactionsPlugin.getInstance().getConfig().getInt("fvault.Price"); int amount = FactionsPlugin.getInstance().getConfig().getInt("fvault.Price");
if (!context.fPlayer.hasMoney(amount)) { if (!context.fPlayer.hasMoney(amount)) {
return; return;
} }
if (!context.fPlayer.takeMoney(amount)) {
return;
}
//success :) //success :)
context.fPlayer.takeMoney(amount);
context.player.getInventory().addItem(vault); context.player.getInventory().addItem(vault);
context.fPlayer.msg(TL.COMMAND_GETVAULT_RECEIVE); context.fPlayer.msg(TL.COMMAND_GETVAULT_RECEIVE);
} }
public boolean inventoryContains(Inventory inventory, ItemStack item) {
int count = 0;
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) {
count += items[i].getAmount();
}
if (count >= item.getAmount()) {
return true;
}
}
return false;
}
@Override @Override
public TL getUsageTranslation() { public TL getUsageTranslation() {

View File

@@ -88,11 +88,7 @@ public class CmdHome extends FCommand {
final Location loc = context.player.getLocation().clone(); final Location loc = context.player.getLocation().clone();
// if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby // 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 if (Conf.homesTeleportAllowedEnemyDistance > 0 && !faction.isSafeZone() && (!context.fPlayer.isInOwnTerritory() || !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory)) {
&& !faction.isSafeZone()
&& (!context.fPlayer.isInOwnTerritory()
|| (context.fPlayer.isInOwnTerritory()
&& !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))) {
World w = loc.getWorld(); World w = loc.getWorld();
double x = loc.getX(); double x = loc.getX();

View File

@@ -49,6 +49,7 @@ public class CmdInventorySee extends FCommand {
FPlayer targetInv = context.argAsFPlayer(0); FPlayer targetInv = context.argAsFPlayer(0);
if (targetInv == null || !fplayers.contains(targetInv.getPlayer())) { if (targetInv == null || !fplayers.contains(targetInv.getPlayer())) {
assert targetInv != null;
context.msg(TL.PLAYER_NOT_FOUND, Objects.requireNonNull(targetInv.getName())); context.msg(TL.PLAYER_NOT_FOUND, Objects.requireNonNull(targetInv.getName()));
return; return;
} }

View File

@@ -60,14 +60,11 @@ public class CmdInvite extends FCommand {
// Send the invitation to the target player when online, otherwise just ignore // Send the invitation to the target player when online, otherwise just ignore
if (target.isOnline()) { if (target.isOnline()) {
// Tooltips, colors, and commands only apply to the string immediately before it. // Tooltips, colors, and commands only apply to the string immediately before it.
FancyMessage message = new FancyMessage(context.fPlayer.describeTo(target, true)) FancyMessage message = new FancyMessage(TL.COMMAND_INVITE_INVITEDYOU.toString()
.replace("%1$s", context.fPlayer.describeTo(target, true))
.replace("%2$s", context.faction.getTag())
.replace("&", "§"))
.tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString())
.command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag())
.then(TL.COMMAND_INVITE_INVITEDYOU.toString())
.color(ChatColor.YELLOW)
.tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString())
.command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag())
.then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString())
.command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag());
message.send(target.getPlayer()); message.send(target.getPlayer());
} }

View File

@@ -16,10 +16,6 @@ import java.util.Objects;
public class CmdJoin extends FCommand { public class CmdJoin extends FCommand {
/**
* @author FactionsUUID Team
*/
public CmdJoin() { public CmdJoin() {
super(); super();
this.aliases.addAll(Aliases.join); this.aliases.addAll(Aliases.join);
@@ -127,28 +123,13 @@ public class CmdJoin extends FCommand {
} }
faction.deinvite(fplayer); faction.deinvite(fplayer);
context.fPlayer.setRole(faction.getDefaultRole());
try {
context.fPlayer.setRole(faction.getDefaultRole());
FactionsPlugin.instance.logFactionEvent(faction, FLogType.INVITES, context.fPlayer.getName(), CC.Green + "joined", "the faction");
if (Discord.useDiscord && context.fPlayer.discordSetup() && Discord.isInMainGuild(context.fPlayer.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(context.fPlayer.discordUser());
if (Conf.factionRoles) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Objects.requireNonNull(Discord.createFactionRole(faction.getTag()))).queue();
}
if (Conf.factionDiscordTags) {
Discord.mainGuild.getController().setNickname(m, Discord.getNicknameString(context.fPlayer)).queue();
}
}
} catch (HierarchyException e) {
System.out.print(e.getMessage());
}
if (Conf.logFactionJoin) { if (Conf.logFactionJoin) {
if (samePlayer) { if (samePlayer) {
FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); FactionsPlugin.instance.log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag());
} else { } else {
FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_MOVEDLOG.toString(), context.fPlayer.getName(), fplayer.getName(), faction.getTag()); FactionsPlugin.instance.log(TL.COMMAND_JOIN_MOVEDLOG.toString(), context.fPlayer.getName(), fplayer.getName(), faction.getTag());
} }
} }
} }

View File

@@ -1,9 +1,6 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.*;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.cmd.audit.FLogType;
import com.massivecraft.factions.event.FPlayerLeaveEvent; import com.massivecraft.factions.event.FPlayerLeaveEvent;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
@@ -115,6 +112,7 @@ public class CmdKick extends FCommand {
toKickFaction.msg(TL.COMMAND_KICK_FACTION, context.fPlayer.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); toKickFaction.msg(TL.COMMAND_KICK_FACTION, context.fPlayer.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true));
toKick.msg(TL.COMMAND_KICK_KICKED, context.fPlayer.describeTo(toKick, true), toKickFaction.describeTo(toKick)); toKick.msg(TL.COMMAND_KICK_KICKED, context.fPlayer.describeTo(toKick, true), toKickFaction.describeTo(toKick));
if (toKickFaction != context.faction) { if (toKickFaction != context.faction) {
context.fPlayer.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(context.fPlayer), toKickFaction.describeTo(context.fPlayer)); context.fPlayer.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(context.fPlayer), toKickFaction.describeTo(context.fPlayer));
} }
@@ -127,6 +125,9 @@ public class CmdKick extends FCommand {
FactionsPlugin.instance.logFactionEvent(toKickFaction, FLogType.INVITES, context.fPlayer.getName(), CC.Red + "kicked", toKick.getName()); FactionsPlugin.instance.logFactionEvent(toKickFaction, FLogType.INVITES, context.fPlayer.getName(), CC.Red + "kicked", toKick.getName());
toKickFaction.deinvite(toKick); toKickFaction.deinvite(toKick);
toKick.resetFactionData(); toKick.resetFactionData();
if(!CmdFly.checkBypassPerms(toKick, toKick.getPlayer(), toKickFaction, false)){
CmdFly.disableFlight(toKick);
}
} }
@Override @Override

View File

@@ -42,76 +42,75 @@ public class CmdList extends FCommand {
// if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay
if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions"))
return; return;
FactionsPlugin.getInstance().getServer().getScheduler().runTaskAsynchronously(FactionsPlugin.instance, () -> {
ArrayList<Faction> factionList = Factions.getInstance().getAllFactions(); ArrayList<Faction> factionList = Factions.getInstance().getAllFactions();
factionList.remove(Factions.getInstance().getWilderness()); factionList.remove(Factions.getInstance().getWilderness());
factionList.remove(Factions.getInstance().getSafeZone()); factionList.remove(Factions.getInstance().getSafeZone());
factionList.remove(Factions.getInstance().getWarZone()); factionList.remove(Factions.getInstance().getWarZone());
// remove exempt factions // remove exempt factions
if (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) { if (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) {
List<String> exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt"); List<String> exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt");
factionList.removeIf(next -> exemptFactions.contains(next.getTag())); factionList.removeIf(next -> exemptFactions.contains(next.getTag()));
}
// Sort by total followers first
factionList.sort((f1, f2) -> {
int f1Size = f1.getFPlayers().size();
int f2Size = f2.getFPlayers().size();
if (f1Size < f2Size) {
return 1;
} else if (f1Size > f2Size) {
return -1;
} }
return 0;
// Sort by total followers first
factionList.sort((f1, 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
factionList.sort((f1, 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<String> lines = new ArrayList<>();
factionList.add(0, Factions.getInstance().getWilderness());
final int pageheight = 9;
int pagenumber = context.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();
}
String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]);
header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount));
lines.add(FactionsPlugin.getInstance().txt.parse(header));
for (Faction faction : factionList.subList(start, end)) {
if (faction.isWilderness()) {
lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1]))));
continue;
}
lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2]))));
}
context.sendMessage(lines);
}); });
// Then sort by how many members are online now
factionList.sort((f1, 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<String> lines = new ArrayList<>();
factionList.add(0, Factions.getInstance().getWilderness());
final int pageheight = 9;
int pagenumber = context.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();
}
String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]);
assert header != null;
header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount));
lines.add(FactionsPlugin.getInstance().txt.parse(header));
for (Faction faction : factionList.subList(start, end)) {
if (faction.isWilderness()) {
lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1]))));
continue;
}
lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2]))));
}
context.sendMessage(lines);
} }
@Override @Override

View File

@@ -50,6 +50,10 @@ public class CmdMod extends FCommand {
return; return;
} }
if(you.isAlt()){
return;
}
if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) {
context.msg(TL.COMMAND_MOD_NOTADMIN); context.msg(TL.COMMAND_MOD_NOTADMIN);
return; return;

View File

@@ -30,10 +30,6 @@ public class CmdReload extends FCommand {
FactionsPlugin.getInstance().loadLang(); FactionsPlugin.getInstance().loadLang();
if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false)) {
FactionsPlugin.getInstance().factionsFlight = true;
}
if (!FactionsPlugin.getInstance().mc17) { if (!FactionsPlugin.getInstance().mc17) {
FactionsPlayerListener.loadCorners(); FactionsPlayerListener.loadCorners();
} }

View File

@@ -66,18 +66,16 @@ public class CmdRules extends FCommand {
String message = ""; String message = "";
StringBuilder string = new StringBuilder(message); StringBuilder string = new StringBuilder(message);
for (int i = 1; i <= context.args.size() - 1; i++) { for (int i = 1; i <= context.args.size() - 1; i++) {
string.append(" " + context.args.get(i)); string.append(" ").append(context.args.get(i));
} }
context.faction.addRule(string.toString()); context.faction.addRule(string.toString());
context.msg(TL.COMMAND_RULES_ADD_SUCCESS); context.msg(TL.COMMAND_RULES_ADD_SUCCESS);
} }
if (context.args.size() == 2) { if (context.args.size() == 2 && context.args.get(0).equalsIgnoreCase("remove")) {
if (context.args.get(0).equalsIgnoreCase("remove")) {
int index = context.argAsInt(1); int index = context.argAsInt(1);
context.faction.removeRule(index - 1); context.faction.removeRule(index - 1);
context.msg(TL.COMMAND_RULES_REMOVE_SUCCESS); context.msg(TL.COMMAND_RULES_REMOVE_SUCCESS);
}
} }
} }

View File

@@ -24,17 +24,21 @@ public class CmdShow extends FCommand {
this.aliases.addAll(Aliases.show_show); this.aliases.addAll(Aliases.show_show);
// add defaults to /f show in case config doesnt have it // add defaults to /f show in case config doesnt have it
defaults.add("{header}"); defaults.add("&8&m--------------&7 &8<&e{faction}&8> &8&m--------------");
defaults.add("<a>Description: <i>{description}"); defaults.add("&4* &cOwner: &f{leader}");
defaults.add("<a>Joining: <i>{joining} {peaceful}"); defaults.add("&4* &cDescription: &f{description}");
defaults.add("<a>Land / Power / Maxpower: <i> {chunks} / {power} / {maxPower}"); defaults.add("&4* &cLand / Power / Max Power: &f{chunks} &8/ &f{power} &8/ &f{maxPower}");
defaults.add("<a>Founded: <i>{create-date}"); defaults.add("&4* &cFaction Strikes: &f{strikes}");
defaults.add("<a>This faction is permanent, remaining even with no members."); defaults.add("&4* &cFaction Points: &f{faction-points}");
defaults.add("<a>Land value: <i>{land-value} {land-refund}"); defaults.add("&4* &cFounded: &f{create-date}");
defaults.add("<a>Balance: <i>{faction-balance}"); defaults.add("&4* &cBalance: &f{faction-balance}");
defaults.add("<a>Allies(<i>{allies}<a>/<i>{max-allies}<a>): {allies-list}"); defaults.add("&4* &cAllies: &a{allies-list}");
defaults.add("<a>Online: (<i>{online}<a>/<i>{members}<a>): {online-list}"); defaults.add("&4* &cEnemies: &4{enemies-list}");
defaults.add("<a>Offline: (<i>{offline}<a>/<i>{members}<a>): {offline-list}"); defaults.add("&4* &cOnline Members: &8[&f{online}/{members}&8] &a{online-list}");
defaults.add("&4* &cOffline Members: &8[&f{offline}/{members}&8] &a{offline-list}");
defaults.add("&4* &cAlts: &f{alts}");
defaults.add("&4* &cBans: &f{faction-bancount}");
defaults.add("&8&m----------------------------------------");
// this.requiredArgs.add(""); // this.requiredArgs.add("");
this.optionalArgs.put("faction tag", "yours"); this.optionalArgs.put("faction tag", "yours");
@@ -45,6 +49,7 @@ public class CmdShow extends FCommand {
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
Faction faction = context.faction; Faction faction = context.faction;
FactionsPlugin instance = FactionsPlugin.getInstance();
if (context.argIsSet(0)) if (context.argIsSet(0))
faction = context.argAsFaction(0); faction = context.argAsFaction(0);
@@ -52,7 +57,7 @@ public class CmdShow extends FCommand {
return; return;
if (context.fPlayer != null && !context.player.getPlayer().hasPermission("factions.show.bypassexempt") if (context.fPlayer != null && !context.player.getPlayer().hasPermission("factions.show.bypassexempt")
&& FactionsPlugin.getInstance().getConfig().getStringList("show-exempt").contains(faction.getTag())) { && instance.getConfig().getStringList("show-exempt").contains(faction.getTag())) {
context.msg(TL.COMMAND_SHOW_EXEMPT); context.msg(TL.COMMAND_SHOW_EXEMPT);
return; return;
} }
@@ -62,7 +67,7 @@ public class CmdShow extends FCommand {
return; return;
} }
List<String> show = FactionsPlugin.getInstance().getConfig().getStringList("show"); List<String> show = instance.getConfig().getStringList("show");
if (show == null || show.isEmpty()) if (show == null || show.isEmpty())
show = defaults; show = defaults;
@@ -71,41 +76,49 @@ public class CmdShow extends FCommand {
// send header and that's all // send header and that's all
String header = show.get(0); String header = show.get(0);
if (TagReplacer.HEADER.contains(header)) { if (TagReplacer.HEADER.contains(header)) {
context.msg(FactionsPlugin.getInstance().txt.titleize(tag)); context.msg(instance.txt.titleize(tag));
} else { } else {
context.msg(FactionsPlugin.getInstance().txt.parse(TagReplacer.FACTION.replace(header, tag))); context.msg(instance.txt.parse(TagReplacer.FACTION.replace(header, tag)));
} }
return; // we only show header for non-normal factions return; // we only show header for non-normal factions
} }
for (String raw : show) { List<FancyMessage> fancy = new ArrayList<>();
String parsed = TagUtil.parsePlain(faction, context.fPlayer, raw); // use relations List<String> finalShow = show;
if (parsed == null) { Faction finalFaction = faction;
continue; // Due to minimal f show. instance.getServer().getScheduler().runTaskAsynchronously(instance, () -> {
} for (String raw : finalShow) {
String parsed = TagUtil.parsePlain(finalFaction, context.fPlayer, raw); // use relations
if (context.fPlayer != null) { if (parsed == null) {
parsed = TagUtil.parsePlaceholders(context.fPlayer.getPlayer(), parsed); continue; // Due to minimal f show.
}
if (TagUtil.hasFancy(parsed)) {
List<FancyMessage> fancy = TagUtil.parseFancy(faction, context.fPlayer, parsed);
if (fancy != null)
context.sendFancyMessage(fancy);
continue;
}
if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) {
if (parsed.contains("{ig}")) {
// replaces all variables with no home TL
parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString();
} }
if (parsed.contains("%")) {
parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. if (context.fPlayer != null) {
parsed = TagUtil.parsePlaceholders(context.fPlayer.getPlayer(), parsed);
}
if (TagUtil.hasFancy(parsed)) {
List<FancyMessage> localFancy = TagUtil.parseFancy(finalFaction, context.fPlayer, parsed);
if (localFancy != null)
fancy.addAll(localFancy);
continue;
}
if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) {
if (parsed.contains("{ig}")) {
// replaces all variables with no home TL
parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString();
}
if (parsed.contains("%")) {
parsed = parsed.replace("%", ""); // Just in case it got in there before we disallowed it.
}
parsed = FactionsPlugin.getInstance().txt.parse(parsed);
FancyMessage localFancy = instance.txt.parseFancy(parsed);
fancy.add(localFancy);
} }
context.msg(FactionsPlugin.getInstance().txt.parse(parsed));
} }
} instance.getServer().getScheduler().runTask(instance, () -> context.sendFancyMessage(fancy));
});
} }
@Override @Override

View File

@@ -4,6 +4,7 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap; import com.google.common.collect.ListMultimap;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public class CmdShowClaims extends FCommand { public class CmdShowClaims extends FCommand {
@@ -16,6 +17,7 @@ public class CmdShowClaims extends FCommand {
this.aliases.addAll(Aliases.show_claims); this.aliases.addAll(Aliases.show_claims);
this.requirements = new CommandRequirements.Builder(Permission.SHOWCLAIMS) this.requirements = new CommandRequirements.Builder(Permission.SHOWCLAIMS)
.withAction(PermissableAction.TERRITORY)
.playerOnly() .playerOnly()
.memberOnly() .memberOnly()
.build(); .build();

View File

@@ -33,6 +33,7 @@ public class CmdShowInvites extends FCommand {
String name = fp != null ? fp.getName() : id; String name = fp != null ? fp.getName() : id;
msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_SHOWINVITES_CLICKTOREVOKE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_SHOWINVITES_CLICKTOREVOKE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name);
} }
context.sendFancyMessage(msg);
} }
@Override @Override

View File

@@ -20,7 +20,7 @@ public class CmdStealth extends FCommand {
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
if (!Conf.useSealthSystem) { if (!Conf.useStealthSystem) {
context.msg(TL.GENERIC_DISABLED, "Factions Stealth"); context.msg(TL.GENERIC_DISABLED, "Factions Stealth");
return; return;
} }

View File

@@ -30,9 +30,7 @@ public class CmdTpBanner extends FCommand {
if (FactionsBlockListener.bannerLocations.containsKey(context.fPlayer.getTag())) { if (FactionsBlockListener.bannerLocations.containsKey(context.fPlayer.getTag())) {
context.msg(TL.COMMAND_TPBANNER_SUCCESS); context.msg(TL.COMMAND_TPBANNER_SUCCESS);
context.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", () -> { context.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", () -> context.player.teleport(FactionsBlockListener.bannerLocations.get(context.fPlayer.getTag())), FactionsPlugin.getInstance().getConfig().getLong("warmups.f-banner", 0));
context.player.teleport(FactionsBlockListener.bannerLocations.get(context.fPlayer.getTag()));
}, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-banner", 0));
} else { } else {
context.msg(TL.COMMAND_TPBANNER_NOTSET); context.msg(TL.COMMAND_TPBANNER_NOTSET);
} }

View File

@@ -5,6 +5,7 @@ import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Material;
public class CmdUnban extends FCommand { public class CmdUnban extends FCommand {
@@ -32,12 +33,8 @@ public class CmdUnban extends FCommand {
return; // the above method sends a message if fails to find someone. return; // the above method sends a message if fails to find someone.
} }
if (target.getFaction() != context.fPlayer.getFaction()) { if (target.getFaction() != context.fPlayer.getFaction() && target.getFaction().getAccess(context.fPlayer, PermissableAction.BAN) != Access.ALLOW && !context.fPlayer.isAdminBypassing()) {
if (target.getFaction().getAccess(context.fPlayer, PermissableAction.BAN) != Access.ALLOW) {
if (!context.fPlayer.isAdminBypassing()) {
context.fPlayer.msg(TL.COMMAND_UNBAN_TARGET_IN_OTHER_FACTION, target.getName()); context.fPlayer.msg(TL.COMMAND_UNBAN_TARGET_IN_OTHER_FACTION, target.getName());
}
}
} }
if (!context.faction.isBanned(target)) { if (!context.faction.isBanned(target)) {
@@ -48,7 +45,7 @@ public class CmdUnban extends FCommand {
context.faction.unban(target); context.faction.unban(target);
context.msg(TL.COMMAND_UNBAN_UNBANNED, context.fPlayer.getName(), target.getName()); context.msg(TL.COMMAND_UNBAN_UNBANNED, context.fPlayer.getName(), target.getName());
target.msg(TL.COMMAND_UNBAN_TARGET, context.faction.getTag(target)); target.msg(TL.COMMAND_UNBAN_TARGETUNBANNED, context.faction.getTag(target));
} }
@Override @Override

View File

@@ -70,13 +70,9 @@ public class CommandRequirements {
return false; return false;
} }
if (access != Access.ALLOW) { if (access != Access.ALLOW && role != null && !context.fPlayer.getRole().isAtLeast(role)) {
// They have undefined assert their role if (informIfNot) context.msg(TL.GENERIC_YOUMUSTBE, role.translation);
if (role != null && !context.fPlayer.getRole().isAtLeast(role)) { return false;
// They do not fullfill the role
if (informIfNot) context.msg(TL.GENERIC_YOUMUSTBE, role.translation);
return false;
}
} }
// They have been explicitly allowed // They have been explicitly allowed
return true; return true;

View File

@@ -399,11 +399,9 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
addSubCommand(this.cmdFocus); addSubCommand(this.cmdFocus);
fFocusEnabled = true; fFocusEnabled = true;
} }
if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false) && !fFlyEnabled) { if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", true) && !fFlyEnabled) {
this.addSubCommand(this.cmdFly); this.addSubCommand(this.cmdFly);
fFlyEnabled = true; fFlyEnabled = true;
CmdFly.startFlyCheck();
CmdFly.startParticles();
} }
} }

View File

@@ -44,7 +44,7 @@ public class CmdAltsList extends FCommand {
return; return;
} }
if (faction.getAltPlayers().size() == 0) { if (faction.getAltPlayers().isEmpty()) {
context.msg(TL.COMMAND_ALTS_LIST_NOALTS, faction.getTag()); context.msg(TL.COMMAND_ALTS_LIST_NOALTS, faction.getTag());
return; return;
} }

View File

@@ -114,7 +114,7 @@ public class FAuditMenu extends GUIMenu {
} }
lore.add(""); lore.add("");
lore.add(CC.Gray + "Click to toggle timestamp"); lore.add(CC.Gray + "Click to toggle timestamp");
setItem(slot++, (new ClickableItemStack((new ItemBuilder(Material.PAPER)).name(CC.GreenB + "Log #" + page).lore(lore).build())).setClickCallback((e) -> { setItem(slot++, (new ClickableItemStack((new ItemBuilder(Material.PAPER)).name(CC.GreenB + "Log #" + page).lore(lore).build())).setClickCallback(e -> {
e.setCancelled(true); e.setCancelled(true);
timeStamp = !timeStamp; timeStamp = !timeStamp;
drawItems(); drawItems();
@@ -122,7 +122,7 @@ public class FAuditMenu extends GUIMenu {
} }
} }
} }
setItem(getSize() - 1, (new ClickableItemStack((new ItemBuilder(Material.ARROW)).name(CC.Green + "Previous Page").lore("", CC.Gray + "Click to view previous page!").build())).setClickCallback((event) -> { setItem(getSize() - 1, (new ClickableItemStack((new ItemBuilder(Material.ARROW)).name(CC.Green + "Previous Page").lore("", CC.Gray + "Click to view previous page!").build())).setClickCallback(event -> {
event.setCancelled(true); event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditMenu(player, faction)).open(player)); Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditMenu(player, faction)).open(player));
})); }));

View File

@@ -25,8 +25,6 @@ public class FLogManager {
private Map<UUID, LogTimer> logTimers = new ConcurrentHashMap<>(); private Map<UUID, LogTimer> logTimers = new ConcurrentHashMap<>();
private boolean saving = false; private boolean saving = false;
public FLogManager() {
}
public void log(Faction faction, FLogType type, String... arguments) { public void log(Faction faction, FLogType type, String... arguments) {
FactionLogs logs = factionLogMap.computeIfAbsent(faction.getId(), (n) -> new FactionLogs()); FactionLogs logs = factionLogMap.computeIfAbsent(faction.getId(), (n) -> new FactionLogs());
@@ -90,8 +88,7 @@ public class FLogManager {
Faction faction = null; Faction faction = null;
for (Map.Entry<UUID, LogTimer> uuidLogTimerEntry : getLogTimers().entrySet()) { for (Map.Entry<UUID, LogTimer> uuidLogTimerEntry : getLogTimers().entrySet()) {
Map.Entry<UUID, LogTimer> timer = uuidLogTimerEntry; LogTimer logTimer = uuidLogTimerEntry.getValue();
LogTimer logTimer = timer.getValue();
if (faction == null) { if (faction == null) {
faction = Factions.getInstance().getFactionById(logTimer.getFactionId()); faction = Factions.getInstance().getFactionById(logTimer.getFactionId());
} }

View File

@@ -65,11 +65,11 @@ public class FactionLogs {
} }
} }
} }
if (logs.size() <= 0) if (logs.isEmpty())
toRemove.add(logType); toRemove.add(logType);
} }
}); });
toRemove.forEach((rem) -> mostRecentLogs.remove(rem)); toRemove.forEach(rem -> mostRecentLogs.remove(rem));
} }
public Map<FLogType, LinkedList<FactionLog>> getMostRecentLogs() { public Map<FLogType, LinkedList<FactionLog>> getMostRecentLogs() {

View File

@@ -26,11 +26,11 @@ public class LogTimer extends ConcurrentHashMap<LogTimer.TimerType, Map<LogTimer
} }
public Map<LogTimer.TimerSubType, LogTimer.Timer> getCurrentTimersOrCreate(LogTimer.TimerType type) { public Map<LogTimer.TimerSubType, LogTimer.Timer> getCurrentTimersOrCreate(LogTimer.TimerType type) {
return this.computeIfAbsent(type, (m) -> new ConcurrentHashMap<>()); return this.computeIfAbsent(type, m -> new ConcurrentHashMap<>());
} }
public LogTimer.Timer attemptLog(LogTimer.TimerType type, LogTimer.TimerSubType subType, long increment) { public LogTimer.Timer attemptLog(LogTimer.TimerType type, LogTimer.TimerSubType subType, long increment) {
return this.getCurrentTimersOrCreate(type).computeIfAbsent(subType, (e) -> new Timer(System.currentTimeMillis(), 0L, null)).increment(increment); return this.getCurrentTimersOrCreate(type).computeIfAbsent(subType, e -> new Timer(System.currentTimeMillis(), 0L, null)).increment(increment);
} }
public void pushLogs(Faction faction, LogTimer.TimerType type) { public void pushLogs(Faction faction, LogTimer.TimerType type) {

View File

@@ -13,24 +13,19 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData; import org.bukkit.material.MaterialData;
import org.jetbrains.annotations.NotNull;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
public class CheckHistoryFrame implements FactionGUI { public class CheckHistoryFrame implements FactionGUI {
/**
* @author Driftay
*/
private FactionsPlugin plugin;
private Faction faction; private Faction faction;
private Inventory inventory; private Inventory inventory;
private SimpleDateFormat simpleDateFormat; private SimpleDateFormat simpleDateFormat;
public CheckHistoryFrame(FactionsPlugin plugin, Faction faction) { public CheckHistoryFrame(FactionsPlugin plugin, Faction faction) {
this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat);
this.plugin = plugin;
this.faction = faction; this.faction = faction;
this.inventory = plugin.getServer().createInventory(this, 54, TL.CHECK_HISTORY_GUI_TITLE.toString()); this.inventory = plugin.getServer().createInventory(this, 54, TL.CHECK_HISTORY_GUI_TITLE.toString());
} }
@@ -88,6 +83,7 @@ public class CheckHistoryFrame implements FactionGUI {
} }
} }
@NotNull
public Inventory getInventory() { public Inventory getInventory() {
return inventory; return inventory;
} }

View File

@@ -12,6 +12,7 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import java.util.Collections; import java.util.Collections;
@@ -71,6 +72,7 @@ public class CheckSettingsFrame implements InventoryHolder, FactionGUI {
inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot"), historyStack); inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot"), historyStack);
} }
@NotNull
public Inventory getInventory() { public Inventory getInventory() {
return this.inventory; return this.inventory;
} }
@@ -92,9 +94,6 @@ public class CheckSettingsFrame implements InventoryHolder, FactionGUI {
case 15: { case 15: {
return 30; return 30;
} }
case 30: {
return 0;
}
default: { default: {
return 0; return 0;
} }

View File

@@ -11,14 +11,7 @@ import net.dv8tion.jda.core.entities.TextChannel;
public class WeeWooTask implements Runnable { public class WeeWooTask implements Runnable {
/**
* @author Driftay
*/
private FactionsPlugin plugin;
public WeeWooTask(FactionsPlugin plugin) { public WeeWooTask(FactionsPlugin plugin) {
this.plugin = plugin;
} }
@Override @Override

View File

@@ -27,22 +27,27 @@ public class AntiChestListener implements Listener {
if (e.isCancelled()) return; if (e.isCancelled()) return;
Inventory clicked = e.getClickedInventory(); Inventory clicked = e.getClickedInventory();
Inventory clicker = e.getWhoClicked().getInventory();
if (e.getClick().isShiftClick()) { if (e.getClick().isShiftClick() && clicked == clicker) {
if (clicked == e.getWhoClicked().getInventory()) { ItemStack clickedOn = e.getCurrentItem();
ItemStack clickedOn = e.getCurrentItem(); if (clickedOn != null && FactionsPlugin.getInstance().itemList.contains(clickedOn.getType().toString())) {
if (clickedOn != null && FactionsPlugin.getInstance().itemList.contains(clickedOn.getType().toString())) { fPlayer.msg(TL.CHEST_ITEM_DENIED_TRANSFER, clickedOn.getType().toString());
fPlayer.msg(TL.CHEST_ITEM_DENIED_TRANSFER, clickedOn.getType().toString()); e.setCancelled(true);
e.setCancelled(true);
}
} }
} }
if (clicked != e.getWhoClicked().getInventory()) { if (clicked != clicker) {
ItemStack onCursor = e.getCursor(); ItemStack onCursor = e.getCursor();
if (onCursor != null && FactionsPlugin.getInstance().itemList.contains(onCursor.getType().toString())) { if (onCursor != null && FactionsPlugin.getInstance().itemList.contains(onCursor.getType().toString())) {
fPlayer.msg(TL.CHEST_ITEM_DENIED_TRANSFER, onCursor.getType().toString()); fPlayer.msg(TL.CHEST_ITEM_DENIED_TRANSFER, onCursor.getType().toString());
e.setCancelled(true); e.setCancelled(true);
} else if (e.getClick().isKeyboardClick()) {
ItemStack item = clicker.getItem(e.getHotbarButton());
if (item != null && FactionsPlugin.getInstance().itemList.contains(item.getType().toString())) {
fPlayer.msg(TL.CHEST_ITEM_DENIED_TRANSFER, item.getType().toString());
e.setCancelled(true);
}
} }
} }
} }

View File

@@ -1,5 +1,6 @@
package com.massivecraft.factions.cmd.claim; package com.massivecraft.factions.cmd.claim;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
@@ -25,7 +26,6 @@ public class CmdAutoClaim extends FCommand {
super(); super();
this.aliases.addAll(Aliases.claim_auto); this.aliases.addAll(Aliases.claim_auto);
//this.requiredArgs.add("");
this.optionalArgs.put("faction", "your"); this.optionalArgs.put("faction", "your");
this.requirements = new CommandRequirements.Builder(Permission.AUTOCLAIM) this.requirements = new CommandRequirements.Builder(Permission.AUTOCLAIM)
@@ -38,13 +38,9 @@ public class CmdAutoClaim extends FCommand {
public void perform(CommandContext context) { public void perform(CommandContext context) {
Faction forFaction = context.argAsFaction(0, context.faction); Faction forFaction = context.argAsFaction(0, context.faction);
if (forFaction != context.fPlayer.getFaction()) { if (forFaction != context.fPlayer.getFaction() && !context.fPlayer.isAdminBypassing() && forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) {
if (!context.fPlayer.isAdminBypassing()) { context.msg(TL.COMMAND_CLAIM_DENIED);
if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { return;
context.msg(TL.COMMAND_CLAIM_DENIED);
return;
}
}
} }
if (forFaction == null || forFaction == context.fPlayer.getAutoClaimFor()) { if (forFaction == null || forFaction == context.fPlayer.getAutoClaimFor()) {
@@ -62,11 +58,15 @@ public class CmdAutoClaim extends FCommand {
return; return;
} }
Faction at = Board.getInstance().getFactionAt(new FLocation(context.fPlayer.getPlayer().getLocation()));
context.fPlayer.setAutoClaimFor(forFaction); context.fPlayer.setAutoClaimFor(forFaction);
FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", new FLocation(context.fPlayer.getPlayer().getLocation()).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", new FLocation(context.fPlayer.getPlayer().getLocation()).formatXAndZ(","));
context.msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(context.fPlayer)); context.msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(context.fPlayer));
context.fPlayer.attemptClaim(forFaction, context.fPlayer.getPlayer().getLocation(), true); if (FactionsPlugin.cachedRadiusClaim && context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true)) {
context.fPlayer.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_CLAIMED, context.fPlayer.describeTo(f, true), context.fPlayer.getFaction().describeTo(f), at.describeTo(f)));
} else {
context.fPlayer.attemptClaim(forFaction, context.fPlayer.getPlayer().getLocation(), true);
}
} }
@Override @Override

View File

@@ -1,9 +1,6 @@
package com.massivecraft.factions.cmd.claim; package com.massivecraft.factions.cmd.claim;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.*;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.Aliases; import com.massivecraft.factions.cmd.Aliases;
import com.massivecraft.factions.cmd.CommandContext; import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements; import com.massivecraft.factions.cmd.CommandRequirements;
@@ -44,13 +41,9 @@ public class CmdClaim extends FCommand {
int radius = context.argAsInt(0, 1); // Default to 1 int radius = context.argAsInt(0, 1); // Default to 1
final Faction forFaction = context.argAsFaction(1, context.faction); // Default to own final Faction forFaction = context.argAsFaction(1, context.faction); // Default to own
if (!context.fPlayer.isAdminBypassing()) { if (!context.fPlayer.isAdminBypassing() && !(context.fPlayer.getFaction().equals(forFaction) && context.fPlayer.getRole() == Role.LEADER) && forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) {
if (!(context.fPlayer.getFaction().equals(forFaction) && context.fPlayer.getRole() == Role.LEADER)) { context.msg(TL.COMMAND_CLAIM_DENIED);
if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { return;
context.msg(TL.COMMAND_CLAIM_DENIED);
return;
}
}
} }
@@ -59,8 +52,14 @@ public class CmdClaim extends FCommand {
return; return;
} }
Faction at = Board.getInstance().getFactionAt(new FLocation(context.fPlayer.getPlayer().getLocation()));
if (radius < 2) { if (radius < 2) {
// single chunk if (FactionsPlugin.cachedRadiusClaim && context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), false)) {
context.fPlayer.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_CLAIMED, context.fPlayer.describeTo(f, true), context.fPlayer.getFaction().describeTo(f), at.describeTo(f)));
FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(","));
return;
}
context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true); context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true);
FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(","));
} else { } else {
@@ -68,16 +67,17 @@ public class CmdClaim extends FCommand {
if (!Permission.CLAIM_RADIUS.has(context.sender, true)) { if (!Permission.CLAIM_RADIUS.has(context.sender, true)) {
return; return;
} }
new SpiralTask(new FLocation(context.player), radius) { new SpiralTask(new FLocation(context.player), radius) {
private final int limit = Conf.radiusClaimFailureLimit - 1; private final int limit = Conf.radiusClaimFailureLimit - 1;
private int failCount = 0; private int failCount = 0;
private int successfulClaims = 0;
@Override @Override
public boolean work() { public boolean work() {
boolean success = context.fPlayer.attemptClaim(forFaction, this.currentLocation(), true); boolean success = context.fPlayer.attemptClaim(forFaction, this.currentLocation(), true);
if (success) { if (success) {
failCount = 0; failCount = 0;
successfulClaims++;
FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(","));
} else if (failCount++ >= limit) { } else if (failCount++ >= limit) {
this.stop(); this.stop();
@@ -85,6 +85,14 @@ public class CmdClaim extends FCommand {
} }
return true; return true;
} }
@Override
public void finish() {
if (FactionsPlugin.cachedRadiusClaim && successfulClaims > 0) {
context.fPlayer.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_RADIUS_CLAIM, context.fPlayer.describeTo(f, true), String.valueOf(successfulClaims), context.fPlayer.getPlayer().getLocation().getChunk().getX(), context.fPlayer.getPlayer().getLocation().getChunk().getZ()));
stop();
}
}
}; };
} }
} }

View File

@@ -2,6 +2,7 @@ package com.massivecraft.factions.cmd.claim;
import com.massivecraft.factions.Board; import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.Aliases; import com.massivecraft.factions.cmd.Aliases;
import com.massivecraft.factions.cmd.CommandContext; import com.massivecraft.factions.cmd.CommandContext;
@@ -39,6 +40,15 @@ public class CmdClaimAt extends FCommand {
int x = context.argAsInt(1); int x = context.argAsInt(1);
int z = context.argAsInt(2); int z = context.argAsInt(2);
FLocation location = new FLocation(context.argAsString(0), x, z); FLocation location = new FLocation(context.argAsString(0), x, z);
Faction at = Board.getInstance().getFactionAt(new FLocation(context.fPlayer.getPlayer().getLocation()));
if (FactionsPlugin.cachedRadiusClaim && context.fPlayer.attemptClaim(context.fPlayer.getFaction(), context.player.getLocation(), true)) {
context.fPlayer.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_CLAIMED, context.fPlayer.describeTo(f, true), context.fPlayer.getFaction().describeTo(f), at.describeTo(f)));
FactionsPlugin.instance.logFactionEvent(context.fPlayer.getFaction(), FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (new FLocation(context.fPlayer.getPlayer().getLocation())).formatXAndZ(","));
showMap(context);
return;
}
context.fPlayer.attemptClaim(context.faction, location, true); context.fPlayer.attemptClaim(context.faction, location, true);
FactionsPlugin.instance.logFactionEvent(context.fPlayer.getFaction(), FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (location).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(context.fPlayer.getFaction(), FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", "1", (location).formatXAndZ(","));
showMap(context); showMap(context);

View File

@@ -1,9 +1,6 @@
package com.massivecraft.factions.cmd.claim; package com.massivecraft.factions.cmd.claim;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.*;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.Aliases; import com.massivecraft.factions.cmd.Aliases;
import com.massivecraft.factions.cmd.CommandContext; import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements; import com.massivecraft.factions.cmd.CommandRequirements;
@@ -72,23 +69,26 @@ public class CmdClaimLine extends FCommand {
final Faction forFaction = context.argAsFaction(2, context.faction); final Faction forFaction = context.argAsFaction(2, context.faction);
if (forFaction != context.fPlayer.getFaction()) { if (forFaction != context.fPlayer.getFaction() && !context.fPlayer.isAdminBypassing() && forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) {
if (!context.fPlayer.isAdminBypassing()) {
if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) {
context.msg(TL.COMMAND_CLAIM_DENIED); context.msg(TL.COMMAND_CLAIM_DENIED);
return; return;
}
}
} }
Location location = context.player.getLocation(); Location location = context.player.getLocation();
// TODO: make this a task like claiming a radius? // TODO: make this a task like claiming a radius?
int claims = 0;
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {
context.fPlayer.attemptClaim(forFaction, location, true); if (!FactionsPlugin.cachedRadiusClaim || !context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), false)) {
location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16); context.fPlayer.attemptClaim(forFaction, location, true);
}
claims++;
location = location.add(blockFace.getModX() * 16D, 0, blockFace.getModZ() * 16D);
FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", String.valueOf(i), new FLocation(context.player.getLocation()).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(forFaction, FLogType.CHUNK_CLAIMS, context.fPlayer.getName(), CC.GreenB + "CLAIMED", String.valueOf(i), new FLocation(context.player.getLocation()).formatXAndZ(","));
} }
int cachedClaims = claims;
context.fPlayer.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_RADIUS_CLAIM, context.fPlayer.describeTo(f, true), String.valueOf(cachedClaims), context.fPlayer.getPlayer().getLocation().getChunk().getX(), context.fPlayer.getPlayer().getLocation().getChunk().getZ()));
} }
@Override @Override

View File

@@ -8,7 +8,6 @@ import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements; import com.massivecraft.factions.cmd.CommandRequirements;
import com.massivecraft.factions.cmd.FCommand; import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.cmd.audit.FLogType;
import com.massivecraft.factions.iface.EconomyParticipator;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
@@ -44,23 +43,21 @@ public class CmdMoneyWithdraw extends FCommand {
return; return;
} }
EconomyParticipator faction = context.argAsFaction(1, context.faction); Faction faction = context.argAsFaction(1, context.faction);
if (faction == null) { if (faction == null) {
return; return;
} }
Access access = context.faction.getAccess(context.fPlayer, PermissableAction.WITHDRAW); Access access = context.faction.getAccess(context.fPlayer, PermissableAction.WITHDRAW);
if (context.fPlayer.getRole() != Role.LEADER) { if (context.fPlayer.getRole() != Role.LEADER && access == Access.DENY) {
if (access == Access.DENY) { context.msg(TL.GENERIC_NOPERMISSION, "withdraw", "withdraw money from the bank");
context.msg(TL.GENERIC_NOPERMISSION, "withdraw", "withdraw money from the bank"); return;
return;
}
} }
boolean success = Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount); boolean success = Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount);
if (success && Conf.logMoneyTransactions) { if (success && Conf.logMoneyTransactions) {
FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null)))); FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null))));
FactionsPlugin.instance.logFactionEvent((Faction) faction, FLogType.BANK_EDIT, context.fPlayer.getName(), CC.RedB + "WITHDREW", amount + ""); FactionsPlugin.instance.logFactionEvent(faction, FLogType.BANK_EDIT, context.fPlayer.getName(), CC.RedB + "WITHDREW", amount + "");
} }
} }

View File

@@ -37,31 +37,29 @@ public class CmdGrace extends FCommand {
return; return;
} }
if(context.args.size() == 1) { if (context.args.size() == 1 && context.sender.hasPermission(String.valueOf(Permission.GRACETOGGLE))) {
if (context.sender.hasPermission(String.valueOf(Permission.GRACETOGGLE))) { if (context.argAsString(0).equalsIgnoreCase("on") || context.argAsString(0).equalsIgnoreCase("start")) {
if (context.argAsString(0).equalsIgnoreCase("on") || context.argAsString(0).equalsIgnoreCase("start")) { FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false);
FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false); FactionsPlugin.getInstance().getTimerManager().graceTimer.setRemaining(TimeUnit.DAYS.toMillis(Conf.gracePeriodTimeDays), true);
FactionsPlugin.getInstance().getTimerManager().graceTimer.setRemaining(TimeUnit.DAYS.toMillis(Conf.gracePeriodTimeDays), true); if (Conf.broadcastGraceToggles) {
if (Conf.broadcastGraceToggles) { for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers())
for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) follower.msg(TL.COMMAND_GRACE_ENABLED_FORMAT, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)));
follower.msg(TL.COMMAND_GRACE_ENABLED_FORMAT, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)));
}
return;
} }
return;
}
if (context.argAsString(0).equalsIgnoreCase("off") || context.argAsString(0).equalsIgnoreCase("stop")) { if (context.argAsString(0).equalsIgnoreCase("off") || context.argAsString(0).equalsIgnoreCase("stop")) {
FactionsPlugin.getInstance().getTimerManager().graceTimer.setRemaining(TimeUnit.SECONDS.toMillis(0L), true); FactionsPlugin.getInstance().getTimerManager().graceTimer.setRemaining(TimeUnit.SECONDS.toMillis(0L), true);
FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false); FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false);
if (Conf.broadcastGraceToggles) { if (Conf.broadcastGraceToggles) {
for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers())
follower.msg(TL.COMMAND_GRACE_DISABLED_FORMAT); follower.msg(TL.COMMAND_GRACE_DISABLED_FORMAT);
}
return;
} }
return;
} }
} }
if(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() <= 0L) { if (FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() <= 0L) {
context.fPlayer.msg(TL.COMMAND_GRACE_DISABLED_NO_FORMAT.toString()); context.fPlayer.msg(TL.COMMAND_GRACE_DISABLED_NO_FORMAT.toString());
} else { } else {
context.fPlayer.msg(TL.COMMAND_GRACE_TIME_REMAINING, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true))); context.fPlayer.msg(TL.COMMAND_GRACE_TIME_REMAINING, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)));

View File

@@ -15,10 +15,8 @@ public class LogoutHandler {
public static Map<String, LogoutHandler> factionDatas = new HashMap<>(); public static Map<String, LogoutHandler> factionDatas = new HashMap<>();
private Map<UUID, Long> logoutCooldown = new HashMap<>(); private Map<UUID, Long> logoutCooldown = new HashMap<>();
private String name;
public LogoutHandler(String name) { public LogoutHandler(String name) {
this.name = name;
factionDatas.put(name, this); factionDatas.put(name, this);
} }

View File

@@ -39,9 +39,9 @@ public abstract class FRelationCommand extends FCommand {
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
Faction them = context.argAsFaction(0); Faction them = context.argAsFaction(0);
if (them == null) { if (them == null) return;
return;
} if (!context.faction.isNormal()) return;
if (!them.isNormal()) { if (!them.isNormal()) {
context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE); context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE);
@@ -112,16 +112,14 @@ public abstract class FRelationCommand extends FCommand {
private boolean hasMaxRelations(Faction us, Faction them, Relation targetRelation) { private boolean hasMaxRelations(Faction us, Faction them, Relation targetRelation) {
int max = FactionsPlugin.getInstance().getConfig().getInt("max-relations." + targetRelation.toString(), -1); int max = FactionsPlugin.getInstance().getConfig().getInt("max-relations." + targetRelation.toString(), -1);
if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", false)) { if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", false) && max != -1) {
if (max != -1) { if (us.getRelationCount(targetRelation) >= max) {
if (us.getRelationCount(targetRelation) >= max) { us.msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation());
us.msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); return true;
return true; }
} if (them.getRelationCount(targetRelation) >= max) {
if (them.getRelationCount(targetRelation) >= max) { them.msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation());
them.msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation()); return true;
return true;
}
} }
} }
return false; return false;

View File

@@ -57,6 +57,16 @@ public class FPromoteCommand extends FCommand {
context.msg(TL.COMMAND_PROMOTE_NOT_SAME); context.msg(TL.COMMAND_PROMOTE_NOT_SAME);
return; return;
} }
// Don't allow people to promote people with same or higher rank than their.
if (context.fPlayer.getRole().value <= target.getRole().value) {
context.msg(TL.COMMAND_PROMOTE_HIGHER_RANK, target.getName());
return;
}
// Don't allow people to demote people who already have the lowest rank.
if (current.value == 0 && relative <= 0) {
context.msg(TL.COMMAND_PROMOTE_LOWEST_RANK, target.getName());
return;
}
// Don't allow people to promote people to their same or higher rank. // Don't allow people to promote people to their same or higher rank.
if (context.fPlayer.getRole().value <= promotion.value) { if (context.fPlayer.getRole().value <= promotion.value) {
context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED);
@@ -64,11 +74,20 @@ public class FPromoteCommand extends FCommand {
} }
} }
if (promotion == null) { if(target.isAlt()){
context.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER);
return; return;
} }
// Don't allow people to demote people who already have the lowest rank.
if (current.value == 0 && relative <= 0) {
context.msg(TL.COMMAND_PROMOTE_LOWEST_RANK, target.getName());
return;
}
// Don't allow people to promote people who already have the highest rank.
if (current.value == 4 && relative > 0) {
context.msg(TL.COMMAND_PROMOTE_HIGHEST_RANK, target.getName());
return;
}
// Don't allow people to promote people to their same or higher rnak. // Don't allow people to promote people to their same or higher rnak.
if (context.fPlayer.getRole().value <= promotion.value) { if (context.fPlayer.getRole().value <= promotion.value) {
context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED);

View File

@@ -1,10 +1,7 @@
package com.massivecraft.factions.cmd.wild; package com.massivecraft.factions.cmd.wild;
import com.massivecraft.factions.Board; import com.massivecraft.factions.*;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.Aliases; import com.massivecraft.factions.cmd.Aliases;
import com.massivecraft.factions.cmd.CommandContext; import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements; import com.massivecraft.factions.cmd.CommandRequirements;
@@ -22,11 +19,15 @@ import org.bukkit.potion.PotionEffectType;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
import java.util.Random; import java.util.Random;
/**
* @author DroppingAnvil
*/
public class CmdWild extends FCommand implements WaitedTask { public class CmdWild extends FCommand implements WaitedTask {
public static HashMap<Player, String> teleportRange; public static HashMap<Player, String> teleportRange = new HashMap<>();
public static HashSet<Player> teleporting; public static HashSet<Player> teleporting = new HashSet<>();
public static CmdWild instance; public static CmdWild instance;
public CmdWild() { public CmdWild() {
@@ -36,16 +37,12 @@ public class CmdWild extends FCommand implements WaitedTask {
this.requirements = new CommandRequirements.Builder(Permission.WILD) this.requirements = new CommandRequirements.Builder(Permission.WILD)
.playerOnly() .playerOnly()
.build(); .build();
teleporting = new HashSet<>(); }
teleportRange = new HashMap<>();
}
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
if (!teleportRange.containsKey(context.player)) { if (!teleportRange.containsKey(context.player)) {
context.player.openInventory(new WildGUI(context.player, context.fPlayer).getInventory()); context.player.openInventory(new WildGUI(context.player, context.fPlayer).getInventory());
} else {
context.fPlayer.msg(TL.COMMAND_WILD_WAIT);
} }
} }
@@ -55,16 +52,18 @@ public class CmdWild extends FCommand implements WaitedTask {
int tries = 0; int tries = 0;
ConfigurationSection c = FactionsPlugin.getInstance().getConfig().getConfigurationSection("Wild.Zones." + teleportRange.get(p)); ConfigurationSection c = FactionsPlugin.getInstance().getConfig().getConfigurationSection("Wild.Zones." + teleportRange.get(p));
while (tries < 5) { while (tries < 5) {
assert c != null;
int x = new Random().nextInt((c.getInt("Range.MaxX") - c.getInt("Range.MinX")) + 1) + c.getInt("Range.MinX"); int x = new Random().nextInt((c.getInt("Range.MaxX") - c.getInt("Range.MinX")) + 1) + c.getInt("Range.MinX");
int z = new Random().nextInt((c.getInt("Range.MaxZ") - c.getInt("Range.MinZ")) + 1) + c.getInt("Range.MinZ"); int z = new Random().nextInt((c.getInt("Range.MaxZ") - c.getInt("Range.MinZ")) + 1) + c.getInt("Range.MinZ");
if (Board.getInstance().getFactionAt(new FLocation(p.getWorld().getName(), x, z)).isWilderness()) { if (Board.getInstance().getFactionAt(new FLocation(p.getWorld().getName(), x, z)).isWilderness()) {
success = true; success = true;
FLocation loc = new FLocation(p.getWorld().getName(), x, z); FLocation loc = new FLocation(Objects.requireNonNull(c.getString("World", "World")), x, z);
teleportRange.remove(p); teleportRange.remove(p);
if (!FPlayers.getInstance().getByPlayer(p).takeMoney(c.getInt("Cost"))) { if (!FPlayers.getInstance().getByPlayer(p).takeMoney(c.getInt("Cost"))) {
p.sendMessage(TL.GENERIC_NOTENOUGHMONEY.toString()); p.sendMessage(TL.GENERIC_NOTENOUGHMONEY.toString());
return; return;
} }
if (Conf.wildLoadChunkBeforeTeleport && !loc.getChunk().isLoaded()) loc.getChunk().load();
teleportPlayer(p, loc); teleportPlayer(p, loc);
break; break;
} }
@@ -72,15 +71,16 @@ public class CmdWild extends FCommand implements WaitedTask {
} }
if (!success) { if (!success) {
p.sendMessage(TL.COMMAND_WILD_FAILED.toString()); p.sendMessage(TL.COMMAND_WILD_FAILED.toString());
teleportRange.remove(p);
} }
} }
public void teleportPlayer(Player p, FLocation loc) { public void teleportPlayer(Player p, FLocation loc) {
Location finalLoc; Location finalLoc;
if (FactionsPlugin.getInstance().getConfig().getBoolean("Wild.Arrival.SpawnAbove")) { if (FactionsPlugin.getInstance().getConfig().getBoolean("Wild.Arrival.SpawnAbove")) {
finalLoc = new Location(p.getWorld(), loc.getX(), p.getWorld().getHighestBlockYAt(Math.round(loc.getX()), Math.round(loc.getZ())) + FactionsPlugin.getInstance().getConfig().getInt("Wild.Arrival.SpawnAboveBlocks", 1), loc.getZ()); finalLoc = new Location(loc.getWorld(), loc.getX(), loc.getWorld().getHighestBlockYAt(Math.round(loc.getX()), Math.round(loc.getZ())) + FactionsPlugin.getInstance().getConfig().getInt("Wild.Arrival.SpawnAboveBlocks", 1), loc.getZ());
} else { } else {
finalLoc = new Location(p.getWorld(), loc.getX(), p.getWorld().getHighestBlockYAt(Math.round(loc.getX()), Math.round(loc.getZ())), loc.getZ()); finalLoc = new Location(loc.getWorld(), loc.getX(), loc.getWorld().getHighestBlockYAt(Math.round(loc.getX()), Math.round(loc.getZ())), loc.getZ());
} }
p.teleport(finalLoc, PlayerTeleportEvent.TeleportCause.PLUGIN); p.teleport(finalLoc, PlayerTeleportEvent.TeleportCause.PLUGIN);
setTeleporting(p); setTeleporting(p);
@@ -89,7 +89,7 @@ public class CmdWild extends FCommand implements WaitedTask {
public void applyEffects(Player p) { public void applyEffects(Player p) {
for (String s : FactionsPlugin.getInstance().getConfig().getStringList("Wild.Arrival.Effects")) { for (String s : FactionsPlugin.getInstance().getConfig().getStringList("Wild.Arrival.Effects")) {
p.addPotionEffect(new PotionEffect(PotionEffectType.getByName(s), 40, 1)); p.addPotionEffect(new PotionEffect(Objects.requireNonNull(PotionEffectType.getByName(s)), 40, 1));
} }
} }
@@ -111,6 +111,6 @@ public class CmdWild extends FCommand implements WaitedTask {
@Override @Override
public void handleFailure(Player player) { public void handleFailure(Player player) {
player.sendMessage(TL.COMMAND_WILD_INTERUPTED.toString()); player.sendMessage(TL.COMMAND_WILD_INTERUPTED.toString());
teleportRange.remove(player);
} }
} }

View File

@@ -20,6 +20,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/**
* @author DroppingAnvil
*/
public class WildGUI implements FactionGUI { public class WildGUI implements FactionGUI {
Player player; Player player;
FPlayer fplayer; FPlayer fplayer;
@@ -37,7 +40,7 @@ public class WildGUI implements FactionGUI {
if (map.containsKey(slot)) { if (map.containsKey(slot)) {
String zone = map.get(slot); String zone = map.get(slot);
if (fplayer.hasMoney(FactionsPlugin.getInstance().getConfig().getInt("Wild.Zones." + zone + ".Cost"))) { if (fplayer.hasMoney(FactionsPlugin.getInstance().getConfig().getInt("Wild.Zones." + zone + ".Cost"))) {
WaitExecutor.taskMap.put(player, new WaitTask(FactionsPlugin.getInstance().getConfig().getInt("Wild.Wait"), TL.COMMAND_WILD_INPROGRESS, player, CmdWild.instance)); WaitExecutor.taskMap.put(player, new WaitTask(FactionsPlugin.getInstance().getConfig().getInt("Wild.Wait"), TL.COMMAND_WILD_WAIT, player, CmdWild.instance));
CmdWild.teleportRange.put(player, zone); CmdWild.teleportRange.put(player, zone);
fplayer.msg(TL.COMMAND_WILD_WAIT, FactionsPlugin.getInstance().getConfig().getInt("Wild.Wait") + " Seconds"); fplayer.msg(TL.COMMAND_WILD_WAIT, FactionsPlugin.getInstance().getConfig().getInt("Wild.Wait") + " Seconds");
player.closeInventory(); player.closeInventory();
@@ -57,7 +60,8 @@ public class WildGUI implements FactionGUI {
inv.setItem(fill, fillItem); inv.setItem(fill, fillItem);
} }
for (String key : Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getConfigurationSection("Wild.Zones")).getKeys(false)) { for (String key : Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getConfigurationSection("Wild.Zones")).getKeys(false)) {
ItemStack zoneItem = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("Wild.Zones." + key + ".Material")).get().parseItem(); ItemStack zoneItem = XMaterial.matchXMaterial(Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getString("Wild.Zones." + key + ".Material"))).get().parseItem();
assert zoneItem != null;
ItemMeta zoneMeta = zoneItem.getItemMeta(); ItemMeta zoneMeta = zoneItem.getItemMeta();
if (zoneMeta == null) return; if (zoneMeta == null) return;
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();

View File

@@ -60,17 +60,17 @@ public class CmdSetGuild extends FCommand {
if (guild == null) { if (guild == null) {
context.msg(TL.SET_GUILD_ID_INVALID_ID); context.msg(TL.SET_GUILD_ID_INVALID_ID);
} else if (Factions.getInstance().getAllFactions().stream().anyMatch((f) -> guildId.equals(f.getGuildId()))) { } else if (Factions.getInstance().getAllFactions().stream().anyMatch(f -> guildId.equals(f.getGuildId()))) {
context.msg(TL.SET_GUILD_ID_GUILD_ALREADY_LINKED); context.msg(TL.SET_GUILD_ID_GUILD_ALREADY_LINKED);
} else { } else {
context.msg(TL.SET_GUILD_ID_PMING_OWNER); context.msg(TL.SET_GUILD_ID_PMING_OWNER);
User user = guild.getOwner().getUser(); User user = guild.getOwner().getUser();
Guild finalGuild = guild; Guild finalGuild = guild;
Guild finalGuild1 = guild; Guild finalGuild1 = guild;
user.openPrivateChannel().queue((privateChannel) -> privateChannel.sendMessage("Link guild **" + finalGuild1.getName() + "** to faction **" + ChatColor.stripColor(faction.getTag()) + "**?").queue((message) -> { user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("Link guild **" + finalGuild1.getName() + "** to faction **" + ChatColor.stripColor(faction.getTag()) + "**?").queue(message -> {
String checkMark = ""; String checkMark = "";
message.addReaction(checkMark).queue(); message.addReaction(checkMark).queue();
this.eventWaiter.waitForEvent(PrivateMessageReactionAddEvent.class, (event) -> event.getReactionEmote().getName().equals(checkMark) && event.getUser().getId().equals(user.getId()) && event.getMessageId().equals(message.getId()), (event) -> { this.eventWaiter.waitForEvent(PrivateMessageReactionAddEvent.class, event -> event.getReactionEmote().getName().equals(checkMark) && event.getUser().getId().equals(user.getId()) && event.getMessageId().equals(message.getId()), event -> {
faction.setGuildId(context.argAsString(0)); faction.setGuildId(context.argAsString(0));
context.msg(TL.SET_GUILD_ID_SUCCESS); context.msg(TL.SET_GUILD_ID_SUCCESS);
privateChannel.sendMessage("Successfully linked **" + finalGuild.getName() + " & " + ChatColor.stripColor(faction.getTag()) + "**").queue(); privateChannel.sendMessage("Successfully linked **" + finalGuild.getName() + " & " + ChatColor.stripColor(faction.getTag()) + "**").queue();
@@ -78,9 +78,7 @@ public class CmdSetGuild extends FCommand {
privateChannel.sendMessage(TL.SET_GUILD_ID_TIMED_OUT_DISCORD.toString()).queue(); privateChannel.sendMessage(TL.SET_GUILD_ID_TIMED_OUT_DISCORD.toString()).queue();
context.msg(TL.SET_GUILD_ID_TIMED_OUT_MINECRAFT); context.msg(TL.SET_GUILD_ID_TIMED_OUT_MINECRAFT);
}); });
}, (t) -> { }, t -> context.msg(TL.SET_GUILD_ID_UNABLE_TO_MESSAGE_GUILD_OWNER)), t -> context.msg(TL.SET_GUILD_ID_UNABLE_TO_MESSAGE_GUILD_OWNER));
context.msg(TL.SET_GUILD_ID_UNABLE_TO_MESSAGE_GUILD_OWNER);
}), (t) -> context.msg(TL.SET_GUILD_ID_UNABLE_TO_MESSAGE_GUILD_OWNER));
} }
} else { } else {
faction.setGuildId(null); faction.setGuildId(null);

View File

@@ -31,7 +31,7 @@ public class Discord {
public static Boolean confUseDiscord; public static Boolean confUseDiscord;
public static String botToken; public static String botToken;
public static String mainGuildID; public static String mainGuildID;
public static Boolean useDiscord; public static boolean useDiscord;
public static java.awt.Color roleColor; public static java.awt.Color roleColor;
public static Guild mainGuild; public static Guild mainGuild;
public static Role leader; public static Role leader;
@@ -53,13 +53,11 @@ public class Discord {
* Called to reload variables and if needed start JDA * Called to reload variables and if needed start JDA
*/ */
public static void setupDiscord() { public static void setupDiscord() {
if (jda == null) { if (jda == null && startBot()) {
if (startBot()) { varSetup();
varSetup(); jda.addEventListener(new FactionChatHandler(plugin));
jda.addEventListener(new FactionChatHandler(plugin)); jda.addEventListener(new DiscordListener(plugin));
jda.addEventListener(new DiscordListener(plugin)); return;
return;
}
} }
varSetup(); varSetup();
} }
@@ -84,6 +82,7 @@ public class Discord {
confUseDiscord = Conf.useDiscordSystem; confUseDiscord = Conf.useDiscordSystem;
botToken = Conf.discordBotToken; botToken = Conf.discordBotToken;
if (jda != null && Conf.leaderRoles || Conf.factionDiscordTags) { if (jda != null && Conf.leaderRoles || Conf.factionDiscordTags) {
assert jda != null;
mainGuild = jda.getGuildById(Conf.mainGuildID); mainGuild = jda.getGuildById(Conf.mainGuildID);
} else { } else {
mainGuild = null; mainGuild = null;
@@ -151,12 +150,9 @@ public class Discord {
* @param s String target Faction tag * @param s String target Faction tag
* @return * @return
*/ */
public static Boolean doesFactionRoleExist(String s) { public static boolean doesFactionRoleExist(String s) {
StringBuilder sb = new StringBuilder(); String sb = Conf.factionRolePrefix + s + Conf.factionRoleSuffix;
sb.append(Conf.factionRolePrefix); return getRoleFromName(sb) != null;
sb.append(s);
sb.append(Conf.factionRoleSuffix);
return getRoleFromName(sb.toString()) != null;
} }
public static Role getRoleFromName(String s) { public static Role getRoleFromName(String s) {
@@ -189,7 +185,8 @@ public class Discord {
sb.append(Conf.factionRoleSuffix); sb.append(Conf.factionRoleSuffix);
if (!doesFactionRoleExist(sb.toString())) { if (!doesFactionRoleExist(sb.toString())) {
try { try {
Role newRole = mainGuild.getController().createRole() Role newRole;
newRole = mainGuild.getController().createRole()
.setName(sb.toString()) .setName(sb.toString())
.setColor(roleColor) .setColor(roleColor)
.setPermissions(Permission.EMPTY_PERMISSIONS) .setPermissions(Permission.EMPTY_PERMISSIONS)
@@ -211,11 +208,7 @@ public class Discord {
* @return Name of would be Role * @return Name of would be Role
*/ */
public static String getFactionRoleName(String tag) { public static String getFactionRoleName(String tag) {
StringBuilder sb = new StringBuilder(); return Conf.factionRolePrefix + tag + Conf.factionRoleSuffix;
sb.append(Conf.factionRolePrefix);
sb.append(tag);
sb.append(Conf.factionRoleSuffix);
return sb.toString();
} }
/** /**
@@ -224,7 +217,7 @@ public class Discord {
* @param u User * @param u User
* @return Boolean * @return Boolean
*/ */
public static Boolean isInMainGuild(User u) { public static boolean isInMainGuild(User u) {
if (mainGuild == null) return false; if (mainGuild == null) return false;
return mainGuild.getMember(u) == null ? Boolean.FALSE : Boolean.TRUE; return mainGuild.getMember(u) == null ? Boolean.FALSE : Boolean.TRUE;
} }
@@ -252,10 +245,12 @@ public class Discord {
if (fp.discordSetup() && isInMainGuild(fp.discordUser())) { if (fp.discordSetup() && isInMainGuild(fp.discordUser())) {
try { try {
Member m = mainGuild.getMember(fp.discordUser()); Member m = mainGuild.getMember(fp.discordUser());
if (Conf.factionDiscordTags) { boolean discordTags = Conf.factionDiscordTags;
boolean factionRoles = Conf.factionRoles;
if (discordTags) {
mainGuild.getController().setNickname(m, Discord.getNicknameString(fp)).queue(); mainGuild.getController().setNickname(m, Discord.getNicknameString(fp)).queue();
} }
if (Conf.factionRoles) { if (factionRoles) {
mainGuild.getController().removeSingleRoleFromMember(m, Objects.requireNonNull(getRoleFromName(oldTag))).queue(); mainGuild.getController().removeSingleRoleFromMember(m, Objects.requireNonNull(getRoleFromName(oldTag))).queue();
mainGuild.getController().addSingleRoleToMember(m, Objects.requireNonNull(createFactionRole(f.getTag()))).queue(); mainGuild.getController().addSingleRoleToMember(m, Objects.requireNonNull(createFactionRole(f.getTag()))).queue();
} }

View File

@@ -37,7 +37,7 @@ public class DiscordListener extends ListenerAdapter {
this.decimalFormat = new DecimalFormat("$#,###.##"); this.decimalFormat = new DecimalFormat("$#,###.##");
this.plugin = plugin; this.plugin = plugin;
int minute = 3600; int minute = 3600;
plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, DiscordListener::saveGuilds, minute * 15, minute * 15); plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, DiscordListener::saveGuilds, minute * 15L, minute * 15L);
} }
private static JSONGuilds loadGuilds() { private static JSONGuilds loadGuilds() {
@@ -64,6 +64,7 @@ public class DiscordListener extends ListenerAdapter {
} }
} }
@Override
public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) { public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) {
Integer i; Integer i;
if (e.getAuthor().isBot()) return; if (e.getAuthor().isBot()) return;
@@ -85,6 +86,7 @@ public class DiscordListener extends ListenerAdapter {
} }
} }
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) { public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
try { try {
if (event.getMessage().isWebhookMessage() || event.getAuthor().isBot()) return; if (event.getMessage().isWebhookMessage() || event.getAuthor().isBot()) return;

View File

@@ -109,7 +109,7 @@ public class DiscordSetupAttempt {
sb.append(inProcessTime); sb.append(inProcessTime);
//Just a separator for looks //Just a separator for looks
sb.append(" "); sb.append(" ");
String s = ""; String s;
switch (timeIndex) { switch (timeIndex) {
case 0: case 0:
s = "MS"; s = "MS";
@@ -129,6 +129,8 @@ public class DiscordSetupAttempt {
case 5: case 5:
s = "Years"; s = "Years";
break; break;
default:
throw new IllegalStateException("Unexpected value: " + timeIndex);
} }
sb.append(s); sb.append(s);
sb.append(" ago"); sb.append(" ago");

View File

@@ -35,7 +35,7 @@ public class FactionChatHandler extends ListenerAdapter {
this.plugin = plugin; this.plugin = plugin;
} }
public static void sendMessage(FactionsPlugin plugin, Faction faction, UUID uuid, String username, String message) { public static void sendMessage(Faction faction, UUID uuid, String username, String message) {
String factionsChatChannelId = faction.getFactionChatChannelId(); String factionsChatChannelId = faction.getFactionChatChannelId();
String messageWithMentions = null; String messageWithMentions = null;
if (factionsChatChannelId == null || factionsChatChannelId.isEmpty()) return; if (factionsChatChannelId == null || factionsChatChannelId.isEmpty()) return;

View File

@@ -1,6 +1,5 @@
package com.massivecraft.factions.event; package com.massivecraft.factions.event;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
@@ -10,51 +9,20 @@ import org.bukkit.event.Cancellable;
*/ */
public class PowerRegenEvent extends FactionPlayerEvent implements Cancellable { public class PowerRegenEvent extends FactionPlayerEvent implements Cancellable {
/**
* @author Illyria Team
*/
private boolean cancelled = false; private boolean cancelled = false;
private double modified = 0; private double delta;
public PowerRegenEvent(Faction f, FPlayer p) { public PowerRegenEvent(Faction f, FPlayer p, double delta) {
super(f, p); super(f, p);
this.delta = delta;
} }
/** public double getDelta() {
* Get the amount of power this player will regen by default return delta;
*
* @return power amount gained as a Double.
*/
public double getDefaultPowerGained() {
return fPlayer.getMillisPassed() * Conf.powerPerMinute / 60000;
} }
/** public void setDelta(double delta) {
* Get the amount of custom power this player will gain. Ignored if less than or equal to 0. this.delta = delta;
*
* @return Custom power as a double
*/
public double getCustomPower() {
return modified;
}
/**
* Set the custom power gain for this event.
*
* @param gain Amount of power to be added to player.
*/
public void setCustomPower(Double gain) {
modified = gain;
}
/**
* Get if we will be using the custom power gain instead of default.
*
* @return If we will process the event custom returned as a Boolean.
*/
public boolean usingCustomPower() {
return modified > 0;
} }
@Override @Override

View File

@@ -32,9 +32,8 @@ public class Econ {
private static Economy econ = null; private static Economy econ = null;
public static void setup() { public static void setup() {
if (isSetup()) { if (isSetup()) return;
return;
}
String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" ";
@@ -42,21 +41,14 @@ public class Econ {
FactionsPlugin.getInstance().log(integrationFail + "is not installed."); FactionsPlugin.getInstance().log(integrationFail + "is not installed.");
return; return;
} }
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) { if (rsp == null) {
FactionsPlugin.getInstance().log(integrationFail + "is not hooked into an economy plugin."); FactionsPlugin.getInstance().log(integrationFail + "is not hooked into an economy plugin.");
return; return;
} }
econ = rsp.getProvider(); econ = rsp.getProvider();
FactionsPlugin.getInstance().log("Economy integration through Vault plugin successful."); FactionsPlugin.getInstance().log("Economy integration through Vault plugin successful.");
if (!Conf.econEnabled) FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true");
if (!Conf.econEnabled) {
FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true");
}
//FactionsPlugin.getInstance().cmdBase.cmdHelp.updateHelp();
} }
public static boolean shouldBeUsed() { public static boolean shouldBeUsed() {
@@ -68,26 +60,24 @@ public class Econ {
} }
public static void modifyUniverseMoney(double delta) { public static void modifyUniverseMoney(double delta) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) return;
return; if (Conf.econUniverseAccount == null) return;
} if (Conf.econUniverseAccount.length() == 0) return;
if (!econ.hasAccount(Conf.econUniverseAccount)) return;
if (Conf.econUniverseAccount == null) {
return;
}
if (Conf.econUniverseAccount.length() == 0) {
return;
}
if (!econ.hasAccount(Conf.econUniverseAccount)) {
return;
}
modifyBalance(Conf.econUniverseAccount, delta); modifyBalance(Conf.econUniverseAccount, delta);
} }
public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) {
if (!shouldBeUsed()) {
FactionsPlugin.instance.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin.");
return;
}
to.msg(TL.ECON_PLAYERBALANCE, about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId())));
}
public static void sendBalanceInfo(CommandSender to, Faction about) { public static void sendBalanceInfo(CommandSender to, Faction about) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) {
FactionsPlugin.getInstance().log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); FactionsPlugin.instance.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin.");
return; return;
} }
to.sendMessage(String.format(TL.ECON_PLAYERBALANCE.toString(), about.getTag(), Econ.moneyString(econ.getBalance(about.getAccountId())))); to.sendMessage(String.format(TL.ECON_PLAYERBALANCE.toString(), about.getTag(), Econ.moneyString(econ.getBalance(about.getAccountId()))));
@@ -98,38 +88,20 @@ public class Econ {
Faction fYou = RelationUtil.getFaction(you); Faction fYou = RelationUtil.getFaction(you);
// This is a system invoker. Accept it. // This is a system invoker. Accept it.
if (fI == null) { if (fI == null) return true;
return true;
}
// Bypassing players can do any kind of transaction // Bypassing players can do any kind of transaction
if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) { if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) return true;
return true;
}
// Players with the any withdraw can do. // Players with the any withdraw can do.
if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) { if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) return true;
return true;
}
// You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again.
if (i == you) { if (i == you) return true;
return true;
}
// A faction can always transfer away the money of it's members and its own money... // 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. // 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. // Ohh by the way... Yes it could. For daily rent to the faction.
if (i == fI && fI == fYou) { if (i == fI && fI == fYou) return true;
return true;
}
// Factions can be controlled by members that are moderators... or any member if any member can withdraw. // Factions can be controlled by members that are moderators... or any member if any member can withdraw.
if (i instanceof FPlayer && you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer) i).getRole().value >= Role.MODERATOR.value)) { if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || (i instanceof FPlayer && ((FPlayer) i).getRole().value >= Role.MODERATOR.value)))
return true; return true;
}
// Otherwise you may not!;,,;
i.msg(TL.ECON_CANTCONTROLMONEY, i.describeTo(i, true), you.describeTo(i)); i.msg(TL.ECON_CANTCONTROLMONEY, i.describeTo(i, true), you.describeTo(i));
return false; return false;
} }
@@ -140,7 +112,7 @@ public class Econ {
public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) {
invoker.msg(TL.ECON_OFF); invoker.msg(TL.ECON_DISABLED);
return false; return false;
} }
@@ -154,30 +126,21 @@ public class Econ {
} }
// Check the rights // Check the rights
if (!canIControllYou(invoker, from)) { if (!canIControllYou(invoker, from)) return false;
return false;
}
OfflinePlayer fromAcc; OfflinePlayer fromAcc;
OfflinePlayer toAcc; OfflinePlayer toAcc;
if (isUUID(from.getAccountId())) { if (isUUID(from.getAccountId())) {
fromAcc = Bukkit.getOfflinePlayer(UUID.fromString(from.getAccountId())); fromAcc = Bukkit.getOfflinePlayer(UUID.fromString(from.getAccountId()));
if (fromAcc.getName() == null) { if (fromAcc.getName() == null) return false;
return false; } else fromAcc = Bukkit.getOfflinePlayer(from.getAccountId());
}
} else {
fromAcc = Bukkit.getOfflinePlayer(from.getAccountId());
}
if (isUUID(to.getAccountId())) { if (isUUID(to.getAccountId())) {
toAcc = Bukkit.getOfflinePlayer(UUID.fromString(to.getAccountId())); toAcc = Bukkit.getOfflinePlayer(UUID.fromString(to.getAccountId()));
if (toAcc.getName() == null) { if (toAcc.getName() == null) return false;
return false; } else toAcc = Bukkit.getOfflinePlayer(to.getAccountId());
}
} else {
toAcc = Bukkit.getOfflinePlayer(to.getAccountId());
}
// Is there enough money for the transaction to happen? // Is there enough money for the transaction to happen?
if (!econ.has(fromAcc, amount)) { if (!econ.has(fromAcc, amount)) {
@@ -185,13 +148,6 @@ public class Econ {
if (invoker != null && notify) { if (invoker != null && notify) {
invoker.msg(TL.COMMAND_MONEYTRANSFERFF_TRANSFERCANTAFFORD, from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); invoker.msg(TL.COMMAND_MONEYTRANSFERFF_TRANSFERCANTAFFORD, from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker));
} }
return false;
}
// Check if the new balance is over Essential's money cap.
if (Essentials.isOverBalCap(to, econ.getBalance(toAcc) + amount)) {
invoker.msg(TL.ECON_OVER_BAL_CAP, amount);
return false; return false;
} }
@@ -201,21 +157,15 @@ public class Econ {
if (erw.transactionSuccess()) { if (erw.transactionSuccess()) {
EconomyResponse erd = econ.depositPlayer(toAcc, amount); EconomyResponse erd = econ.depositPlayer(toAcc, amount);
if (erd.transactionSuccess()) { if (erd.transactionSuccess()) {
if (notify) { if (notify) sendTransferInfo(invoker, from, to, amount);
sendTransferInfo(invoker, from, to, amount);
}
return true; return true;
} else { } else econ.depositPlayer(fromAcc, amount);
// transaction failed, refund account
econ.depositPlayer(fromAcc, amount);
}
} }
// if we get here something with the transaction failed // if we get here something with the transaction failed
if (notify) { if (notify)
invoker.msg(TL.ECON_UNABLETOTRANSFER, moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); invoker.msg(TL.ECON_UNABLETOTRANSFER, moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true));
}
return false; return false;
} }
@@ -240,28 +190,22 @@ public class Econ {
recipients.addAll(getFplayers(to)); recipients.addAll(getFplayers(to));
if (invoker == null) { if (invoker == null) {
for (FPlayer recipient : recipients) { for (FPlayer recipient : recipients)
recipient.msg(TL.ECON_MONEYTRASFERREDFROM, moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); recipient.msg(TL.ECON_MONEYTRASFERREDFROM, moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
} else if (invoker == from) { } else if (invoker == from) {
for (FPlayer recipient : recipients) { for (FPlayer recipient : recipients)
recipient.msg(TL.ECON_PERSONGAVEMONEYTO, from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); recipient.msg(TL.ECON_PERSONGAVEMONEYTO, from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient));
}
} else if (invoker == to) { } else if (invoker == to) {
for (FPlayer recipient : recipients) { for (FPlayer recipient : recipients)
recipient.msg(TL.ECON_PERSONTOOKMONEYFROM, to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); recipient.msg(TL.ECON_PERSONTOOKMONEYFROM, to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient));
}
} else { } else {
for (FPlayer recipient : recipients) { for (FPlayer recipient : recipients)
recipient.msg(TL.ECON_MONEYTRASFERREDFROMPERSONTOPERSON, invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); recipient.msg(TL.ECON_MONEYTRASFERREDFROMPERSONTOPERSON, invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
} }
} }
public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) { public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) return true;
return true;
}
// going the hard way round as econ.has refuses to work. // going the hard way round as econ.has refuses to work.
boolean affordable = false; boolean affordable = false;
@@ -269,85 +213,59 @@ public class Econ {
if (isUUID(ep.getAccountId())) { if (isUUID(ep.getAccountId())) {
OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId()));
if (offline.getName() != null) { if (offline.getName() != null)
currentBalance = econ.getBalance(Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId()))); currentBalance = econ.getBalance(Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())));
} else { else currentBalance = 0;
currentBalance = 0; } else currentBalance = econ.getBalance(ep.getAccountId());
} if (currentBalance >= delta) affordable = true;
} else {
currentBalance = econ.getBalance(ep.getAccountId());
}
if (currentBalance >= delta) {
affordable = true;
}
if (!affordable) { if (!affordable) {
if (toDoThis != null && !toDoThis.isEmpty()) { if (toDoThis != null && !toDoThis.isEmpty())
ep.msg(TL.COMMAND_MONEY_CANTAFFORD, ep.describeTo(ep, true), moneyString(delta), toDoThis); ep.msg(TL.COMMAND_MONEY_CANTAFFORD, ep.describeTo(ep, true), moneyString(delta), toDoThis);
}
return false; return false;
} }
return true; return true;
} }
public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) return false;
return false;
}
OfflinePlayer acc; OfflinePlayer acc;
if (isUUID(ep.getAccountId())) { if (isUUID(ep.getAccountId())) {
acc = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); acc = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId()));
if (acc.getName() == null) { if (acc.getName() == null) return false;
return false; } else acc = Bukkit.getOfflinePlayer(ep.getAccountId());
} String you = ep.describeTo(ep, true);
} else {
acc = Bukkit.getOfflinePlayer(ep.getAccountId());
}
String You = ep.describeTo(ep, true); if (delta == 0) return true;
else if (delta > 0) {
if (delta == 0) {
// no money actually transferred?
// ep.msg("<h>%s<i> didn't have to pay anything %s.", You, forDoingThis); // might be for gains, might be for losses
return true;
}
if (delta > 0) {
// The player should gain money // The player should gain money
// The account might not have enough space // The account might not have enough space
EconomyResponse er = econ.depositPlayer(acc, delta); EconomyResponse er = econ.depositPlayer(acc, delta);
if (er.transactionSuccess()) { if (er.transactionSuccess()) {
modifyUniverseMoney(-delta); modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty()) { if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg(TL.COMMAND_MONEY_GAINED, You, moneyString(delta), forDoingThis); ep.msg(TL.COMMAND_MONEY_GAINED, you, moneyString(delta), forDoingThis);
}
return true; return true;
} else { } else {
// transfer to account failed // transfer to account failed
if (forDoingThis != null && !forDoingThis.isEmpty()) { if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg(TL.ECON_DEPOSITFAILED, You, moneyString(delta), forDoingThis); ep.msg(TL.ECON_DEPOSITFAILED, you, moneyString(delta), forDoingThis);
}
return false; return false;
} }
} else { } else {
// The player should loose money // The player should loose money
// The player might not have enough. // The player might not have enough.
if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) { if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) {
// There is enough money to pay // There is enough money to pay
modifyUniverseMoney(-delta); modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty()) { if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg(TL.ECON_MONEYLOST, You, moneyString(-delta), forDoingThis); ep.msg(TL.ECON_MONEYLOST, you, moneyString(-delta), forDoingThis);
}
return true; return true;
} else { } else {
// There was not enough money to pay // There was not enough money to pay
if (toDoThis != null && !toDoThis.isEmpty()) { if (toDoThis != null && !toDoThis.isEmpty())
ep.msg(TL.ECON_CANTAFFORD, You, moneyString(-delta), toDoThis); ep.msg(TL.ECON_CANTAFFORD, you, moneyString(-delta), toDoThis);
}
return false; return false;
} }
} }
@@ -359,10 +277,7 @@ public class Econ {
// calculate the cost for claiming land // calculate the cost for claiming land
public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) { public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) return 0d;
return 0d;
}
// basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction // 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); return Conf.econCostClaimWilderness + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0);
} }
@@ -375,9 +290,7 @@ public class Econ {
// calculate value of all owned land // calculate value of all owned land
public static double calculateTotalLandValue(int ownedLand) { public static double calculateTotalLandValue(int ownedLand) {
double amount = 0; double amount = 0;
for (int x = 0; x < ownedLand; x++) { for (int x = 0; x < ownedLand; x++) amount += calculateClaimCost(x, false);
amount += calculateClaimCost(x, false);
}
return amount; return amount;
} }
@@ -401,9 +314,7 @@ public class Econ {
public static String getFriendlyBalance(UUID uuid) { public static String getFriendlyBalance(UUID uuid) {
OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid);
if (offline.getName() == null) { if (offline.getName() == null) return "0";
return "0";
}
return format.format(econ.getBalance(offline)); return format.format(econ.getBalance(offline));
} }
@@ -413,19 +324,13 @@ public class Econ {
public static boolean setBalance(String account, double amount) { public static boolean setBalance(String account, double amount) {
double current = econ.getBalance(account); double current = econ.getBalance(account);
if (current > amount) { if (current > amount) return econ.withdrawPlayer(account, current - amount).transactionSuccess();
return econ.withdrawPlayer(account, current - amount).transactionSuccess(); else return econ.depositPlayer(account, amount - current).transactionSuccess();
} else {
return econ.depositPlayer(account, amount - current).transactionSuccess();
}
} }
public static boolean modifyBalance(String account, double amount) { public static boolean modifyBalance(String account, double amount) {
if (amount < 0) { if (amount < 0) return econ.withdrawPlayer(account, -amount).transactionSuccess();
return econ.withdrawPlayer(account, -amount).transactionSuccess(); else return econ.depositPlayer(account, amount).transactionSuccess();
} else {
return econ.depositPlayer(account, amount).transactionSuccess();
}
} }
public static boolean deposit(String account, double amount) { public static boolean deposit(String account, double amount) {

View File

@@ -4,47 +4,30 @@ import com.earth2me.essentials.Teleport;
import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.iface.EconomyParticipator;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.plugin.Plugin; import org.bukkit.metadata.MetadataValue;
import java.math.BigDecimal; import java.math.BigDecimal;
public class Essentials { public class Essentials {
/**
* @author FactionsUUID Team
*/
private static IEssentials essentials; private static IEssentials essentials;
public static void setup() { public static void setup() {
Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); essentials = (IEssentials) Bukkit.getPluginManager().getPlugin("Essentials");
if (ess != null) {
essentials = (IEssentials) ess;
}
}
public static boolean isOverBalCap(EconomyParticipator participator, double amount) {
if (essentials == null) {
return false;
}
return amount > essentials.getSettings().getMaxMoney().doubleValue();
} }
// return false if feature is disabled or Essentials isn't available // return false if feature is disabled or Essentials isn't available
public static boolean handleTeleport(Player player, Location loc) { public static boolean handleTeleport(Player player, Location loc) {
if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) { if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) return false;
return false;
}
Teleport teleport = essentials.getUser(player).getTeleport(); Teleport teleport = essentials.getUser(player).getTeleport();
Trade trade = new Trade(new BigDecimal(Conf.econCostHome), essentials); Trade trade = new Trade(BigDecimal.valueOf(Conf.econCostHome), essentials);
try { try {
teleport.teleport(loc, trade, TeleportCause.PLUGIN); teleport.teleport(loc, trade, TeleportCause.PLUGIN);
} catch (Exception e) { } catch (Exception e) {
@@ -54,8 +37,21 @@ public class Essentials {
} }
public static boolean isVanished(Player player) { public static boolean isVanished(Player player) {
if (essentials == null) return false; // Edge case handling.
User user = essentials.getUser(player); if (player == null) return false;
return user != null && user.isVanished(); boolean vanish = false;
if (essentials != null) {
User user = essentials.getUser(player);
if (user != null && user.isVanished()) return true;
}
if (player.hasMetadata("vanished"))
for (MetadataValue meta : player.getMetadata("vanished")) {
if (meta == null) continue;
if (meta.asBoolean()) {
vanish = true;
break;
}
}
return vanish;
} }
} }

View File

@@ -159,7 +159,6 @@ public class Worldguard {
FactionsPlugin.getInstance().log("We failed to load Vector Classes from WorldGuard! Support will be removed!"); FactionsPlugin.getInstance().log("We failed to load Vector Classes from WorldGuard! Support will be removed!");
FactionsPlugin.getInstance().log("WorldGuard 7.0.0 support is currently in BETA. Please be careful!"); FactionsPlugin.getInstance().log("WorldGuard 7.0.0 support is currently in BETA. Please be careful!");
regionContainer = null; regionContainer = null;
return;
} }
} }
} }

View File

@@ -26,20 +26,17 @@ public class EngineDynmap {
// CONSTANTS // CONSTANTS
// -------------------------------------------- // // -------------------------------------------- //
public final static int BLOCKS_PER_CHUNK = 16; public static final int BLOCKS_PER_CHUNK = 16;
public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; public static final String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e";
public final static String FACTIONS = "factions"; public static final String FACTIONS = "factions";
public final static String FACTIONS_ = FACTIONS + "_"; public static final String FACTIONS_ = FACTIONS + "_";
public static final String FACTIONS_MARKERSET = FACTIONS_ + "markerset";
public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; public static final String FACTIONS_HOME = FACTIONS_ + "home";
public static final String FACTIONS_HOME_ = FACTIONS_HOME + "_";
public final static String FACTIONS_HOME = FACTIONS_ + "home"; public static final String FACTIONS_PLAYERSET = FACTIONS_ + "playerset";
public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; public static final String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_";
public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset";
public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_";
// -------------------------------------------- // // -------------------------------------------- //
// INSTANCE & CONSTRUCT // INSTANCE & CONSTRUCT
@@ -277,13 +274,13 @@ public class EngineDynmap {
String world = entry.getKey().getWorldName(); String world = entry.getKey().getWorldName();
Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue());
Map<Faction, Set<FLocation>> factionChunks = worldFactionChunks.get(world); Map<Faction, Set<FLocation>> factionChunks = worldFactionChunks.computeIfAbsent(world, s -> null);
if (factionChunks == null) { if (factionChunks == null) {
factionChunks = new HashMap<>(); factionChunks = new HashMap<>();
worldFactionChunks.put(world, factionChunks); worldFactionChunks.put(world, factionChunks);
} }
Set<FLocation> factionTerritory = factionChunks.get(chunkOwner); Set<FLocation> factionTerritory = factionChunks.computeIfAbsent(chunkOwner, s -> null);
if (factionTerritory == null) { if (factionTerritory == null) {
factionTerritory = new HashSet<>(); factionTerritory = new HashSet<>();
factionChunks.put(chunkOwner, factionTerritory); factionChunks.put(chunkOwner, factionTerritory);
@@ -735,8 +732,7 @@ public class EngineDynmap {
} }
// Find all contiguous blocks, set in target and clear in source // Find all contiguous blocks, set in target and clear in source
private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { private void floodFillTarget(TileFlags source, TileFlags destination, int x, int y) {
int cnt = 0;
ArrayDeque<int[]> stack = new ArrayDeque<>(); ArrayDeque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{x, y}); stack.push(new int[]{x, y});
@@ -747,7 +743,6 @@ public class EngineDynmap {
if (source.getFlag(x, y)) { // Set in src if (source.getFlag(x, y)) { // Set in src
source.setFlag(x, y, false); // Clear source source.setFlag(x, y, false); // Clear source
destination.setFlag(x, y, true); // Set in destination destination.setFlag(x, y, true); // Set in destination
cnt++;
if (source.getFlag(x + 1, y)) { if (source.getFlag(x + 1, y)) {
stack.push(new int[]{x + 1, y}); stack.push(new int[]{x + 1, y});
} }
@@ -762,7 +757,6 @@ public class EngineDynmap {
} }
} }
} }
return cnt;
} }
enum Direction { enum Direction {

View File

@@ -15,7 +15,7 @@ public class TempMarkerSet {
public boolean hideByDefault; public boolean hideByDefault;
public MarkerSet create(MarkerAPI markerApi, String id) { public MarkerSet create(MarkerAPI markerApi, String id) {
MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent") MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not persistent")
if (ret == null) { if (ret == null) {
return null; return null;
@@ -41,10 +41,8 @@ public class TempMarkerSet {
markerset.setMarkerSetLabel(this.label); markerset.setMarkerSetLabel(this.label);
} }
if (this.minimumZoom > 0) { if (this.minimumZoom > 0 && markerset.getMinZoom() != this.minimumZoom) {
if (markerset.getMinZoom() != this.minimumZoom) {
markerset.setMinZoom(this.minimumZoom); markerset.setMinZoom(this.minimumZoom);
}
} }
if (markerset.getLayerPriority() != this.priority) { if (markerset.getLayerPriority() != this.priority) {

View File

@@ -27,7 +27,6 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.*; import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
@@ -48,6 +47,8 @@ public class FactionsBlockListener implements Listener {
public static HashMap<String, Location> bannerLocations = new HashMap<>(); public static HashMap<String, Location> bannerLocations = new HashMap<>();
private HashMap<String, Boolean> bannerCooldownMap = new HashMap<>(); private HashMap<String, Boolean> bannerCooldownMap = new HashMap<>();
private long placeTimer = TimeUnit.SECONDS.toMillis(15L); private long placeTimer = TimeUnit.SECONDS.toMillis(15L);
private static final String varFac = "{faction}";
private static final String varAction = "{action}";
public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) {
@@ -62,9 +63,8 @@ public class FactionsBlockListener implements Listener {
if (otherFaction.isWilderness()) { if (otherFaction.isWilderness()) {
if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) return true; if (Conf.worldGuardBuildPriority && Worldguard.getInstance().playerCanBuild(player, location)) return true;
if (location.getWorld() != null) { if (location.getWorld() != null && !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) {
if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) return true;
return true;
} }
if (!justCheck) me.msg(TL.ACTION_DENIED_WILDERNESS, action); if (!justCheck) me.msg(TL.ACTION_DENIED_WILDERNESS, action);
return false; return false;
@@ -94,24 +94,27 @@ public class FactionsBlockListener implements Listener {
boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty()); boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty());
if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId()))) if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId())))
return true; return true;
else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) { else {
me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); String replace = TL.ACTIONS_NOPERMISSIONPAIN.toString().replace(varAction, action.toString());
if (shouldHurt) { if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) {
player.damage(Conf.actionDeniedPainAmount); me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc)));
me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); if (shouldHurt) {
} player.damage(Conf.actionDeniedPainAmount);
return false; me.msg(replace.replace(varFac, Board.getInstance().getFactionAt(loc).getTag(myFaction)));
} else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway }
if (shouldHurt) { return false;
player.damage(Conf.actionDeniedPainAmount); } else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway
if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null) if (shouldHurt) {
me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); player.damage(Conf.actionDeniedPainAmount);
} if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null)
if (myFaction.getTag(me.getFaction()) != null && action != null) me.msg(replace.replace(varFac, Board.getInstance().getFactionAt(loc).getTag(myFaction)));
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); }
return false; if (myFaction.getTag(me.getFaction()) != null && action != null)
} else if (access == Access.ALLOW) return true; me.msg(TL.ACTIONS_NOPERMISSION.toString().replace(varFac, myFaction.getTag(me.getFaction())).replace(varAction, action.toString()));
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); return false;
} else if (access == Access.ALLOW) return true;
}
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace(varFac, myFaction.getTag(me.getFaction())).replace(varAction, action.toString()));
return false; return false;
} }
@@ -119,10 +122,10 @@ public class FactionsBlockListener implements Listener {
if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) { if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) {
// If pain should be applied // If pain should be applied
if (pain && Conf.ownedAreaPainBuild) if (pain && Conf.ownedAreaPainBuild)
me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace("{action}", action.toString()).replace("{faction}", target.getOwnerListString(location))); me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace(varAction, action.toString()).replace(varFac, target.getOwnerListString(location)));
if (Conf.ownedAreaDenyBuild && pain) return false; if (Conf.ownedAreaDenyBuild && pain) return false;
else if (Conf.ownedAreaDenyBuild) { else if (Conf.ownedAreaDenyBuild) {
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag(me.getFaction())).replace("{action}", action.toString())); me.msg(TL.ACTIONS_NOPERMISSION.toString().replace(varFac, target.getTag(me.getFaction())).replace(varAction, action.toString()));
return false; return false;
} }
} }
@@ -169,29 +172,31 @@ public class FactionsBlockListener implements Listener {
return; return;
} }
if (isSpawner) { if (isSpawner && Conf.spawnerLock) {
if (Conf.spawnerLock) { event.setCancelled(true);
event.setCancelled(true); event.getPlayer().sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_SPAWNER_LOCK_CANNOT_PLACE.toString()));
event.getPlayer().sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_SPAWNER_LOCK_CANNOT_PLACE.toString()));
}
} }
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) { public void onBlockFromTo(BlockFromToEvent event) {
if (!Conf.handleExploitLiquidFlow) return; if (!Conf.handleExploitLiquidFlow) return;
if (event.getBlock().isLiquid()) {
if (event.getToBlock().isEmpty()) { if (event.getBlock().isLiquid() && event.getToBlock().isEmpty()) {
Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock()));
Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock()));
if (from == to) return; if (from == to) return;
// from faction != to faction // from faction != to faction
if (to.isNormal()) { if (to.isSystemFaction()) {
if (from.isNormal() && from.getRelationTo(to).isAlly()) { event.setCancelled(true);
return; return;
} }
event.setCancelled(true);
if (to.isNormal()) {
if (from.isNormal() && from.getRelationTo(to).isAlly()) {
return;
} }
event.setCancelled(true);
} }
} }
} }
@@ -212,7 +217,7 @@ public class FactionsBlockListener implements Listener {
Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1); 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 potentially pushing into air/water/lava in another territory, we need to check it out
if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && canPistonMoveBlock(pistonFaction, targetBlock.getLocation()))
event.setCancelled(true); event.setCancelled(true);
} }
@@ -281,12 +286,10 @@ public class FactionsBlockListener implements Listener {
continue; continue;
} }
if (blockLoc.getBlock().getType() == XMaterial.CHEST.parseMaterial()) { if (blockLoc.getBlock().getType() == XMaterial.CHEST.parseMaterial() && factionAt.getVault().equals(blockLoc)) {
if (factionAt.getVault().equals(blockLoc)) { e.setCancelled(true);
e.setCancelled(true); fme.msg(TL.COMMAND_VAULT_NO_HOPPER);
fme.msg(TL.COMMAND_VAULT_NO_HOPPER); return;
return;
}
} }
} }
} }
@@ -311,7 +314,7 @@ public class FactionsBlockListener implements Listener {
// if potentially retracted block is just air/water/lava, no worries // if potentially retracted block is just air/water/lava, no worries
if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) return; if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) return;
Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock()));
if (!canPistonMoveBlock(pistonFaction, targetLoc)) event.setCancelled(true); if (canPistonMoveBlock(pistonFaction, targetLoc)) event.setCancelled(true);
} }
@EventHandler @EventHandler
@@ -321,11 +324,9 @@ public class FactionsBlockListener implements Listener {
return; return;
} }
if (bannerLocations.containsValue(e.getBlock().getLocation())) { if (bannerLocations.containsValue(e.getBlock().getLocation()) && e.getBlock().getType().name().contains("BANNER")) {
if (e.getBlock().getType().name().contains("BANNER")) { e.setCancelled(true);
e.setCancelled(true); fme.msg(TL.BANNER_CANNOT_BREAK);
fme.msg(TL.BANNER_CANNOT_BREAK);
}
} }
} }
@@ -425,7 +426,8 @@ public class FactionsBlockListener implements Listener {
if (!justCheck) fPlayer.setLastFrostwalkerMessage(); if (!justCheck) fPlayer.setLastFrostwalkerMessage();
// Check if they have build permissions here. If not, block this from happening. // Check if they have build permissions here. If not, block this from happening.
if (!playerCanBuildDestroyBlock(player, location, PermissableAction.FROST_WALK.toString(), justCheck)) event.setCancelled(true); if (!playerCanBuildDestroyBlock(player, location, PermissableAction.FROST_WALK.toString(), justCheck))
event.setCancelled(true);
} }
@EventHandler @EventHandler
@@ -443,15 +445,15 @@ public class FactionsBlockListener implements Listener {
private boolean canPistonMoveBlock(Faction pistonFaction, Location target) { private boolean canPistonMoveBlock(Faction pistonFaction, Location target) {
Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target)); Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target));
if (pistonFaction == otherFaction) return true; if (pistonFaction == otherFaction) return false;
if (otherFaction.isWilderness()) if (otherFaction.isWilderness())
return !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()); return Conf.wildernessDenyBuild && !Conf.worldsNoWildernessProtection.contains(target.getWorld().getName());
else if (otherFaction.isSafeZone()) return !Conf.safeZoneDenyBuild; else if (otherFaction.isSafeZone()) return Conf.safeZoneDenyBuild;
else if (otherFaction.isWarZone()) return !Conf.warZoneDenyBuild; else if (otherFaction.isWarZone()) return Conf.warZoneDenyBuild;
Relation rel = pistonFaction.getRelationTo(otherFaction); Relation rel = pistonFaction.getRelationTo(otherFaction);
return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); return rel.confDenyBuild(otherFaction.hasPlayersOnline());
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@@ -499,15 +501,12 @@ public class FactionsBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void FrameRemove(HangingBreakByEntityEvent event) { public void frameRemove(HangingBreakByEntityEvent event) {
if (event.getRemover() == null) return; if (event.getRemover() == null) return;
if ((event.getRemover() instanceof Player)) { if ((event.getRemover() instanceof Player) && event.getEntity().getType().equals(EntityType.ITEM_FRAME)) {
if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) { Player p = (Player) event.getRemover();
Player p = (Player) event.getRemover(); if (!playerCanBuildDestroyBlock(p, event.getEntity().getLocation(), "destroy", true)) {
if (!playerCanBuildDestroyBlock(p, event.getEntity().getLocation(), "destroy", true)) { event.setCancelled(true);
event.setCancelled(true);
return;
}
} }
} }
} }

View File

@@ -87,7 +87,7 @@ public class FactionsChatListener implements Listener {
fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message); fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message);
} }
} }
FactionChatHandler.sendMessage(FactionsPlugin.getInstance(), myFaction, me.getPlayer().getUniqueId(), me.getPlayer().getName(), event.getMessage()); FactionChatHandler.sendMessage(myFaction, me.getPlayer().getUniqueId(), me.getPlayer().getName(), event.getMessage());
event.setCancelled(true); event.setCancelled(true);
} else if (chat == ChatMode.ALLIANCE) { } else if (chat == ChatMode.ALLIANCE) {
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();

View File

@@ -143,7 +143,7 @@ public class FactionsEntityListener implements Listener {
} else { } else {
// we don't want to let mobs/arrows destroy item frames/armor stands // we don't want to let mobs/arrows destroy item frames/armor stands
// so we only have to run the check as if there had been an explosion at the damager location // so we only have to run the check as if there had been an explosion at the damager location
if (!this.checkExplosionForBlock(damager, damagee.getLocation().getBlock())) if (this.checkExplosionForBlock(damager, damagee.getLocation().getBlock()))
event.setCancelled(true); event.setCancelled(true);
} }
// we don't need to go after // we don't need to go after
@@ -216,7 +216,7 @@ public class FactionsEntityListener implements Listener {
Entity boomer = event.getEntity(); Entity boomer = event.getEntity();
// Before we need to check the location where the block is placed // Before we need to check the location where the block is placed
if (!this.checkExplosionForBlock(boomer, event.getLocation().getBlock())) { if (this.checkExplosionForBlock(boomer, event.getLocation().getBlock())) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@@ -224,7 +224,7 @@ public class FactionsEntityListener implements Listener {
// Loop the blocklist to run checks on each aimed block // Loop the blocklist to run checks on each aimed block
// The block don't have to explode // The block don't have to explode
event.blockList().removeIf(block -> !this.checkExplosionForBlock(boomer, block)); event.blockList().removeIf(block -> this.checkExplosionForBlock(boomer, block));
// Cancel the event if no block will explode // Cancel the event if no block will explode
if (!event.blockList().isEmpty() && (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { if (!event.blockList().isEmpty() && (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) {
@@ -259,7 +259,7 @@ public class FactionsEntityListener implements Listener {
Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation()));
if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom))
return false; return true;
// faction is peaceful and has explosions set to disabled // faction is peaceful and has explosions set to disabled
boolean online = faction.hasPlayersOnline(); boolean online = faction.hasPlayersOnline();
@@ -269,17 +269,17 @@ public class FactionsEntityListener implements Listener {
(faction.isWarZone() && Conf.warZoneBlockCreepers) || (faction.isWarZone() && Conf.warZoneBlockCreepers) ||
faction.isSafeZone())) { faction.isSafeZone())) {
// creeper which needs prevention // creeper which needs prevention
return false; return true;
} else if ( } 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 // 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 Wither) && (faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName()) || faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline) || faction.isWarZone() && Conf.warZoneBlockFireballs || faction.isSafeZone())) { (boomer instanceof Fireball || boomer instanceof Wither) && (faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName()) || faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline) || faction.isWarZone() && Conf.warZoneBlockFireballs || faction.isSafeZone())) {
// ghast fireball which needs prevention // ghast fireball which needs prevention
return false; return true;
} else } else
return (!(boomer instanceof TNTPrimed) && !(boomer instanceof ExplosiveMinecart)) || ((!faction.isWilderness() || !Conf.wildernessBlockTNT || Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) && return (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && ((faction.isWilderness() && Conf.wildernessBlockTNT && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) ||
(!faction.isNormal() || (online ? !Conf.territoryBlockTNT : !Conf.territoryBlockTNTWhenOffline)) && (faction.isNormal() && (online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline)) ||
(!faction.isWarZone() || !Conf.warZoneBlockTNT) && (faction.isWarZone() && Conf.warZoneBlockTNT) ||
(!faction.isSafeZone() || !Conf.safeZoneBlockTNT)); (faction.isSafeZone() && Conf.safeZoneBlockTNT));
// No condition retained, destroy the block! // No condition retained, destroy the block!
} }
@@ -311,7 +311,7 @@ public class FactionsEntityListener implements Listener {
if (thrower instanceof Player) { if (thrower instanceof Player) {
Player player = (Player) thrower; Player player = (Player) thrower;
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
if (badjuju && fPlayer.getFaction().isPeaceful()) { if (fPlayer.getFaction().isPeaceful()) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@@ -327,7 +327,6 @@ public class FactionsEntityListener implements Listener {
public boolean isPlayerInSafeZone(Entity damagee) { public boolean isPlayerInSafeZone(Entity damagee) {
if (!(damagee instanceof Player)) return false; if (!(damagee instanceof Player)) return false;
return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone();
} }
@@ -338,12 +337,8 @@ public class FactionsEntityListener implements Listener {
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) {
Entity damager = sub.getDamager(); Entity damager = sub.getDamager();
Entity damagee = sub.getEntity(); Entity damagee = sub.getEntity();
if (!(damagee instanceof Player)) return true; if (!(damagee instanceof Player)) return true;
FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee);
if (damager instanceof Player) { if (damager instanceof Player) {
FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager);
if (defender == null || defender.getPlayer() == null) return true; if (defender == null || defender.getPlayer() == null) return true;
@@ -358,12 +353,8 @@ public class FactionsEntityListener implements Listener {
} }
} }
} }
Location defenderLoc = defender.getPlayer().getLocation(); Location defenderLoc = defender.getPlayer().getLocation();
Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc));
// for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source
if (damager instanceof Projectile) { if (damager instanceof Projectile) {
Projectile projectile = (Projectile) damager; Projectile projectile = (Projectile) damager;
@@ -515,10 +506,8 @@ public class FactionsEntityListener implements Listener {
if (!(e.getRemover() instanceof Player)) return; if (!(e.getRemover() instanceof Player)) return;
Player p = (Player) e.getRemover(); Player p = (Player) e.getRemover();
if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME) { if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME && !FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) {
if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { e.setCancelled(true);
e.setCancelled(true);
}
} }
} }
@@ -526,11 +515,9 @@ public class FactionsEntityListener implements Listener {
public void onPaintingPlace(HangingPlaceEvent e) { public void onPaintingPlace(HangingPlaceEvent e) {
if (e.getPlayer() == null) return; if (e.getPlayer() == null) return;
if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME) { if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME && !FactionsBlockListener.playerCanBuildDestroyBlock(e.getPlayer(), e.getBlock().getLocation(), "build", false)) {
if (!FactionsBlockListener.playerCanBuildDestroyBlock(e.getPlayer(), e.getBlock().getLocation(), "build", false)) { e.setCancelled(true);
e.setCancelled(true); e.getPlayer().updateInventory();
e.getPlayer().updateInventory();
}
} }
} }
@@ -555,73 +542,37 @@ public class FactionsEntityListener implements Listener {
} }
/*
@EventHandler
public void onTravel(PlayerPortalEvent event) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("portals.limit", false))
return; // Don't do anything if they don't want us to.
TravelAgent agent = event.getPortalTravelAgent();
// If they aren't able to find a portal, it'll try to create one.
if (event.useTravelAgent() && agent.getCanCreatePortal() && agent.findPortal(event.getTo()) == null) {
FLocation loc = new FLocation(event.getTo());
Faction faction = Board.getInstance().getFactionAt(loc);
if (faction.isWilderness()) {
return; // We don't care about wilderness.
} else if (!faction.isNormal() && !event.getPlayer().isOp()) {
// Don't let non ops make portals in safezone or warzone.
event.setCancelled(true);
return;
}
FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer());
String mininumRelation = FactionsPlugin.getInstance().getConfig().getString("portals.minimum-relation", "MEMBER"); // Defaults to Neutral if typed wrong.
if (!fp.getFaction().getRelationTo(faction).isAtLeast(Relation.fromString(mininumRelation))) {
event.setCancelled(true);
}
}
}
*/
@EventHandler @EventHandler
public void onHit(EntityDamageByEntityEvent e) { public void onHit(EntityDamageByEntityEvent e) {
if (e.getDamager() instanceof Player) { if (e.getDamager() instanceof Player && e.getEntity() instanceof Player) {
if (e.getEntity() instanceof Player) { Player victim = (Player) e.getEntity();
Player victim = (Player) e.getEntity(); Player attacker = (Player) e.getDamager();
Player attacker = (Player) e.getDamager(); FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim);
FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); FPlayer fattacker = FPlayers.getInstance().getByPlayer(attacker);
FPlayer fattacker = FPlayers.getInstance().getByPlayer(attacker); if (fattacker.getRelationTo(fvictim) == Relation.TRUCE) {
if (fattacker.getRelationTo(fvictim) == Relation.TRUCE) { fattacker.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fattacker));
fattacker.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fattacker)); e.setCancelled(true);
e.setCancelled(true);
}
} }
} }
} }
@EventHandler @EventHandler
public void onBowHit(EntityDamageByEntityEvent e) { public void onBowHit(EntityDamageByEntityEvent e) {
if (e.getDamager() instanceof Projectile) { if (e.getDamager() instanceof Projectile && e.getEntity() instanceof Player) {
if (e.getEntity() instanceof Player) { Projectile arrow = ((Projectile) e.getDamager());
Projectile arrow = ((Projectile) e.getDamager()); if (arrow.getShooter() instanceof Player) {
if (arrow.getShooter() instanceof Player) { Player damager = (Player) ((Projectile) e.getDamager()).getShooter();
Player damager = (Player) ((Projectile) e.getDamager()).getShooter(); Player victim = (Player) e.getEntity();
Player victim = (Player) e.getEntity(); FPlayer fdamager = FPlayers.getInstance().getByPlayer(damager);
FPlayer fdamager = FPlayers.getInstance().getByPlayer(damager); FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim);
FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); if (damager == victim) return;
if (damager == victim) return; if (fdamager == fvictim) return;
if (fdamager == fvictim) return; if (fvictim.getRelationTo(fdamager) == Relation.TRUCE) {
if (fvictim.getRelationTo(fdamager) == Relation.TRUCE) { fdamager.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fdamager));
fdamager.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fdamager)); e.setCancelled(true);
e.setCancelled(true); }
} if (fvictim.getRelationTo(fdamager) == Relation.ENEMY && fvictim.isFlying()) {
if (fvictim.getRelationTo(fdamager) == Relation.ENEMY) { fvictim.setFFlying(false, true);
if (fvictim.isFlying()) {
fvictim.setFFlying(false, true);
}
}
} }
} }
} }

View File

@@ -4,7 +4,6 @@ import com.massivecraft.factions.*;
import com.massivecraft.factions.cmd.CmdFGlobal; import com.massivecraft.factions.cmd.CmdFGlobal;
import com.massivecraft.factions.cmd.CmdFly; import com.massivecraft.factions.cmd.CmdFly;
import com.massivecraft.factions.cmd.CmdSeeChunk; import com.massivecraft.factions.cmd.CmdSeeChunk;
import com.massivecraft.factions.cmd.FCmdRoot;
import com.massivecraft.factions.cmd.audit.FLogType; import com.massivecraft.factions.cmd.audit.FLogType;
import com.massivecraft.factions.cmd.logout.LogoutHandler; import com.massivecraft.factions.cmd.logout.LogoutHandler;
import com.massivecraft.factions.cmd.wild.CmdWild; import com.massivecraft.factions.cmd.wild.CmdWild;
@@ -56,8 +55,6 @@ import java.util.logging.Level;
public class FactionsPlayerListener implements Listener { public class FactionsPlayerListener implements Listener {
public static Set<FLocation> corners; public static Set<FLocation> corners;
public static BukkitTask positionTask = null;
public static Map<UUID, Location> lastLocations = new HashMap<>();
/** /**
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
@@ -191,7 +188,6 @@ public class FactionsPlayerListener implements Listener {
FLocation loc = new FLocation(block); FLocation loc = new FLocation(block);
Faction otherFaction = Board.getInstance().getFactionAt(loc); Faction otherFaction = Board.getInstance().getFactionAt(loc);
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();
Relation rel = myFaction.getRelationTo(otherFaction);
// no door/chest/whatever protection in wilderness, war zones, or safe zones // no door/chest/whatever protection in wilderness, war zones, or safe zones
if (otherFaction.isSystemFaction()) return true; if (otherFaction.isSystemFaction()) return true;
@@ -309,7 +305,7 @@ public class FactionsPlayerListener implements Listener {
if ((landOwned && factionToCheck.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(factionToCheck.getId()))) { if ((landOwned && factionToCheck.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(factionToCheck.getId()))) {
return true; return true;
} else if (landOwned && !factionToCheck.getOwnerListString(loc).contains(player.getName())) { } else if (landOwned && !factionToCheck.getOwnerListString(loc).contains(player.getName())) {
me.msg(TL.ACTIONS_OWNEDTERRITORYDENY, factionToCheck.getOwnerListString(loc)); me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", factionToCheck.getOwnerListString(loc)));
if (doPain) player.damage(Conf.actionDeniedPainAmount); if (doPain) player.damage(Conf.actionDeniedPainAmount);
return false; return false;
} else if (!landOwned && access == Access.ALLOW) { } else if (!landOwned && access == Access.ALLOW) {
@@ -385,6 +381,10 @@ public class FactionsPlayerListener implements Listener {
case CHEST_MINECART: case CHEST_MINECART:
case BARREL: case BARREL:
case COMPOSTER:
case LOOM:
case CARTOGRAPHY_TABLE:
case GRINDSTONE:
case SHULKER_BOX: case SHULKER_BOX:
case BLACK_SHULKER_BOX: case BLACK_SHULKER_BOX:
@@ -453,7 +453,6 @@ public class FactionsPlayerListener implements Listener {
case CHIPPED_ANVIL: case CHIPPED_ANVIL:
case DAMAGED_ANVIL: case DAMAGED_ANVIL:
case BREWING_STAND: case BREWING_STAND:
return PermissableAction.CONTAINER; return PermissableAction.CONTAINER;
default: default:
return null; return null;
@@ -474,6 +473,8 @@ public class FactionsPlayerListener implements Listener {
// Update the lastLoginTime for this fplayer // Update the lastLoginTime for this fplayer
me.setLastLoginTime(System.currentTimeMillis()); me.setLastLoginTime(System.currentTimeMillis());
lastLocations.put(player.getUniqueId(), player.getLocation());
// Store player's current FLocation and notify them where they are // Store player's current FLocation and notify them where they are
me.setLastStoodAt(new FLocation(player.getLocation())); me.setLastStoodAt(new FLocation(player.getLocation()));
@@ -517,19 +518,18 @@ public class FactionsPlayerListener implements Listener {
@EventHandler @EventHandler
public void onPlayerFall(EntityDamageEvent e) { public void onPlayerFall(EntityDamageEvent e) {
if (e.getEntity() instanceof Player) { if (e.getEntity() instanceof Player && e.getCause() == EntityDamageEvent.DamageCause.FALL) {
if (e.getCause() == EntityDamageEvent.DamageCause.FALL) { Player player = (Player) e.getEntity();
Player player = (Player) e.getEntity(); if (fallMap.containsKey(player)) {
if (fallMap.containsKey(player)) { e.setCancelled(true);
e.setCancelled(true); fallMap.remove(player);
fallMap.remove(player);
}
} }
} }
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
Player this_ = event.getPlayer();
FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer());
// Make sure player's power is up to date when they log off. // Make sure player's power is up to date when they log off.
@@ -546,6 +546,8 @@ public class FactionsPlayerListener implements Listener {
FactionsPlugin.instance.getTimers().remove(me.getPlayer().getUniqueId()); FactionsPlugin.instance.getTimers().remove(me.getPlayer().getUniqueId());
} }
lastLocations.remove(this_.getUniqueId());
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();
if (!myFaction.isWilderness()) myFaction.memberLoggedOff(); if (!myFaction.isWilderness()) myFaction.memberLoggedOff();
@@ -570,17 +572,19 @@ public class FactionsPlayerListener implements Listener {
.replace("{leader}", faction.getFPlayerAdmin() + ""); .replace("{leader}", faction.getFPlayerAdmin() + "");
return string; return string;
} }
@Deprecated
public void checkCanFly(FPlayer me) { public void checkCanFly(FPlayer me) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight") || !FactionsPlugin.instance.getConfig().getBoolean("ffly.AutoEnable")) if (!me.canFlyAtLocation() || me.checkIfNearbyEnemies()) {
if (me.isFlying())
me.setFFlying(false, false);
return; return;
if (me.isFlying()) return;
if (me.getPlayer().hasPermission(Permission.FLY_FLY.node)) {
me.setFFlying(true, false);
CmdFly.flyMap.put(me.getName(), true);
if (CmdFly.particleTask == null)
CmdFly.startParticles();
} }
if (me.isFlying() || !FactionsPlugin.instance.getConfig().getBoolean("ffly.AutoEnable"))
return;
me.setFFlying(true, false);
CmdFly.flyMap.put(me.getName(), true);
if (CmdFly.particleTask == null)
CmdFly.startParticles();
} }
//inspect //inspect
@@ -606,7 +610,7 @@ public class FactionsPlayerListener implements Listener {
fplayer.msg(TL.COMMAND_INSPECT_BYPASS); fplayer.msg(TL.COMMAND_INSPECT_BYPASS);
} }
List<String[]> info = CoreProtect.getInstance().getAPI().blockLookup(e.getClickedBlock(), 0); List<String[]> info = CoreProtect.getInstance().getAPI().blockLookup(e.getClickedBlock(), 0);
if (info.size() == 0) { if (info.isEmpty()) {
e.getPlayer().sendMessage(TL.COMMAND_INSPECT_NODATA.toString()); e.getPlayer().sendMessage(TL.COMMAND_INSPECT_NODATA.toString());
return; return;
} }
@@ -645,15 +649,16 @@ public class FactionsPlayerListener implements Listener {
return (result.length() == 3 ? result + "0" : result) + "/hrs ago"; return (result.length() == 3 ? result + "0" : result) + "/hrs ago";
} }
public static BukkitTask positionTask = null;
public final Map<UUID, Location> lastLocations = new HashMap<>();
public void startPositionCheck() { public void startPositionCheck() {
positionTask = Bukkit.getScheduler().runTaskTimer(FactionsPlugin.instance, () -> { positionTask = Bukkit.getScheduler().runTaskTimer(FactionsPlugin.getInstance(), () -> {
if (Bukkit.getOnlinePlayers().size() > 0) { if (lastLocations.isEmpty()) return;
for (Player player : Bukkit.getOnlinePlayers()) { for (Map.Entry<UUID, Location> check : lastLocations.entrySet()) {
if (!lastLocations.containsKey(player.getUniqueId())) { Player player = Bukkit.getPlayer(check.getKey());
lastLocations.put(player.getUniqueId(), player.getLocation()); if (player != null) {
continue; refreshPosition(player, check.getValue(), player.getLocation());
}
refreshPosition(player, lastLocations.get(player.getUniqueId()), player.getLocation());
lastLocations.put(player.getUniqueId(), player.getLocation()); lastLocations.put(player.getUniqueId(), player.getLocation());
} }
} }
@@ -719,16 +724,16 @@ public class FactionsPlayerListener implements Listener {
}, 5); }, 5);
} }
} }
if (FCmdRoot.instance.fFlyEnabled && CmdFly.autoenable && CmdFly.checkFly(me, me.getPlayer(), factionTo)) {
me.setFFlying(true, false);
CmdFly.flyMap.put(me.getName(), true);
if (CmdFly.particleTask == null)
CmdFly.startParticles();
}
checkCanFly(me);
Faction at = Board.getInstance().getFactionAt(new FLocation(me.getPlayer().getLocation()));
if (me.getAutoClaimFor() != null) { if (me.getAutoClaimFor() != null) {
me.attemptClaim(me.getAutoClaimFor(), newLocation, true); if (FactionsPlugin.cachedRadiusClaim && me.attemptClaim(me.getFaction(), me.getPlayer().getLocation(), true)) {
me.getFaction().getFPlayersWhereOnline(true).forEach(f -> f.msg(TL.CLAIM_CLAIMED, me.describeTo(f, true), me.getFaction().describeTo(f), at.describeTo(f)));
} else {
me.attemptClaim(me.getAutoClaimFor(), newLocation, true);
}
FactionsPlugin.instance.logFactionEvent(me.getAutoClaimFor(), FLogType.CHUNK_CLAIMS, me.getName(), CC.GreenB + "CLAIMED", String.valueOf(1), (new FLocation(player.getLocation())).formatXAndZ(",")); FactionsPlugin.instance.logFactionEvent(me.getAutoClaimFor(), FLogType.CHUNK_CLAIMS, me.getName(), CC.GreenB + "CLAIMED", String.valueOf(1), (new FLocation(player.getLocation())).formatXAndZ(","));
if (Conf.disableFlightOnFactionClaimChange) CmdFly.disableFlight(me); if (Conf.disableFlightOnFactionClaimChange) CmdFly.disableFlight(me);
} else if (me.isAutoSafeClaimEnabled()) { } else if (me.isAutoSafeClaimEnabled()) {
@@ -819,18 +824,14 @@ public class FactionsPlayerListener implements Listener {
// Do type null checks so if XMaterial has a parsing issue and fills null as a value it will not bypass. // Do type null checks so if XMaterial has a parsing issue and fills null as a value it will not bypass.
// territoryCancelAndAllowItemUseMaterial bypass the protection system but only if they're not clicking on territoryDenySwitchMaterials // territoryCancelAndAllowItemUseMaterial bypass the protection system but only if they're not clicking on territoryDenySwitchMaterials
// if they're clicking on territoryDenySwitchMaterials, let the protection system handle the permissions // if they're clicking on territoryDenySwitchMaterials, let the protection system handle the permissions
if (type != null && !Conf.territoryDenySwitchMaterials.contains(block.getType())) { if (type != null && !Conf.territoryDenySwitchMaterials.contains(block.getType()) && Conf.territoryCancelAndAllowItemUseMaterial.contains(type)) {
if (Conf.territoryCancelAndAllowItemUseMaterial.contains(type)) { return;
return;
}
} }
if (GetPermissionFromUsableBlock(block.getType()) != null) { if (GetPermissionFromUsableBlock(block.getType()) != null && !canPlayerUseBlock(player, block, false)) {
if (!canPlayerUseBlock(player, block, false)) { event.setCancelled(true);
event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY); return;
return;
}
} }
if (type != null && !playerCanUseItemHere(player, block.getLocation(), event.getItem().getType(), false, PermissableAction.ITEM)) { if (type != null && !playerCanUseItemHere(player, block.getLocation(), event.getItem().getType(), false, PermissableAction.ITEM)) {
@@ -841,27 +842,23 @@ public class FactionsPlayerListener implements Listener {
@EventHandler @EventHandler
public void onInventorySee(InventoryClickEvent e) { public void onInventorySee(InventoryClickEvent e) {
if (e.getCurrentItem() == null) if (e.getCurrentItem() == null) return;
return; if (!e.getView().getTitle().endsWith("'s Inventory")) return;
if (!e.getView().getTitle().endsWith("'s Inventory"))
return;
e.setCancelled(true); e.setCancelled(true);
} }
@EventHandler @EventHandler
public void onPlayerBoneMeal(PlayerInteractEvent event) { public void onPlayerBoneMeal(PlayerInteractEvent event) {
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && block.getType() == XMaterial.GRASS_BLOCK.parseMaterial() if (event.getAction() == Action.RIGHT_CLICK_BLOCK && block.getType() == XMaterial.GRASS_BLOCK.parseMaterial()
&& event.hasItem() && event.getItem().getType() == XMaterial.BONE_MEAL.parseMaterial()) { && event.hasItem() && event.getItem().getType() == XMaterial.BONE_MEAL.parseMaterial()
if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), block.getLocation(), PermissableAction.BUILD.name(), true)) { && !FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), block.getLocation(), PermissableAction.BUILD.name(), true)) {
FPlayer me = FPlayers.getInstance().getById(event.getPlayer().getUniqueId().toString()); FPlayer me = FPlayers.getInstance().getById(event.getPlayer().getUniqueId().toString());
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", "use bone meal")); me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", "use bone meal"));
event.setCancelled(true); event.setCancelled(true);
}
} }
} }
@@ -929,10 +926,8 @@ public class FactionsPlayerListener implements Listener {
player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_DAMAGE_TAKEN)); player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_DAMAGE_TAKEN));
} }
WaitExecutor.handleAction(player); WaitExecutor.handleAction(player);
if (CmdWild.teleporting.contains(player)) { if (CmdWild.teleporting.contains(player) && !FactionsPlugin.getInstance().getConfig().getBoolean("Wild.FallDamage") && e.getCause() == EntityDamageEvent.DamageCause.FALL) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("Wild.FallDamage") && e.getCause() == EntityDamageEvent.DamageCause.FALL) { e.setCancelled(true);
e.setCancelled(true);
}
} }
} }
} }
@@ -941,7 +936,6 @@ public class FactionsPlayerListener implements Listener {
public void onTeleport(PlayerTeleportEvent e) { public void onTeleport(PlayerTeleportEvent e) {
Player player = e.getPlayer(); Player player = e.getPlayer();
if (player == null) return;
LogoutHandler handler = LogoutHandler.getByName(player.getName()); LogoutHandler handler = LogoutHandler.getByName(player.getName());
if (handler.isLogoutActive(player)) { if (handler.isLogoutActive(player)) {
handler.cancelLogout(player); handler.cancelLogout(player);
@@ -969,7 +963,7 @@ public class FactionsPlayerListener implements Listener {
if (badGuy == null) return; if (badGuy == null) return;
// if player was banned (not just kicked), get rid of their stored info // if player was banned (not just kicked), get rid of their stored info
if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) { if (Conf.removePlayerDataWhenBanned && event.getReason().equals(Conf.removePlayerDataWhenBannedReason)) {
if (badGuy.getRole() == Role.LEADER) badGuy.getFaction().promoteNewLeader(); if (badGuy.getRole() == Role.LEADER) badGuy.getFaction().promoteNewLeader();
@@ -979,7 +973,7 @@ public class FactionsPlayerListener implements Listener {
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
final public void onFactionJoin(FPlayerJoinEvent event) { final void onFactionJoin(FPlayerJoinEvent event) {
FTeamWrapper.applyUpdatesLater(event.getFaction()); FTeamWrapper.applyUpdatesLater(event.getFaction());
} }
@@ -993,7 +987,7 @@ public class FactionsPlayerListener implements Listener {
} }
@EventHandler @EventHandler
public void AsyncPlayerChatEvent(AsyncPlayerChatEvent e) { public void asyncPlayerChatEvent(AsyncPlayerChatEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if (CmdFGlobal.toggled.contains(p.getUniqueId())) { if (CmdFGlobal.toggled.contains(p.getUniqueId())) {
@@ -1019,10 +1013,8 @@ public class FactionsPlayerListener implements Listener {
for (int i = l.size() - 1; i >= 0; i--) { // going backwards in the list to prevent a ConcurrentModificationException for (int i = l.size() - 1; i >= 0; i--) { // going backwards in the list to prevent a ConcurrentModificationException
Player recipient = l.get(i); Player recipient = l.get(i);
if (recipient != null) { if (recipient != null && CmdFGlobal.toggled.contains(recipient.getUniqueId())) {
if (CmdFGlobal.toggled.contains(recipient.getUniqueId())) { e.getRecipients().remove(recipient);
e.getRecipients().remove(recipient);
}
} }
} }
} }

View File

@@ -15,9 +15,6 @@ import org.bukkit.inventory.ItemStack;
*/ */
public class MenuListener implements Listener { public class MenuListener implements Listener {
public MenuListener() {
}
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if (event.getView().getTitle().equals("Faction Logs")) { if (event.getView().getTitle().equals("Faction Logs")) {

View File

@@ -137,7 +137,7 @@ public class FScoreboard {
updateObjective(); updateObjective();
} }
} }
}.runTaskLater(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("scoreboard.expiration", 7) * 20); }.runTaskLater(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("scoreboard.expiration", 7) * 20L);
} }
private void updateObjective() { private void updateObjective() {

View File

@@ -25,6 +25,8 @@ public class FTeamWrapper {
private final String teamName; private final String teamName;
private final Faction faction; private final Faction faction;
private final Set<OfflinePlayer> members = new HashSet<>(); private final Set<OfflinePlayer> members = new HashSet<>();
private static final String defaultPrefixes = "scoreboard.default-prefixes";
private static final String invisFactionMembers = "See-Invisible-Faction-Members";
private FTeamWrapper(Faction faction) { private FTeamWrapper(Faction faction) {
this.teamName = "faction_" + (factionTeamPtr++); this.teamName = "faction_" + (factionTeamPtr++);
@@ -44,7 +46,7 @@ public class FTeamWrapper {
return; return;
} }
if (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members")) { if (!FactionsPlugin.getInstance().getConfig().getBoolean(defaultPrefixes, false) || FactionsPlugin.getInstance().getConfig().getBoolean(invisFactionMembers)) {
return; return;
} }
@@ -66,7 +68,7 @@ public class FTeamWrapper {
return; return;
} }
if (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members")) { if (!FactionsPlugin.getInstance().getConfig().getBoolean(defaultPrefixes, false) || FactionsPlugin.getInstance().getConfig().getBoolean(invisFactionMembers)) {
return; return;
} }
@@ -158,7 +160,7 @@ public class FTeamWrapper {
} }
private void updatePrefixes() { private void updatePrefixes() {
if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { if (FactionsPlugin.getInstance().getConfig().getBoolean(defaultPrefixes, false)) {
for (FScoreboard fboard : teams.keySet()) { for (FScoreboard fboard : teams.keySet()) {
updatePrefix(fboard); updatePrefix(fboard);
} }
@@ -166,19 +168,19 @@ public class FTeamWrapper {
} }
private void updatePrefix(FScoreboard fboard) { private void updatePrefix(FScoreboard fboard) {
if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { if (FactionsPlugin.getInstance().getConfig().getBoolean(defaultPrefixes, false)) {
FPlayer fplayer = fboard.getFPlayer(); FPlayer fplayer = fboard.getFPlayer();
Team team = teams.get(fboard); Team team = teams.get(fboard);
boolean focused = false; boolean focused = false;
if (FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members", false)) { if (FactionsPlugin.getInstance().getConfig().getBoolean(invisFactionMembers, false)) {
team.setCanSeeFriendlyInvisibles(true); team.setCanSeeFriendlyInvisibles(true);
} }
if ((FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) && (fplayer.getFaction() != null) && (fplayer.getFaction().getFocused() != null)) { if ((FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) && (fplayer.getFaction() != null) && (fplayer.getFaction().getFocused() != null)) {
for (FPlayer fp : faction.getFPlayersWhereOnline(true)) { for (FPlayer fp : faction.getFPlayersWhereOnline(true)) {
if (fplayer.getFaction().getFocused().equalsIgnoreCase(fp.getName())) { if (fplayer.getFaction().getFocused().equalsIgnoreCase(fp.getName())) {
team.setPrefix(ChatColor.translateAlternateColorCodes('&', FactionsPlugin.getInstance().getConfig().getString("ffocus.Prefix", "&7»&b"))); team.setPrefix(ChatColor.translateAlternateColorCodes('&', Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getString("ffocus.Prefix", "&7»&b"))));
focused = true; focused = true;
} }
} }
@@ -191,7 +193,8 @@ public class FTeamWrapper {
prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString()); prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString());
prefix = prefix.replace("{faction}", prefix = prefix.replace("{faction}",
faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length()))); faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length())));
if ((team.getPrefix() == null) || (!team.getPrefix().equals(prefix))) { team.getPrefix();
if (!team.getPrefix().equals(prefix)) {
team.setPrefix(prefix); team.setPrefix(prefix);
} }
} }

View File

@@ -31,7 +31,17 @@ public class FInfoSidebar extends FSidebarProvider {
ListIterator<String> it = lines.listIterator(); ListIterator<String> it = lines.listIterator();
while (it.hasNext()) { while (it.hasNext()) {
it.set(replaceTags(faction, fplayer, it.next())); String next = it.next();
if (next == null) {
it.remove();
continue;
}
String replaced = replaceTags(faction, fplayer, next);
if (replaced == null) {
it.remove();
} else {
it.set(replaced);
}
} }
return lines; return lines;
} }

View File

@@ -45,15 +45,16 @@ public class ShopGUIFrame {
int items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false).size(); int items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false).size();
for (int a = 1; a <= items; a++) { for (int a = 1; a <= items; a++) {
String s = a + ""; String s = a + "";
int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".slot"); String varItems = "items.";
ItemStack material = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".block")).get().parseItem(); int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt(varItems + s + ".slot");
int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".cost"); ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString(varItems + s + ".block")).get().parseItem();
String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".name"); int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt(varItems + s + ".cost");
boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean("items." + s + ".glowing"); String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString(varItems + s + ".name");
List<String> lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".lore"); boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean(varItems + s + ".glowing");
List<String> lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList(varItems + s + ".lore");
ItemStack item = new ItemStack(material); assert item != null;
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(FactionsPlugin.instance.color(name)); meta.setDisplayName(FactionsPlugin.instance.color(name));
meta.addItemFlags(); meta.addItemFlags();

View File

@@ -55,9 +55,9 @@ public enum Role implements Permissable {
return COLEADER; return COLEADER;
case 4: case 4:
return LEADER; return LEADER;
default:
throw new IllegalStateException("Unexpected value: " + value);
} }
return null;
} }
public static Role fromString(String check) { public static Role fromString(String check) {
@@ -76,9 +76,9 @@ public enum Role implements Permissable {
case "recruit": case "recruit":
case "rec": case "rec":
return RECRUIT; return RECRUIT;
default:
throw new IllegalStateException("Unexpected value: " + check.toLowerCase());
} }
return null;
} }
public boolean isAtLeast(Role role) { public boolean isAtLeast(Role role) {

View File

@@ -17,27 +17,27 @@ public enum FactionTag implements Tag {
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
HOME_X("{x}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : Tag.isMinimalShow() ? null : "{ig}"), HOME_X("{x}", fac -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : Tag.isMinimalShow() ? null : "{ig}"),
HOME_Y("{y}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : Tag.isMinimalShow() ? null : "{ig}"), HOME_Y("{y}", fac -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : Tag.isMinimalShow() ? null : "{ig}"),
HOME_Z("{z}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : Tag.isMinimalShow() ? null : "{ig}"), HOME_Z("{z}", fac -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : Tag.isMinimalShow() ? null : "{ig}"),
CHUNKS("{chunks}", (fac) -> String.valueOf(fac.getLandRounded())), CHUNKS("{chunks}", fac -> String.valueOf(fac.getLandRounded())),
WARPS("{warps}", (fac) -> String.valueOf(fac.getWarps().size())), WARPS("{warps}", fac -> String.valueOf(fac.getWarps().size())),
HEADER("{header}", (fac, fp) -> FactionsPlugin.getInstance().txt.titleize(fac.getTag(fp))), HEADER("{header}", (fac, fp) -> FactionsPlugin.getInstance().txt.titleize(fac.getTag(fp))),
POWER("{power}", (fac) -> String.valueOf(fac.getPowerRounded())), POWER("{power}", fac -> String.valueOf(fac.getPowerRounded())),
MAX_POWER("{maxPower}", (fac) -> String.valueOf(fac.getPowerMaxRounded())), MAX_POWER("{maxPower}", fac -> String.valueOf(fac.getPowerMaxRounded())),
POWER_BOOST("{power-boost}", (fac) -> { POWER_BOOST("{power-boost}", fac -> {
double powerBoost = fac.getPowerBoost(); double powerBoost = fac.getPowerBoost();
return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")");
}), }),
LEADER("{leader}", (fac) -> { LEADER("{leader}", fac -> {
FPlayer fAdmin = fac.getFPlayerAdmin(); FPlayer fAdmin = fac.getFPlayerAdmin();
return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length());
}), }),
JOINING("{joining}", (fac) -> (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString())), JOINING("{joining}", fac -> (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString())),
FACTION("{faction}", (Function<Faction, String>) Faction::getTag), FACTION("{faction}", (Function<Faction, String>) Faction::getTag),
FACTION_RELATION_COLOR("{faction-relation-color}", (fac, fp) -> fp == null ? "" : fp.getColorTo(fac).toString()), FACTION_RELATION_COLOR("{faction-relation-color}", (fac, fp) -> fp == null ? "" : fp.getColorTo(fac).toString()),
HOME_WORLD("{world}", (fac) -> fac.hasHome() ? fac.getHome().getWorld().getName() : Tag.isMinimalShow() ? null : "{ig}"), HOME_WORLD("{world}", fac -> fac.hasHome() ? fac.getHome().getWorld().getName() : Tag.isMinimalShow() ? null : "{ig}"),
RAIDABLE("{raidable}", (fac) -> { RAIDABLE("{raidable}", fac -> {
if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false)) { if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false)) {
boolean raidable = fac.getLandRounded() >= fac.getPowerRounded(); boolean raidable = fac.getLandRounded() >= fac.getPowerRounded();
String str = raidable ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); String str = raidable ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString();
@@ -50,37 +50,35 @@ public enum FactionTag implements Tag {
return null; return null;
}), }),
ANNOUNCEMENT("{announcement}", (fac) -> { ANNOUNCEMENT("{announcement}", fac -> String.valueOf(fac.getAnnouncements())),
return String.valueOf(fac.getAnnouncements()); PEACEFUL("{peaceful}", fac -> fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""),
}), PERMANENT("permanent", fac -> fac.isPermanent() ? "permanent" : "{notPermanent}"), // no braces needed
PEACEFUL("{peaceful}", (fac) -> fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""), LAND_VALUE("{land-value}", fac -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("value")),
PERMANENT("permanent", (fac) -> fac.isPermanent() ? "permanent" : "{notPermanent}"), // no braces needed
LAND_VALUE("{land-value}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("value")),
DESCRIPTION("{description}", Faction::getDescription), DESCRIPTION("{description}", Faction::getDescription),
CREATE_DATE("{create-date}", (fac) -> TL.sdf.format(fac.getFoundedDate())), CREATE_DATE("{create-date}", fac -> TL.sdf.format(fac.getFoundedDate())),
LAND_REFUND("{land-refund}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")), LAND_REFUND("{land-refund}", fac -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")),
BANK_BALANCE("{faction-balance}", (fac) -> { BANK_BALANCE("{faction-balance}", fac -> {
if (Econ.shouldBeUsed()) { if (Econ.shouldBeUsed()) {
return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance");
} }
return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance");
}), }),
TNT_BALANCE("{tnt-balance}", (fac) -> { TNT_BALANCE("{tnt-balance}", fac -> {
if (FactionsPlugin.instance.getConfig().getBoolean("ftnt.Enabled")) { if (FactionsPlugin.instance.getConfig().getBoolean("ftnt.Enabled")) {
return String.valueOf(fac.getTnt()); return String.valueOf(fac.getTnt());
} }
return Tag.isMinimalShow() ? null : ""; return Tag.isMinimalShow() ? null : "";
}), }),
TNT_MAX("{tnt-max-balance}", (fac) -> { TNT_MAX("{tnt-max-balance}", fac -> {
if (FactionsPlugin.instance.getConfig().getBoolean("ftnt.Enabled")) { if (FactionsPlugin.instance.getConfig().getBoolean("ftnt.Enabled")) {
return String.valueOf(fac.getTntBankLimit()); return String.valueOf(fac.getTntBankLimit());
} }
return Tag.isMinimalShow() ? null : ""; return Tag.isMinimalShow() ? null : "";
}), }),
ALLIES_COUNT("{allies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ALLY))), ALLIES_COUNT("{allies}", fac -> String.valueOf(fac.getRelationCount(Relation.ALLY))),
ENEMIES_COUNT("{enemies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ENEMY))), ENEMIES_COUNT("{enemies}", fac -> String.valueOf(fac.getRelationCount(Relation.ENEMY))),
TRUCES_COUNT("{truces}", (fac) -> String.valueOf(fac.getRelationCount(Relation.TRUCE))), TRUCES_COUNT("{truces}", fac -> String.valueOf(fac.getRelationCount(Relation.TRUCE))),
ONLINE_COUNT("{online}", (fac, fp) -> { ONLINE_COUNT("{online}", (fac, fp) -> {
if (fp != null && fp.isOnline()) { if (fp != null && fp.isOnline()) {
return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size());
@@ -97,12 +95,12 @@ public enum FactionTag implements Tag {
return String.valueOf(fac.getFPlayersWhereOnline(false).size()); return String.valueOf(fac.getFPlayersWhereOnline(false).size());
} }
}), }),
FACTION_STRIKES("{faction-strikes}", (fac) -> String.valueOf(fac.getStrikes())), FACTION_STRIKES("{faction-strikes}", fac -> String.valueOf(fac.getStrikes())),
FACTION_POINTS("{faction-points}", (fac) -> String.valueOf(fac.getPoints())), FACTION_POINTS("{faction-points}", fac -> String.valueOf(fac.getPoints())),
FACTION_SIZE("{members}", (fac) -> String.valueOf(fac.getFPlayers().size())), FACTION_SIZE("{members}", fac -> String.valueOf(fac.getFPlayers().size())),
FACTION_KILLS("{faction-kills}", (fac) -> String.valueOf(fac.getKills())), FACTION_KILLS("{faction-kills}", fac -> String.valueOf(fac.getKills())),
FACTION_DEATHS("{faction-deaths}", (fac) -> String.valueOf(fac.getDeaths())), FACTION_DEATHS("{faction-deaths}", fac -> String.valueOf(fac.getDeaths())),
FACTION_BANCOUNT("{faction-bancount}", (fac) -> String.valueOf(fac.getBannedPlayers().size())), FACTION_BANCOUNT("{faction-bancount}", fac -> String.valueOf(fac.getBannedPlayers().size())),
; ;
private final String tag; private final String tag;
@@ -149,10 +147,7 @@ public enum FactionTag implements Tag {
if (!this.foundInString(text)) { if (!this.foundInString(text)) {
return text; return text;
} }
String result = null; String result = this.function == null ? this.biFunction.apply(faction, player) : this.function.apply(faction);
if (this.biFunction != null) {
result = this.function == null ? this.biFunction.apply(faction, player) : this.function.apply(faction);
}
return result == null ? null : text.replace(this.tag, result); return result == null ? null : text.replace(this.tag, result);
} }

View File

@@ -177,7 +177,7 @@ public enum FancyTag implements Tag {
public List getMessage(String text, Faction faction, FPlayer player, Map<UUID, String> groupMap) { public List getMessage(String text, Faction faction, FPlayer player, Map<UUID, String> groupMap) {
if (!this.foundInString(text)) { if (!this.foundInString(text)) {
return Collections.EMPTY_LIST; // We really, really shouldn't be here. return Collections.emptyList(); // We really, really shouldn't be here.
} }
return this.function.apply(faction, player, text.replace(this.getTag(), ""), groupMap); return this.function.apply(faction, player, text.replace(this.getTag(), ""), groupMap);
} }

View File

@@ -21,6 +21,7 @@ public enum PlayerTag implements Tag {
}), }),
PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))), PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))),
PLAYER_POWER("{player-power}", (fp) -> String.valueOf(fp.getPowerRounded())), PLAYER_POWER("{player-power}", (fp) -> String.valueOf(fp.getPowerRounded())),
ROLE("{player-role}", FPlayer::getRolePrefix),
PLAYER_MAXPOWER("{player-maxpower}", (fp) -> String.valueOf(fp.getPowerMaxRounded())), PLAYER_MAXPOWER("{player-maxpower}", (fp) -> String.valueOf(fp.getPowerMaxRounded())),
PLAYER_KILLS("{player-kills}", (fp) -> String.valueOf(fp.getKills())), PLAYER_KILLS("{player-kills}", (fp) -> String.valueOf(fp.getKills())),
PLAYER_DEATHS("{player-deaths}", (fp) -> String.valueOf(fp.getDeaths())), PLAYER_DEATHS("{player-deaths}", (fp) -> String.valueOf(fp.getDeaths())),

View File

@@ -10,8 +10,8 @@ import java.util.logging.Level;
public class AutoLeaveProcessTask extends BukkitRunnable { public class AutoLeaveProcessTask extends BukkitRunnable {
private transient boolean readyToGo = false; private transient boolean readyToGo;
private transient boolean finished = false; private transient boolean finished;
private transient ListIterator<FPlayer> iterator; private transient ListIterator<FPlayer> iterator;
private transient double toleranceMillis; private transient double toleranceMillis;

View File

@@ -14,7 +14,10 @@ import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational { public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational {
@@ -210,16 +213,45 @@ public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements R
return String.valueOf(faction.getMaxVaults()); return String.valueOf(faction.getMaxVaults());
case "faction_relation_color": case "faction_relation_color":
return fPlayer.getColorTo(faction).toString(); return fPlayer.getColorTo(faction).toString();
case "faction_grace_time": case "grace_time":
return String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)); if(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() >= 0) {
return String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true));
} else {
return TL.GRACE_DISABLED_PLACEHOLDER.toString();
}
case "faction_name_at_location": case "faction_name_at_location":
Faction factionAtLocation = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); Faction factionAtLocation = Board.getInstance().getFactionAt(new FLocation(player.getLocation()));
return factionAtLocation != null ? factionAtLocation.getTag() : Factions.getInstance().getWilderness().getTag(); return factionAtLocation != null ? factionAtLocation.getTag() : Factions.getInstance().getWilderness().getTag();
} }
//If its not hardcoded lets try to grab it anyways
boolean targetFaction = false;
Object target = fPlayer;
String stripped = "";
if (placeholder.startsWith("faction_")) {
targetFaction = true;
target = faction;
stripped = placeholder.replace("faction_", "");
} else {
stripped = placeholder.replace("player_", "");
}
try {
Object pulled;
if (targetFaction) {
pulled = Faction.class.getDeclaredMethod(stripped).invoke(target);
} else {
pulled = FPlayer.class.getDeclaredMethod(stripped).invoke(target);
}
return String.valueOf(pulled);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
logInvalid(stripped);
}
return null; return TL.PLACEHOLDERAPI_NULL.toString();
} }
private static void logInvalid(String placeholder) {
FactionsPlugin.getInstance().getLogger().log(Level.INFO, "Invalid request through PlaceholderAPI for placeholder '" + placeholder + "'");
}
private int countOn(Faction f, Relation relation, Boolean status, FPlayer player) { private int countOn(Faction f, Relation relation, Boolean status, FPlayer player) {
int count = 0; int count = 0;

View File

@@ -19,7 +19,7 @@ public class Cooldown {
} }
public static boolean isOnCooldown(Player player, String name) { public static boolean isOnCooldown(Player player, String name) {
if (!player.hasMetadata(name) || player.getMetadata(name).size() <= 0) return false; if (!player.hasMetadata(name) || player.getMetadata(name).isEmpty()) return false;
long time = player.getMetadata(name).get(0).asLong(); long time = player.getMetadata(name).get(0).asLong();
return (time > System.currentTimeMillis()); return (time > System.currentTimeMillis());
} }

View File

@@ -2,6 +2,7 @@ package com.massivecraft.factions.util;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@@ -26,7 +27,9 @@ public class CornerTask extends BukkitRunnable {
cancel(); cancel();
} else { } else {
FLocation fLocation = surrounding.remove(0); FLocation fLocation = surrounding.remove(0);
if (fPlayer.attemptClaim(fPlayer.getFaction(), fLocation, true)) { if (FactionsPlugin.cachedRadiusClaim && fPlayer.attemptClaim(fPlayer.getFaction(), fLocation, true)) {
++amount;
} else if (fPlayer.attemptClaim(fPlayer.getFaction(), fLocation, true)) {
++amount; ++amount;
} else { } else {
fPlayer.sendMessage(TL.COMMAND_CORNER_FAIL_WITH_FEEDBACK.toString().replace("&", "§") + amount); fPlayer.sendMessage(TL.COMMAND_CORNER_FAIL_WITH_FEEDBACK.toString().replace("&", "§") + amount);

View File

@@ -15,7 +15,7 @@ import java.io.IOException;
public class InventoryUtil { public class InventoryUtil {
public static String InventoryToString(ItemStack[] items) throws IllegalStateException { public static String InventoryToString(ItemStack[] items) {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);

View File

@@ -85,6 +85,7 @@ public class MiscUtil {
for (char c : str.toCharArray()) { for (char c : str.toCharArray()) {
if (!substanceChars.contains(String.valueOf(c))) { if (!substanceChars.contains(String.valueOf(c))) {
errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), c)); errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), c));
break;
} }
} }
@@ -108,8 +109,6 @@ public class MiscUtil {
switch (player.getRole()) { switch (player.getRole()) {
case LEADER: case LEADER:
admins.add(player);
break;
case COLEADER: case COLEADER:
admins.add(player); admins.add(player);
break; break;

View File

@@ -20,8 +20,6 @@ public class RelationUtil {
} }
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 (that instanceof Faction) {
if (me instanceof FPlayer && myFaction == thatFaction) { if (me instanceof FPlayer && myFaction == thatFaction) {
ret = TL.GENERIC_YOURFACTION.toString(); ret = TL.GENERIC_YOURFACTION.toString();

View File

@@ -187,7 +187,6 @@ public abstract class SpiralTask implements Runnable {
// for successful completion // for successful completion
public void finish() { public void finish() {
// FactionsPlugin.getInstance().log("SpiralTask successfully completed!");
this.stop(); this.stop();
} }

View File

@@ -15,8 +15,6 @@ public class UtilFly {
*/ */
@Deprecated @Deprecated
public static void run() { public static void run() {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight"))
return;
Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> {
for (FPlayer fp : FPlayers.getInstance().getOnlinePlayers()) { for (FPlayer fp : FPlayers.getInstance().getOnlinePlayers()) {
@@ -28,8 +26,6 @@ public class UtilFly {
@Deprecated @Deprecated
public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) { public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight"))
return;
fp.getPlayer().setAllowFlight(fly); fp.getPlayer().setAllowFlight(fly);
fp.getPlayer().setFlying(fly); fp.getPlayer().setFlying(fly);

View File

@@ -16,8 +16,7 @@ public class VisualizeUtil {
} }
public static Set<Location> getPlayerLocations(UUID uuid) { public static Set<Location> getPlayerLocations(UUID uuid) {
Set<Location> ret = playerLocations.computeIfAbsent(uuid, k -> new HashSet<>()); return playerLocations.computeIfAbsent(uuid, k -> new HashSet<>());
return ret;
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View File

@@ -25,13 +25,6 @@ public class TimerRunnable {
} }
public TimerRunnable(UUID playerUUID, Timer timer, long duration) {
this.timer = timer;
setRemaining(duration);
FactionsPlugin plugin = FactionsPlugin.getInstance();
plugin.getTimerManager().getTimerRunnableList().add(this);
}
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return cancelled;
} }

View File

@@ -26,22 +26,20 @@ public class GraceTimer extends GlobalTimer implements Listener {
@EventHandler @EventHandler
public void onBreak(EntityExplodeEvent e) { public void onBreak(EntityExplodeEvent e) {
if(getRemaining() > 0) if (getRemaining() > 0) {
e.setCancelled(true); e.setCancelled(true);
}
} }
@EventHandler @EventHandler
public void onTNTPlace(BlockPlaceEvent event) { public void onTNTPlace(BlockPlaceEvent event) {
FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer());
if(getRemaining() > 0) { if (getRemaining() > 0 && !fp.isAdminBypassing() && event.getBlock().getType().equals(Material.TNT)) {
if (!fp.isAdminBypassing()) { event.setCancelled(true);
if (event.getBlock().getType().equals(Material.TNT)) {
event.setCancelled(true);
}
}
} }
} }
@Override @Override
public void load(Config config) { public void load(Config config) {
setPaused(config.getBoolean(this.name + ".paused")); setPaused(config.getBoolean(this.name + ".paused"));

View File

@@ -8,9 +8,7 @@ import org.bukkit.entity.Player;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Factions - Developed by Driftay. * @author DroppingAnvil
* All rights reserved 2020.
* Creation Date: 4/4/2020
*/ */
public class WaitExecutor { public class WaitExecutor {
public static ConcurrentHashMap<Player, WaitTask> taskMap = new ConcurrentHashMap<>(); public static ConcurrentHashMap<Player, WaitTask> taskMap = new ConcurrentHashMap<>();

View File

@@ -3,10 +3,7 @@ package com.massivecraft.factions.zcore;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.Board; import com.massivecraft.factions.*;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.zcore.persist.SaveTask; import com.massivecraft.factions.zcore.persist.SaveTask;
import com.massivecraft.factions.zcore.util.PermUtil; import com.massivecraft.factions.zcore.util.PermUtil;
import com.massivecraft.factions.zcore.util.Persist; import com.massivecraft.factions.zcore.util.Persist;
@@ -15,7 +12,6 @@ import com.massivecraft.factions.zcore.util.TextUtil;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.IllegalPluginAccessException;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.*; import java.io.*;
@@ -100,9 +96,7 @@ public abstract class MPlugin extends JavaPlugin {
long saveTicks = (long) (20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default long saveTicks = (long) (20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default
saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks);
} }
loadLang(); loadLang();
loadSuccessful = true; loadSuccessful = true;
return true; return true;
} }
@@ -178,20 +172,18 @@ public abstract class MPlugin extends JavaPlugin {
} }
public void onDisable() { public void onDisable() {
try { if (saveTask != null) {
if (saveTask != null) { this.getServer().getScheduler().cancelTask(saveTask);
this.getServer().getScheduler().cancelTask(saveTask); saveTask = null;
saveTask = null;
}
// only save data if plugin actually loaded successfully
if (loadSuccessful) {
Factions.getInstance().forceSave();
FPlayers.getInstance().forceSave();
Board.getInstance().forceSave();
}
log("Disabled");
} catch (IllegalPluginAccessException e) {
} }
// only save data if plugin actually loaded successfully
if (loadSuccessful) {
Factions.getInstance().forceSave();
FPlayers.getInstance().forceSave();
Board.getInstance().forceSave();
}
log("Disabled");
} }
// -------------------------------------------- // // -------------------------------------------- //

View File

@@ -19,6 +19,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
public class PermissableActionFrame { public class PermissableActionFrame {
@@ -30,9 +31,10 @@ public class PermissableActionFrame {
public PermissableActionFrame(Faction f) { public PermissableActionFrame(Faction f) {
ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action"); ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action");
assert section != null;
gui = new Gui(FactionsPlugin.getInstance(), gui = new Gui(FactionsPlugin.getInstance(),
section.getInt("rows", 3), section.getInt("rows", 4),
FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.name").replace("{faction}", f.getTag()))); FactionsPlugin.getInstance().color(Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.name")).replace("{faction}", f.getTag())));
} }
public void buildGUI(FPlayer fplayer, Permissable perm) { public void buildGUI(FPlayer fplayer, Permissable perm) {
@@ -40,8 +42,7 @@ public class PermissableActionFrame {
List<GuiItem> GUIItems = new ArrayList<>(); List<GuiItem> GUIItems = new ArrayList<>();
ItemStack dumby = buildDummyItem(); ItemStack dumby = buildDummyItem();
// Fill background of GUI with dumbyitem & replace GUI assets after // Fill background of GUI with dumbyitem & replace GUI assets after
for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true)));
GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true)));
for (PermissableAction action : PermissableAction.values()) { for (PermissableAction action : PermissableAction.values()) {
if (action.getSlot() == -1) continue; if (action.getSlot() == -1) continue;
GUIItems.set(action.getSlot(), new GuiItem(action.buildAsset(fplayer, perm), e -> { GUIItems.set(action.getSlot(), new GuiItem(action.buildAsset(fplayer, perm), e -> {
@@ -53,17 +54,12 @@ public class PermissableActionFrame {
case LEFT: case LEFT:
access = Access.ALLOW; access = Access.ALLOW;
success = fplayer.getFaction().setPermission(perm, action, access); success = fplayer.getFaction().setPermission(perm, action, access);
FactionsPlugin.instance.logFactionEvent(fplayer.getFaction(), FLogType.PERM_EDIT_DEFAULTS, fplayer.getName(), ChatColor.GREEN.toString() + ChatColor.BOLD + "ALLOWED", action.getName(), perm.name());
break; break;
case RIGHT: case RIGHT:
access = Access.DENY; access = Access.DENY;
success = fplayer.getFaction().setPermission(perm, action, access); success = fplayer.getFaction().setPermission(perm, action, access);
FactionsPlugin.instance.logFactionEvent(fplayer.getFaction(), FLogType.PERM_EDIT_DEFAULTS, fplayer.getName(), ChatColor.RED.toString() + ChatColor.BOLD + "DENIED", action.getName(), perm.name());
break; break;
case MIDDLE: case MIDDLE:
access = Access.UNDEFINED;
success = fplayer.getFaction().setPermission(perm, action, access);
break;
default: default:
return; return;
} }
@@ -93,9 +89,11 @@ public class PermissableActionFrame {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item");
ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); if (meta != null) {
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore")));
item.setItemMeta(meta); meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name")));
item.setItemMeta(meta);
}
return item; return item;
} }
@@ -103,9 +101,11 @@ public class PermissableActionFrame {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.back-item"); ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.back-item");
ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); if (meta != null) {
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore")));
item.setItemMeta(meta); meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name")));
item.setItemMeta(meta);
}
return item; return item;
} }
} }

View File

@@ -16,6 +16,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
public class PermissableRelationFrame { public class PermissableRelationFrame {
@@ -27,9 +28,10 @@ public class PermissableRelationFrame {
public PermissableRelationFrame(Faction f) { public PermissableRelationFrame(Faction f) {
ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation");
assert section != null;
gui = new Gui(FactionsPlugin.getInstance(), gui = new Gui(FactionsPlugin.getInstance(),
section.getInt("rows", 3), section.getInt("rows", 4),
FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.name").replace("{faction}", f.getTag()))); FactionsPlugin.getInstance().color(Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.name")).replace("{faction}", f.getTag())));
} }
public void buildGUI(FPlayer fplayer) { public void buildGUI(FPlayer fplayer) {
@@ -37,8 +39,7 @@ public class PermissableRelationFrame {
List<GuiItem> GUIItems = new ArrayList<>(); List<GuiItem> GUIItems = new ArrayList<>();
ItemStack dumby = buildDummyItem(); ItemStack dumby = buildDummyItem();
// Fill background of GUI with dumbyitem & replace GUI assets after // Fill background of GUI with dumbyitem & replace GUI assets after
for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true)));
GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true)));
ConfigurationSection sec = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); ConfigurationSection sec = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation");
for (String key : sec.getConfigurationSection("slots").getKeys(false)) { for (String key : sec.getConfigurationSection("slots").getKeys(false)) {
if (key == null || sec.getInt("slots." + key) < 0) continue; if (key == null || sec.getInt("slots." + key) < 0) continue;
@@ -58,8 +59,10 @@ public class PermissableRelationFrame {
private ItemStack buildAsset(String loc, String relation) { private ItemStack buildAsset(String loc, String relation) {
ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(loc)).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(loc)).get().parseItem();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.Placeholder-Item.Name").replace("{relation}", relation))); if (meta != null) {
item.setItemMeta(meta); meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.Placeholder-Item.Name").replace("{relation}", relation)));
item.setItemMeta(meta);
}
return item; return item;
} }
@@ -67,9 +70,12 @@ public class PermissableRelationFrame {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item");
ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); // So u can set it to air.
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); if (meta != null) {
item.setItemMeta(meta); meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore")));
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name")));
item.setItemMeta(meta);
}
return item; return item;
} }

View File

@@ -28,7 +28,7 @@ public class FDisbandFrame {
private Gui gui; private Gui gui;
public FDisbandFrame(Faction faction) { public FDisbandFrame(Faction faction) {
this.gui = new Gui(FactionsPlugin.getInstance(), 1, "Confirm Disband"); this.gui = new Gui(FactionsPlugin.getInstance(), 1, ChatColor.translateAlternateColorCodes('&', Objects.requireNonNull(FactionsPlugin.getInstance().getConfig().getString("f-disband-gui.title"))));
} }
public void buildGUI(FPlayer fPlayer) { public void buildGUI(FPlayer fPlayer) {

View File

@@ -25,22 +25,22 @@ public class UpgradesListener implements Listener {
@EventHandler @EventHandler
public static void onDamageReduction(EntityDamageByEntityEvent e) { public static void onDamageReduction(EntityDamageByEntityEvent e) {
if (e.isCancelled()) { if (e.isCancelled()) return;
return;
} if (!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) return;
if (!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) { if(e.getEntity() == null) return;
return;
}
FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getEntity()); FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getEntity());
FPlayer dame = FPlayers.getInstance().getByPlayer((Player) e.getDamager()); FPlayer dame = FPlayers.getInstance().getByPlayer((Player) e.getDamager());
if (fme == null || dame == null) {
return; if (fme == null || dame == null) return;
}
FLocation floc = new FLocation(fme.getPlayer().getLocation()); FLocation floc = new FLocation(fme.getPlayer().getLocation());
if(floc == null) return;
if (Board.getInstance().getFactionAt(floc) == fme.getFaction()) { if (Board.getInstance().getFactionAt(floc) == fme.getFaction()) {
if (dame.getFaction() == fme.getFaction()) { if (dame.getFaction() == fme.getFaction()) return;
return;
}
double damage = e.getDamage(); double damage = e.getDamage();
int level = fme.getFaction().getUpgrade(UpgradeType.DAMAGEDECREASE); int level = fme.getFaction().getUpgrade(UpgradeType.DAMAGEDECREASE);
double increase = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.DamageReduction.DamageReductionPercent.level-" + level); double increase = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.DamageReduction.DamageReductionPercent.level-" + level);
@@ -50,20 +50,17 @@ public class UpgradesListener implements Listener {
@EventHandler @EventHandler
public static void onDamageIncrease(EntityDamageByEntityEvent e) { public static void onDamageIncrease(EntityDamageByEntityEvent e) {
if (e == null) { if (e == null) return;
return;
} if (!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) return;
if (!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) {
return;
}
if (e.getDamager().hasMetadata("NPC") || e.getEntity().hasMetadata("NPC")) return; if (e.getDamager().hasMetadata("NPC") || e.getEntity().hasMetadata("NPC")) return;
FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getEntity()); FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getEntity());
FPlayer dame = FPlayers.getInstance().getByPlayer((Player) e.getDamager()); FPlayer dame = FPlayers.getInstance().getByPlayer((Player) e.getDamager());
if (fme == null || dame == null) { if (fme == null || dame == null) return;
return;
}
FLocation floc = new FLocation(fme.getPlayer().getLocation()); FLocation floc = new FLocation(fme.getPlayer().getLocation());
@@ -87,9 +84,8 @@ public class UpgradesListener implements Listener {
@EventHandler @EventHandler
public void onDeath(EntityDeathEvent e) { public void onDeath(EntityDeathEvent e) {
Entity killer = e.getEntity().getKiller(); Entity killer = e.getEntity().getKiller();
if (killer == null || !(killer instanceof Player)) { if (killer == null || !(killer instanceof Player)) return;
return;
}
FLocation floc = new FLocation(e.getEntity().getLocation()); FLocation floc = new FLocation(e.getEntity().getLocation());
Faction faction = Board.getInstance().getFactionAt(floc); Faction faction = Board.getInstance().getFactionAt(floc);
if (!faction.isWilderness()) { if (!faction.isWilderness()) {
@@ -112,9 +108,7 @@ public class UpgradesListener implements Listener {
Faction factionAtLoc = Board.getInstance().getFactionAt(floc); Faction factionAtLoc = Board.getInstance().getFactionAt(floc);
if (!factionAtLoc.isWilderness()) { if (!factionAtLoc.isWilderness()) {
int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER); int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER);
if (level == 0) { if (level == 0) return;
return;
}
this.lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.Spawners.Spawner-Boost.level-" + level)); this.lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.Spawners.Spawner-Boost.level-" + level));
} }
} }
@@ -131,13 +125,10 @@ public class UpgradesListener implements Listener {
if (!factionAtLoc.isWilderness()) { if (!factionAtLoc.isWilderness()) {
int level = factionAtLoc.getUpgrade(UpgradeType.CROP); int level = factionAtLoc.getUpgrade(UpgradeType.CROP);
int chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-" + level); int chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-" + level);
if (level == 0 || chance == 0) { if (level == 0 || chance == 0) return;
return;
}
int randomNum = ThreadLocalRandom.current().nextInt(1, 101); int randomNum = ThreadLocalRandom.current().nextInt(1, 101);
if (randomNum <= chance) { if (randomNum <= chance) this.growCrop(e);
this.growCrop(e);
}
} }
} }
@@ -173,21 +164,16 @@ public class UpgradesListener implements Listener {
if (!factionAtLoc.isWilderness()) { if (!factionAtLoc.isWilderness()) {
int level = factionAtLoc.getUpgrade(UpgradeType.REDSTONE); int level = factionAtLoc.getUpgrade(UpgradeType.REDSTONE);
if (level != 0) { if (level != 0) {
if (level == 1) { if (level == 1) FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost");
FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost"); if (unbreakable.contains(block)) e.setCancelled(true);
}
if (unbreakable.contains(block)) {
e.setCancelled(true);
}
} }
} }
} }
@EventHandler @EventHandler
public void onArmorDamage(PlayerItemDamageEvent e) { public void onArmorDamage(PlayerItemDamageEvent e) {
if (FPlayers.getInstance().getByPlayer(e.getPlayer()) == null) { if (FPlayers.getInstance().getByPlayer(e.getPlayer()) == null) return;
return;
}
if (e.getItem().getType().toString().contains("LEGGINGS") || e.getItem().getType().toString().contains("CHESTPLATE") || e.getItem().getType().toString().contains("HELMET") || e.getItem().getType().toString().contains("BOOTS")) { if (e.getItem().getType().toString().contains("LEGGINGS") || e.getItem().getType().toString().contains("CHESTPLATE") || e.getItem().getType().toString().contains("HELMET") || e.getItem().getType().toString().contains("BOOTS")) {
int lvl = FPlayers.getInstance().getByPlayer(e.getPlayer()).getFaction().getUpgrade(UpgradeType.REINFORCEDARMOR); int lvl = FPlayers.getInstance().getByPlayer(e.getPlayer()).getFaction().getUpgrade(UpgradeType.REINFORCEDARMOR);
double drop = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.Armor.Armor-HP-Drop.level-" + lvl); double drop = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.Armor.Armor-HP-Drop.level-" + lvl);

View File

@@ -40,7 +40,8 @@ public class FactionWarpsFrame {
int count = 0; int count = 0;
for (int x = 0; x <= gui.getRows() * 9 - 1; ++x) for (int x = 0; x <= gui.getRows() * 9 - 1; ++x)
GUIItems.add(new GuiItem(buildDummyItem(), e -> e.setCancelled(true))); GUIItems.add(new GuiItem(buildDummyItem(), e -> e.setCancelled(true)));
slots.forEach(slot -> GUIItems.set(slot, new GuiItem(XMaterial.AIR.parseItem()))); //We comment this out for now so it does not interfere with item placement when no warps are set
//slots.forEach(slot -> GUIItems.set(slot, new GuiItem(XMaterial.AIR.parseItem())));
for (final Map.Entry<String, LazyLocation> warp : fplayer.getFaction().getWarps().entrySet()) { for (final Map.Entry<String, LazyLocation> warp : fplayer.getFaction().getWarps().entrySet()) {
if (slots.size() < fplayer.getFaction().getWarps().entrySet().size()) { if (slots.size() < fplayer.getFaction().getWarps().entrySet().size()) {
slots.add(slots.get(slots.size() - 1) + 1); slots.add(slots.get(slots.size() - 1) + 1);

View File

@@ -663,25 +663,34 @@ public abstract class MemoryFPlayer implements FPlayer {
public void updatePower() { public void updatePower() {
if (this.isOffline()) { if (this.isOffline()) {
losePowerFromBeingOffline(); losePowerFromBeingOffline();
if (!Conf.powerRegenOffline) return; if (!Conf.powerRegenOffline) {
return;
}
} else if (hasFaction() && getFaction().isPowerFrozen()) { } else if (hasFaction() && getFaction().isPowerFrozen()) {
return; // Don't let power regen if faction power is frozen. return; // Don't let power regen if faction power is frozen.
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
this.millisPassed = now - this.lastPowerUpdateTime; long millisPassed = now - this.lastPowerUpdateTime;
this.lastPowerUpdateTime = now; this.lastPowerUpdateTime = now;
Player thisPlayer = this.getPlayer(); Player thisPlayer = this.getPlayer();
if (thisPlayer != null && thisPlayer.isDead()) if (thisPlayer != null && thisPlayer.isDead()) {
return; // don't let dead players regain power until they respawn return; // don't let dead players regain power until they respawn
PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this); }
Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent));
if (!powerRegenEvent.isCancelled()) double delta = millisPassed * Conf.powerPerMinute / 60000; // millisPerMinute : 60 * 1000
if (!powerRegenEvent.usingCustomPower()) if (Bukkit.getPluginManager().getPlugin("FactionsPlugin") != null) {
this.alterPower(millisPassed * Conf.powerPerMinute / 60000); // millisPerMinute : 60 * 1000 Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> {
else this.alterPower(+powerRegenEvent.getCustomPower()); PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this, delta);
Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent);
if (!powerRegenEvent.isCancelled()) {
this.alterPower(powerRegenEvent.getDelta());
}
});
} else {
this.alterPower(delta);
}
} }
public void losePowerFromBeingOffline() { public void losePowerFromBeingOffline() {
@@ -728,12 +737,13 @@ public abstract class MemoryFPlayer implements FPlayer {
public void sendFactionHereMessage(Faction from) { public void sendFactionHereMessage(Faction from) {
Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt());
boolean showChat = true;
if(Conf.worldsNoClaiming.contains(getLastStoodAt().getWorldName())) return;
if (showInfoBoard(toShow)) { if (showInfoBoard(toShow)) {
FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow));
showChat = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.also-send-chat", true);
} }
if (showChat) if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.also-send-chat", true))
this.sendMessage(FactionsPlugin.getInstance().txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); this.sendMessage(FactionsPlugin.getInstance().txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this))));
} }
@@ -842,71 +852,72 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) { public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) {
FactionsPlugin plugin = FactionsPlugin.getInstance();
String error = null; String error = null;
Faction myFaction = getFaction(); Faction myFaction = getFaction();
Faction currentFaction = Board.getInstance().getFactionAt(flocation); Faction currentFaction = Board.getInstance().getFactionAt(flocation);
int ownedLand = forFaction.getLandRounded(); int ownedLand = forFaction.getLandRounded();
int factionBuffer = FactionsPlugin.getInstance().getConfig().getInt("hcf.buffer-zone", 0); int factionBuffer = plugin.getConfig().getInt("hcf.buffer-zone", 0);
int worldBuffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0) - 1; int worldBuffer = plugin.getConfig().getInt("world-border.buffer", 0) - 1;
if (Conf.worldGuardChecking && Worldguard.getInstance().checkForRegionsInChunk(flocation) && !this.isAdminBypassing()) { if (Conf.worldGuardChecking && Worldguard.getInstance().checkForRegionsInChunk(flocation)) {
// Checks for WorldGuard regions in the chunk attempting to be claimed // Checks for WorldGuard regions in the chunk attempting to be claimed
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PROTECTED.toString()); error = plugin.txt.parse(TL.CLAIM_PROTECTED.toString());
} else if (flocation.isOutsideWorldBorder(FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0) - 1)) { } else if (flocation.isOutsideWorldBorder(plugin.getConfig().getInt("world-border.buffer", 0) - 1)) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); error = plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString());
} else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_DISABLED.toString()); error = plugin.txt.parse(TL.CLAIM_DISABLED.toString());
} else if (this.isAdminBypassing()) { } else if (this.isAdminBypassing()) {
return true; return true;
} else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) {
return true; return true;
} else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) {
return true; return true;
} else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW) { } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW && forFaction != currentFaction ) {
return true; return true;
} else if (myFaction != forFaction) { } else if (myFaction != forFaction) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); error = plugin.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this));
} else if (forFaction == currentFaction) { } else if (forFaction == currentFaction) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); error = plugin.txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true));
} else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); error = plugin.txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers);
} else if (currentFaction.isSafeZone()) { } else if (currentFaction.isSafeZone()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_SAFEZONE.toString()); error = plugin.txt.parse(TL.CLAIM_SAFEZONE.toString());
} else if (currentFaction.isWarZone()) { } else if (currentFaction.isWarZone()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_WARZONE.toString()); error = plugin.txt.parse(TL.CLAIM_WARZONE.toString());
} else if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { } else if (plugin.getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_POWER.toString()); error = plugin.txt.parse(TL.CLAIM_POWER.toString());
} else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_LIMIT.toString()); error = plugin.txt.parse(TL.CLAIM_LIMIT.toString());
} else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_ALLY.toString()); error = plugin.txt.parse(TL.CLAIM_ALLY.toString());
} else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) {
if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CONTIGIOUS.toString()); error = plugin.txt.parse(TL.CLAIM_CONTIGIOUS.toString());
} else { } else {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); error = plugin.txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString());
} }
} else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); error = plugin.txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer));
} else if (flocation.isOutsideWorldBorder(worldBuffer)) { } else if (flocation.isOutsideWorldBorder(worldBuffer)) {
if (worldBuffer > 0) { if (worldBuffer > 0) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); error = plugin.txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer));
} else { } else {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); error = plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString());
} }
} else if (currentFaction.isNormal()) { } else if (currentFaction.isNormal()) {
if (myFaction.isPeaceful()) { if (myFaction.isPeaceful()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); error = plugin.txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this));
} else if (currentFaction.isPeaceful()) { } else if (currentFaction.isPeaceful()) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); error = plugin.txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this));
} else if (!currentFaction.hasLandInflation()) { } else if (!currentFaction.hasLandInflation()) {
// TODO more messages WARN current faction most importantly // TODO more messages WARN current faction most importantly
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); error = plugin.txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this));
} else if (currentFaction.hasLandInflation() && !FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true)) { } else if (currentFaction.hasLandInflation() && !plugin.getConfig().getBoolean("hcf.allow-overclaim", true)) {
// deny over claim when it normally would be allowed. // deny over claim when it normally would be allowed.
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); error = plugin.txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString());
} else if (!Board.getInstance().isBorderLocation(flocation)) { } else if (!Board.getInstance().isBorderLocation(flocation)) {
error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_BORDER.toString()); error = plugin.txt.parse(TL.CLAIM_BORDER.toString());
} }
} }
// TODO: Add more else if statements. // TODO: Add more else if statements.
@@ -961,9 +972,6 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
public void setFFlying(boolean fly, boolean damage) { public void setFFlying(boolean fly, boolean damage) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight"))
return;
Player player = getPlayer(); Player player = getPlayer();
if (player == null) return; if (player == null) return;
@@ -972,8 +980,9 @@ public abstract class MemoryFPlayer implements FPlayer {
if (!damage) { if (!damage) {
msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled");
if (!fly) if (!fly) {
sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + "")); sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + ""));
}
} else { } else {
msg(TL.COMMAND_FLY_DAMAGE); msg(TL.COMMAND_FLY_DAMAGE);
} }
@@ -991,6 +1000,7 @@ public abstract class MemoryFPlayer implements FPlayer {
Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> setTakeFallDamage(true), 20L * cooldown); Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> setTakeFallDamage(true), 20L * cooldown);
} }
} }
isFlying = fly; isFlying = fly;
} }
@@ -1016,8 +1026,14 @@ public abstract class MemoryFPlayer implements FPlayer {
public boolean canFlyAtLocation(FLocation location) { public boolean canFlyAtLocation(FLocation location) {
Faction faction = Board.getInstance().getFactionAt(location); Faction faction = Board.getInstance().getFactionAt(location);
if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) return true; if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) {
if (faction.isSystemFaction()) return CmdFly.checkFly(this, getPlayer(), faction); return true;
}
if (faction.isSystemFaction()) {
return CmdFly.checkBypassPerms(this, getPlayer(), faction, false);
}
Access access = faction.getAccess(this, PermissableAction.FLY); Access access = faction.getAccess(this, PermissableAction.FLY);
return access == null || access == Access.UNDEFINED || access == Access.ALLOW; return access == null || access == Access.UNDEFINED || access == Access.ALLOW;
} }
@@ -1286,11 +1302,13 @@ public abstract class MemoryFPlayer implements FPlayer {
// announce success // announce success
Set<FPlayer> informTheseFPlayers = new HashSet<>(); if(!FactionsPlugin.cachedRadiusClaim) {
informTheseFPlayers.add(this); Set<FPlayer> informTheseFPlayers = new HashSet<>();
informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); informTheseFPlayers.add(this);
for (FPlayer fp : informTheseFPlayers) { informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true));
fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); for (FPlayer fp : informTheseFPlayers) {
fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp));
}
} }
Board.getInstance().setFactionAt(forFaction, flocation); Board.getInstance().setFactionAt(forFaction, flocation);

View File

@@ -1277,9 +1277,10 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
if (Conf.logFactionDisband) if (Conf.logFactionDisband)
FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + "."); FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + ".");
if(FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast")) {
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers())
fplayer.msg(TL.COMMAND_DISBAND_BROADCAST_GENERIC, this.getTag(fplayer)); fplayer.msg(TL.COMMAND_DISBAND_BROADCAST_GENERIC, this.getTag(fplayer));
}
FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), autoLeave ? PlayerDisbandReason.INACTIVITY : PlayerDisbandReason.LEAVE); FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), autoLeave ? PlayerDisbandReason.INACTIVITY : PlayerDisbandReason.LEAVE);

Some files were not shown because too many files have changed in this diff Show More