Compare commits

..

123 Commits

Author SHA1 Message Date
Driftay
b7d991c0dd unclaim fly fix 2020-06-08 07:06:16 -04:00
Driftay
6372245fcd Version Change 2020-06-08 06:42:51 -04:00
Driftay
f2c0f725b7 Carib unregistered the command 2020-06-08 05:46:25 -04:00
Driftay
0b677cb4de Merge pull request #134 from ImCarib/1.6.x
shields added
2020-06-08 05:39:38 -04:00
ImCarib
e8642a3108 shields added 2020-06-08 05:22:50 -04:00
DroppingAnvil
a355b1d0c8 Fix certain GUIs not loading 2020-06-07 20:34:42 -04:00
Driftay
929c34d850 Final Touches on PermissableAction Rollback 2020-06-01 22:52:03 -04:00
Driftay
903129e462 Reverted Back To Old FactionsBlockListener to Reference Other Plugins Hook Systems 2020-06-01 22:41:14 -04:00
Driftay
e84c69f2b0 Code Cleanup & Fix With Fly Unclaiming 2020-05-27 23:40:46 -04:00
Driftay
3e530487d7 Merge pull request #131 from SaberLLC/beta
Beta
2020-05-25 20:40:22 -04:00
Driftay
14776b8877 Merge pull request #127 from Juniormunk/1.6.x
Fix Bugs
2020-05-25 20:38:35 -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
droppinganvil
24aaa0ed6f Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-05-23 13:36:04 -05:00
DroppingAnvil
2a01682fbe Fix issue not allowing use of multiworld wild 2020-05-23 13:35:51 -05:00
Juniormunk
ba59310548 Fix occasional dynmap bug 2020-05-22 17:11:53 -04:00
Juniormunk
bec09168b6 Remove debugging prints 2020-05-22 02:33:31 -04:00
Juniormunk
4fe6484db9 Fix bug #129 2020-05-22 02:24:57 -04:00
Juniormunk
71a099beeb Fix bugs #123, #128 2020-05-21 19:29:51 -04:00
Juniormunk
ddd3150732 Fix bugs #118 , #122 2020-05-21 04:22:53 -04:00
Juniormunk
ec1501bf4f Fix Bug #125 2020-05-21 02:51:41 -04:00
Juniormunk
8ad2fdf848 Fix Bug #126 2020-05-21 01:58:05 -04:00
Driftay
1ee62c2267 Merge pull request #121 from SaberLLC/beta
Beta
2020-05-19 13:48:00 -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
Driftay
4496d4251b Finished Grace Timer :) 2020-04-07 23:22:53 -04:00
Driftay
d86d8fc73a Merge remote-tracking branch 'origin/1.6.x' into 1.6.x 2020-04-07 22:24:55 -04:00
Driftay
380caf1ca3 More things to GraceTimer 2020-04-07 22:24:07 -04:00
DroppingAnvil
103c69fecf Changed every fly check to the same one instead of having multiple, FactionsPlayerListener.checkCanFly will be removed soon. 2020-04-07 16:02:18 -05:00
Driftay
d4ac0ab310 Completely Reformatted GracePeriod with a timer now 2020-04-07 07:59:18 -04:00
Driftay
8fb697888f Added Neutral List PlaceHolder 2020-04-06 16:55:22 -04:00
Driftay
b15ff69682 Finalized F Cooldowns 2020-04-06 16:50:12 -04:00
Driftay
919a3ada25 Revert cooldown is player is bypassing 2020-04-06 16:21:22 -04:00
Driftay
62e4114466 Cooldowns initiated & Disable Open Broadcasts 2020-04-06 16:19:41 -04:00
Driftay
cb2afb5a4f Anotha one 2020-04-06 15:34:26 -04:00
Driftay
8efe68111b Class Cast Exception Fixed 2020-04-06 15:28:49 -04:00
Driftay
388f83694d Per Player Friend Fire Added (Command Usage: /f friendlyfire) 2020-04-06 15:10:37 -04:00
Driftay
23320db201 Create As Many Levels to Upgrades As You Would Like Now, Properly Relocating InventoryFramework 2020-04-06 11:26:48 -04:00
Driftay
0c5cc3a978 ItemFrame Fix, Claiming with No Power Double Check, Scoreboard Duplicate Double Check modified BlockListener 2020-04-06 10:32:16 -04:00
Driftay
8d1b26e561 Small Fix in Conf 2020-04-05 16:13:02 -04:00
Driftay
ef90cd5be8 Metrics & bStats 2020-04-05 12:57:28 -04:00
DroppingAnvil
5809387df2 Small change to fly 2020-04-04 18:42:38 -05:00
DroppingAnvil
5cf21d479e Fly improved 2020-04-04 18:41:13 -05:00
Driftay
44cac68a15 Alt Fix Join Limit 2020-04-04 09:31:45 -04:00
124 changed files with 3072 additions and 3921 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

37
pom.xml
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.2-RC</version> <version>1.6.9.5-2.3.8-RC</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>SaberFactions</name> <name>SaberFactions</name>
@@ -41,6 +41,18 @@
<configuration> <configuration>
<createDependencyReducedPom>false</createDependencyReducedPom> <createDependencyReducedPom>false</createDependencyReducedPom>
<relocations> <relocations>
<relocation>
<pattern>com.github.cryptomorin</pattern>
<shadedPattern>com.massivecraft.factions.shade.github.cryptomorin</shadedPattern>
</relocation>
<relocation>
<pattern>com.github.stefvanschie.inventoryframework</pattern>
<shadedPattern>com.massivecraft.factions.shade.stefvanschie.inventoryframework</shadedPattern>
</relocation>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.massivecraft.factions.shade.org.bstats</shadedPattern>
</relocation>
<relocation> <relocation>
<pattern>net.dv8tion</pattern> <pattern>net.dv8tion</pattern>
<shadedPattern>com.massivecraft.factions.shade.net.dv8tion</shadedPattern> <shadedPattern>com.massivecraft.factions.shade.net.dv8tion</shadedPattern>
@@ -101,6 +113,7 @@
<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.8</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
@@ -130,6 +143,18 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>XSeries</artifactId>
<version>5.3.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.6</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.ocpsoft.prettytime</groupId> <groupId>org.ocpsoft.prettytime</groupId>
<artifactId>prettytime</artifactId> <artifactId>prettytime</artifactId>
@@ -403,9 +428,19 @@
<version>2.1</version> <version>2.1</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.7</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
<repository> <repository>
<id>central</id> <id>central</id>
<name>bintray</name> <name>bintray</name>

View File

@@ -1,8 +1,8 @@
package com.massivecraft.factions; package com.massivecraft.factions;
import com.cryptomorin.xseries.XMaterial;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.massivecraft.factions.integration.dynmap.DynmapStyle; import com.massivecraft.factions.integration.dynmap.DynmapStyle;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.fperms.DefaultPermissions; import com.massivecraft.factions.zcore.fperms.DefaultPermissions;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -22,6 +22,7 @@ public class Conf {
public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag"; public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag";
public static final transient boolean DYNMAP_STYLE_BOOST = false; public static final transient boolean DYNMAP_STYLE_BOOST = false;
public static List<String> baseCommandAliases = new ArrayList<>(); public static List<String> baseCommandAliases = new ArrayList<>();
public static String serverTimeZone = "EST";
public static boolean allowNoSlashCommand = true; public static boolean allowNoSlashCommand = true;
// Colors // Colors
@@ -54,8 +55,8 @@ public class Conf {
public static boolean factionTagForceUpperCase = false; public static boolean factionTagForceUpperCase = false;
public static boolean newFactionsDefaultOpen = false; public static boolean newFactionsDefaultOpen = false;
// when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit
public static int factionMemberLimit = 0; public static int factionMemberLimit = 30;
public static int factionAltMemberLimit = 0; public static int factionAltMemberLimit = 10;
// what faction ID to start new players in when they first join the server; default is 0, "no faction" // what faction ID to start new players in when they first join the server; default is 0, "no faction"
public static String newPlayerStartingFactionID = "0"; public static String newPlayerStartingFactionID = "0";
public static boolean showMapFactionKey = true; public static boolean showMapFactionKey = true;
@@ -86,7 +87,9 @@ public class Conf {
public static int factionBufferSize = 20; public static int factionBufferSize = 20;
public static boolean useCheckSystem = true; public static boolean useCheckSystem = true;
public static boolean spawnerLock = false; public static boolean spawnerLock = false;
public static boolean gracePeriod = false; public static boolean useGraceSystem = true;
public static boolean broadcastGraceToggles = true;
public static int gracePeriodTimeDays = 7;
public static boolean noEnderpearlsInFly = false; public static boolean noEnderpearlsInFly = false;
public static boolean broadcastDescriptionChanges = false; public static boolean broadcastDescriptionChanges = false;
public static boolean broadcastTagChanges = false; public static boolean broadcastTagChanges = false;
@@ -95,10 +98,21 @@ 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;
//SHIELDS
public static boolean useFShieldSystem = true;
public static int shieldTimeHours = 12;
public static int shieldFrameChangeCooldownHours = 24;
//RADIUS CLAIMING
public static boolean useRadiusClaimSystem = true;
//FRIENDLY FIRE
public static boolean friendlyFireFPlayersCommand = false;
//Claim Fill //Claim Fill
public static int maxFillClaimCount = 25; public static int maxFillClaimCount = 25;
@@ -117,7 +131,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;
@@ -270,8 +284,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<>();
@@ -282,7 +295,7 @@ public class Conf {
public static boolean econEnabled = false; public static boolean econEnabled = false;
public static String econUniverseAccount = ""; public static String econUniverseAccount = "";
public static double econCostClaimWilderness = 30.0; public static double econCostClaimWilderness = 30.0;
public static double econCostClaimFromFactionBonus = 30.0; public static double econCostClaimFromFactionBonus = 0.0;
public static double econOverclaimRewardMultiplier = 0.0; public static double econOverclaimRewardMultiplier = 0.0;
public static double econClaimAdditionalMultiplier = 0.5; public static double econClaimAdditionalMultiplier = 0.5;
public static double econClaimRefundMultiplier = 0.7; public static double econClaimRefundMultiplier = 0.7;
@@ -418,6 +431,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 {
@@ -548,7 +565,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

@@ -288,6 +288,11 @@ public interface FPlayer extends EconomyParticipator {
boolean hasMoney(int amt); boolean hasMoney(int amt);
//Fplayer specific friendly fire.
boolean hasFriendlyFire();
void setFriendlyFire(boolean status);
//inspect Stuff //inspect Stuff
boolean isInspectMode(); boolean isInspectMode();
@@ -387,6 +392,7 @@ public interface FPlayer extends EconomyParticipator {
// Actions // Actions
// ------------------------------- // -------------------------------
void leave(boolean makePay); void leave(boolean makePay);
boolean canClaimForFaction(Faction forFaction); boolean canClaimForFaction(Faction forFaction);

View File

@@ -1,5 +1,6 @@
package com.massivecraft.factions; package com.massivecraft.factions;
import com.massivecraft.factions.cmd.shields.struct.frame.ShieldFramePersistence;
import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason; import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason;
import com.massivecraft.factions.iface.EconomyParticipator; import com.massivecraft.factions.iface.EconomyParticipator;
import com.massivecraft.factions.iface.RelationParticipator; import com.massivecraft.factions.iface.RelationParticipator;
@@ -59,6 +60,24 @@ public interface Faction extends EconomyParticipator {
void setDiscord(String link); void setDiscord(String link);
boolean isProtected();
void setProtected();
void setUnprotected();
ShieldFramePersistence getShieldFrame();
void setupShieldChange(ShieldFramePersistence frame);
boolean pendingShieldChange();
long getShieldChangeTime();
ShieldFramePersistence getNewFrame();
void applyShield();
void checkPerms(); void checkPerms();
double getReinforcedArmor(); double getReinforcedArmor();

View File

@@ -14,6 +14,9 @@ import com.massivecraft.factions.cmd.chest.AntiChestListener;
import com.massivecraft.factions.cmd.reserve.ListParameterizedType; import com.massivecraft.factions.cmd.reserve.ListParameterizedType;
import com.massivecraft.factions.cmd.reserve.ReserveAdapter; import com.massivecraft.factions.cmd.reserve.ReserveAdapter;
import com.massivecraft.factions.cmd.reserve.ReserveObject; import com.massivecraft.factions.cmd.reserve.ReserveObject;
import com.massivecraft.factions.cmd.shields.struct.ShieldTCMP;
import com.massivecraft.factions.cmd.shields.struct.frame.ShieldFrame;
import com.massivecraft.factions.cmd.shields.struct.tasks.ShieldManagement;
import com.massivecraft.factions.discord.Discord; import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.discord.DiscordListener; import com.massivecraft.factions.discord.DiscordListener;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
@@ -21,11 +24,11 @@ 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.*;
import com.massivecraft.factions.util.adapters.*; import com.massivecraft.factions.util.adapters.*;
import com.massivecraft.factions.util.timer.TimerManager;
import com.massivecraft.factions.util.wait.WaitExecutor; import com.massivecraft.factions.util.wait.WaitExecutor;
import com.massivecraft.factions.zcore.CommandVisibility; import com.massivecraft.factions.zcore.CommandVisibility;
import com.massivecraft.factions.zcore.MPlugin; import com.massivecraft.factions.zcore.MPlugin;
@@ -34,19 +37,19 @@ import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.Permissable; import com.massivecraft.factions.zcore.fperms.Permissable;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.frame.fupgrades.UpgradesListener; import com.massivecraft.factions.zcore.frame.fupgrades.UpgradesListener;
import com.massivecraft.factions.zcore.util.TextUtil;
import me.lucko.commodore.CommodoreProvider; 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.bukkit.*; import org.bstats.bukkit.Metrics;
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;
@@ -65,6 +68,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
@@ -81,7 +85,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;
@@ -96,10 +99,7 @@ public class FactionsPlugin extends MPlugin {
private FLogManager fLogManager; private FLogManager fLogManager;
private List<ReserveObject> reserveObjects; private List<ReserveObject> reserveObjects;
private FileManager fileManager; private FileManager fileManager;
private TimerManager timerManager;
public FileManager getFileManager() {
return fileManager;
}
public FactionsPlugin() { public FactionsPlugin() {
instance = this; instance = this;
@@ -109,6 +109,10 @@ public class FactionsPlugin extends MPlugin {
return instance; return instance;
} }
public FileManager getFileManager() {
return fileManager;
}
public boolean getLocked() { public boolean getLocked() {
return this.locked; return this.locked;
} }
@@ -127,28 +131,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:
@@ -178,36 +174,29 @@ public class FactionsPlugin extends MPlugin {
migrateFPlayerLeaders(); migrateFPlayerLeaders();
log("==== End Setup ===="); log("==== End Setup ====");
if (!preEnable()) return; int pluginId = 7013;
this.loadSuccessful = false; Metrics metrics = new Metrics(this, pluginId);
if (!new File(this.getDataFolder() + "/config.yml").exists()) { if (!preEnable()) {
this.saveResource("config.yml", false); this.loadSuccessful = false;
this.reloadConfig(); return;
} }
saveDefaultConfig();
reloadConfig();
//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();
new ShieldTCMP();
FPlayers.getInstance().load(); FPlayers.getInstance().load();
Factions.getInstance().load(); Factions.getInstance().load();
@@ -222,9 +211,16 @@ 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();
new ShieldManagement();
//Load command aliases //Load command aliases
Aliases.load(); Aliases.load();
// Add Base Commands // Add Base Commands
@@ -241,15 +237,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");
@@ -258,6 +254,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);
@@ -273,6 +270,10 @@ public class FactionsPlugin extends MPlugin {
fLogManager.loadLogs(this); fLogManager.loadLogs(this);
this.timerManager = new TimerManager(this);
this.timerManager.reloadTimerData();
System.out.println("[SABER-FACTIONS] - Loaded " + timerManager.getTimers().size() + " timers into list!");
getServer().getPluginManager().registerEvents(factionsPlayerListener = new FactionsPlayerListener(), this); getServer().getPluginManager().registerEvents(factionsPlayerListener = new FactionsPlayerListener(), this);
// Register Event Handlers // Register Event Handlers
@@ -291,9 +292,14 @@ public class FactionsPlugin extends MPlugin {
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);
@@ -313,6 +319,7 @@ public class FactionsPlugin extends MPlugin {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if (getDescription().getFullName().contains("BETA")) { if (getDescription().getFullName().contains("BETA")) {
divider(); divider();
System.out.println("You are using a BETA version of the plugin!"); System.out.println("You are using a BETA version of the plugin!");
@@ -328,10 +335,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");
@@ -427,6 +430,7 @@ public class FactionsPlugin extends MPlugin {
.registerTypeAdapter(Inventory.class, new InventoryTypeAdapter()) .registerTypeAdapter(Inventory.class, new InventoryTypeAdapter())
.registerTypeAdapter(ReserveObject.class, new ReserveAdapter()) .registerTypeAdapter(ReserveObject.class, new ReserveAdapter())
.registerTypeAdapter(Location.class, new LocationTypeAdapter()) .registerTypeAdapter(Location.class, new LocationTypeAdapter())
.registerTypeAdapter(ShieldFrame.class, new ShieldFrameAdapter())
.registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY); .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY);
} }
@@ -438,6 +442,19 @@ public class FactionsPlugin extends MPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
if (this.AutoLeaveTask != null) {
getServer().getScheduler().cancelTask(this.AutoLeaveTask);
this.AutoLeaveTask = null;
}
Conf.saveSync();
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);
@@ -450,24 +467,7 @@ public class FactionsPlugin extends MPlugin {
e.printStackTrace(); e.printStackTrace();
} }
// only save data if plugin actually completely loaded successfully
if (this.loadSuccessful) Conf.saveSync();
if (AutoLeaveTask != null) {
this.getServer().getScheduler().cancelTask(AutoLeaveTask);
AutoLeaveTask = null;
}
DiscordListener.saveGuilds();
if (Discord.jda != null) {
Discord.jda.shutdownNow();
}
super.onDisable(); super.onDisable();
try {
fLogManager.saveLogs();
} catch (Exception e) {
e.printStackTrace();
}
} }
public void startAutoLeaveTask(boolean restartIfRunning) { public void startAutoLeaveTask(boolean restartIfRunning) {
@@ -488,26 +488,8 @@ 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();
} }
@@ -522,14 +504,6 @@ public class FactionsPlugin extends MPlugin {
return sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender) || super.handleCommand(sender, commandString, testOnly); return sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender) || super.handleCommand(sender, commandString, testOnly);
} }
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
if (split.length == 0) return handleCommand(sender, "/f help", false);
// otherwise, needs to be handled; presumably another plugin directly ran the command
String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0);
return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false);
}
// This method must stay for < 1.12 versions // This method must stay for < 1.12 versions
@Override @Override
@@ -540,7 +514,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) {
@@ -588,70 +561,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;
} }
@@ -660,14 +574,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;
@@ -679,43 +585,19 @@ 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);
} }
public TimerManager getTimerManager() {
return timerManager;
}
public void debug(Level level, String s) { public void debug(Level level, String s) {
if (getConfig().getBoolean("debug", false)) getLogger().log(level, s); if (getConfig().getBoolean("debug", false)) getLogger().log(level, s);
} }
@@ -728,7 +610,4 @@ public class FactionsPlugin extends MPlugin {
debug(Level.INFO, s); debug(Level.INFO, s);
} }
public Worldguard getWg() {
return wg;
}
} }

View File

@@ -10,6 +10,8 @@ public class Aliases {
/** /**
* @author DroppingAnvil * @author DroppingAnvil
*/ */
public static ArrayList<String> friendlyFire = new ArrayList<>(Arrays.asList("friendlyfire", "ff"));
public static ArrayList<String> notifications = new ArrayList<>(Arrays.asList("notifications", "notis")); public static ArrayList<String> notifications = new ArrayList<>(Arrays.asList("notifications", "notis"));
public static ArrayList<String> alts_alts = new ArrayList<>(Arrays.asList("alts", "alt")); public static ArrayList<String> alts_alts = new ArrayList<>(Arrays.asList("alts", "alt"));
public static ArrayList<String> alts_list = new ArrayList<>(Arrays.asList("list", "l")); public static ArrayList<String> alts_list = new ArrayList<>(Arrays.asList("list", "l"));

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
if (FactionsPlugin.instance.getConfig().getBoolean("faction-leader-broadcast")) {
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) {
fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer));
context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), }
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

@@ -2,7 +2,10 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.*; import com.massivecraft.factions.*;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.WarmUpUtil; import com.massivecraft.factions.util.WarmUpUtil;
import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public class CmdCheckpoint extends FCommand { public class CmdCheckpoint extends FCommand {
@@ -17,10 +20,7 @@ public class CmdCheckpoint extends FCommand {
this.optionalArgs.put("set", ""); this.optionalArgs.put("set", "");
this.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT) this.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT).playerOnly().memberOnly().build();
.playerOnly()
.memberOnly()
.build();
} }
@Override @Override
@@ -29,7 +29,26 @@ public class CmdCheckpoint extends FCommand {
context.msg(TL.COMMAND_CHECKPOINT_DISABLED); context.msg(TL.COMMAND_CHECKPOINT_DISABLED);
return; return;
} }
if (context.args.size() == 1) { if (context.args.size() == 1 && context.args.get(0).equalsIgnoreCase("set")) {
if (context.fPlayer.getRole() == Role.LEADER) {
FLocation myLocation = new FLocation(context.player.getLocation());
Faction myLocFaction = Board.getInstance().getFactionAt(myLocation);
if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) {
context.faction.setCheckpoint(context.player.getLocation());
context.msg(TL.COMMAND_CHECKPOINT_SET);
return;
}
} else {
context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION);
return;
}
PermissableAction action = PermissableAction.SETWARP;
Access access = context.faction.getAccess(context.fPlayer, action);
if (access == Access.DENY) {
context.msg(TL.GENERIC_FPERM_NOPERMISSION, action.getName());
return;
} else {
FLocation myLocation = new FLocation(context.player.getLocation()); FLocation myLocation = new FLocation(context.player.getLocation());
Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); Faction myLocFaction = Board.getInstance().getFactionAt(myLocation);
if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) {
@@ -41,6 +60,8 @@ public class CmdCheckpoint extends FCommand {
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);
return; return;
@@ -57,8 +78,6 @@ public class CmdCheckpoint extends FCommand {
} else { } else {
context.msg(TL.COMMAND_CHECKPOINT_CLAIMED); context.msg(TL.COMMAND_CHECKPOINT_CLAIMED);
} }
} }
@Override @Override

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

@@ -8,6 +8,7 @@ import com.massivecraft.factions.event.FactionCreateEvent;
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;
import com.massivecraft.factions.util.Cooldown;
import com.massivecraft.factions.util.MiscUtil; import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
@@ -53,6 +54,11 @@ public class CmdCreate extends FCommand {
return; return;
} }
if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "createCooldown") && !context.fPlayer.isAdminBypassing()) {
context.msg(TL.COMMAND_COOLDOWN);
return;
}
ReserveObject factionReserve = FactionsPlugin.getInstance().getFactionReserves().stream().filter(factionReserve1 -> factionReserve1.getFactionName().equalsIgnoreCase(tag)).findFirst().orElse(null); ReserveObject factionReserve = FactionsPlugin.getInstance().getFactionReserves().stream().filter(factionReserve1 -> factionReserve1.getFactionName().equalsIgnoreCase(tag)).findFirst().orElse(null);
if (factionReserve != null && !factionReserve.getName().equalsIgnoreCase(context.player.getName())) { if (factionReserve != null && !factionReserve.getName().equalsIgnoreCase(context.player.getName())) {
context.msg(TL.COMMAND_CREATE_ALREADY_RESERVED); context.msg(TL.COMMAND_CREATE_ALREADY_RESERVED);
@@ -105,6 +111,7 @@ public class CmdCreate extends FCommand {
// That way we don't have to mess up deleting more stuff. // That way we don't have to mess up deleting more stuff.
// And prevent the user from being returned to NORMAL after deleting his old faction. // And prevent the user from being returned to NORMAL after deleting his old faction.
context.fPlayer.setRole(Role.LEADER); context.fPlayer.setRole(Role.LEADER);
Cooldown.setCooldown(context.fPlayer.getPlayer(), "createCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-create"));
if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-creation-broadcast", true)) { if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-creation-broadcast", true)) {
for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) {
follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.getName(), faction.getTag(follower)); follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.getName(), faction.getTag(follower));

View File

@@ -3,10 +3,7 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import mkremins.fanciful.FancyMessage; import mkremins.fanciful.FancyMessage;
@@ -25,36 +22,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,12 +43,14 @@ 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));
} }

View File

@@ -4,9 +4,10 @@ import com.massivecraft.factions.*;
import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason; import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.zcore.frame.fdisband.FDisbandFrame; import com.massivecraft.factions.util.Cooldown;
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.frame.fdisband.FDisbandFrame;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
@@ -69,6 +70,11 @@ public class CmdDisband extends FCommand {
return; return;
} }
if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "disbandCooldown") && !context.fPlayer.isAdminBypassing()) {
context.msg(TL.COMMAND_COOLDOWN);
return;
}
boolean access = false; boolean access = false;
if (context.fPlayer.getPlayer().hasMetadata("disband_confirm") && (time = context.fPlayer.getPlayer().getMetadata("disband_confirm").get(0).asLong()) != 0L && System.currentTimeMillis() - time <= TimeUnit.SECONDS.toMillis(3L)) { if (context.fPlayer.getPlayer().hasMetadata("disband_confirm") && (time = context.fPlayer.getPlayer().getMetadata("disband_confirm").get(0).asLong()) != 0L && System.currentTimeMillis() - time <= TimeUnit.SECONDS.toMillis(3L)) {
@@ -76,7 +82,7 @@ public class CmdDisband extends FCommand {
} }
if (!access) { if (!access) {
if (Conf.useDisbandGUI && !context.fPlayer.isAdminBypassing() || !context.player.isOp()) { if (Conf.useDisbandGUI && (!context.fPlayer.isAdminBypassing() || !context.player.isOp())) {
if (!disbandMap.containsKey(context.player.getUniqueId().toString())) { if (!disbandMap.containsKey(context.player.getUniqueId().toString())) {
new FDisbandFrame(context.faction).buildGUI(context.fPlayer); new FDisbandFrame(context.faction).buildGUI(context.fPlayer);
return; return;
@@ -84,7 +90,6 @@ public class CmdDisband extends FCommand {
} }
} }
// check for tnt before disbanding. // check for tnt before disbanding.
if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) { if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) {
context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + ""));
@@ -96,25 +101,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);
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);
if (!context.fPlayer.canFlyAtLocation() && FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) { Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband"));
context.fPlayer.setFFlying(false, false);
}
} }
} }

View File

@@ -19,6 +19,7 @@ import java.util.concurrent.ConcurrentHashMap;
public class CmdFly extends FCommand { public class CmdFly extends FCommand {
public static final boolean fly = FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight");
/** /**
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
@@ -26,7 +27,6 @@ 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 CmdFly() { public CmdFly() {
@@ -41,15 +41,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();
@@ -61,75 +58,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, () -> {
checkTaskState();
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);
Faction myFaction = fPlayer.getFaction();
if (!player.hasPermission("factions.fly.bypassnearbyenemycheck") && !fPlayer.isAdminBypassing()) {
if (fPlayer.hasEnemiesNearby()) disableFlightSync(fPlayer);
checkEnemiesSync(fPlayer);
continue;
}
FLocation myFloc = new FLocation(player.getLocation());
if (Board.getInstance().getFactionAt(myFloc) != myFaction) {
if (!checkFly(fPlayer, player, Board.getInstance().getFactionAt(myFloc))) {
disableFlightSync(fPlayer);
}
}
}
}
}, 20L, 20L);
}
public static boolean checkFly(FPlayer fme, Player me, Faction toFac) {
if (Conf.denyFlightIfInNoClaimingWorld && !Conf.worldsNoClaiming.isEmpty() && Conf.worldsNoClaiming.stream().anyMatch(me.getWorld().getName()::equalsIgnoreCase)) if (Conf.denyFlightIfInNoClaimingWorld && !Conf.worldsNoClaiming.isEmpty() && Conf.worldsNoClaiming.stream().anyMatch(me.getWorld().getName()::equalsIgnoreCase))
return false; return false;
if (toFac.getAccess(fme, PermissableAction.FLY) == Access.ALLOW) return true;
if (fme.getFaction().isWilderness()) return false; if (toFac != fme.getFaction()) {
if (toFac.isSystemFaction()) 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()) {
return me.hasPermission(toFac.isWilderness() ? Permission.FLY_WILDERNESS.node : toFac.isSafeZone() ? Permission.FLY_SAFEZONE.node : Permission.FLY_WARZONE.node); if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
Relation relationTo = toFac.getRelationTo(fme.getFaction()); return false;
if (!relationTo.isEnemy() && !relationTo.isMember()) }
return me.hasPermission(Permission.valueOf("FLY_" + relationTo.name()).node); 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; return false;
} }
if (!(me.hasPermission(Permission.FLY_NEUTRAL.node) || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.NEUTRAL && !toFac.isSystemFaction()) {
if (sendMessage) fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme));
return false;
}
return me.hasPermission(Permission.FLY_FLY.node) && (access != Access.DENY || toFac.isSystemFaction());
}
return true;
}
public static void checkTaskState() {
if (flyMap.isEmpty()) {
flyTask.cancel();
flyTask = null;
}
}
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());
@@ -154,7 +120,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;
} }
@@ -174,17 +140,15 @@ public class CmdFly extends FCommand {
return; return;
} }
if (fme.canFlyAtLocation()) {
context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> { context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> {
fme.setFlying(true); fme.setFlying(true);
flyMap.put(fme.getPlayer().getName(), true); flyMap.put(fme.getPlayer().getName(), true);
if (particleTask == null) { if (particleTask == null) startParticles();
startParticles();
}
if (flyTask == null) {
startFlyCheck();
}
}, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-fly", 0)); }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-fly", 0));
} else {
fme.msg(TL.COMMAND_FLY_NO_ACCESS, Board.getInstance().getFactionAt(fme.getLastStoodAt()).getTag());
}
} }
@Override @Override

View File

@@ -0,0 +1,44 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/6/2020
*/
public class CmdFriendlyFire extends FCommand {
public CmdFriendlyFire() {
super();
this.aliases.addAll(Aliases.friendlyFire);
this.requirements = new CommandRequirements.Builder(Permission.FRIENDLYFIRE)
.playerOnly()
.memberOnly()
.build();
}
@Override
public void perform(CommandContext context) {
if (!Conf.friendlyFireFPlayersCommand) {
context.msg(TL.GENERIC_DISABLED, "friendly fire");
return;
}
if (context.fPlayer.hasFriendlyFire()) {
context.fPlayer.setFriendlyFire(false);
context.msg(TL.COMMAND_FRIENDLY_FIRE_TOGGLE_OFF);
} else {
context.fPlayer.setFriendlyFire(true);
context.msg(TL.COMMAND_FRIENDLY_FIRE_TOGGLE_ON);
}
}
@Override
public TL getUsageTranslation() {
return TL.COMMAND_FRIENDLY_FIRE_DESCRIPTION;
}
}

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

@@ -9,7 +9,6 @@ import com.massivecraft.factions.util.CC;
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 mkremins.fanciful.FancyMessage; import mkremins.fanciful.FancyMessage;
import org.bukkit.ChatColor;
public class CmdInvite extends FCommand { public class CmdInvite extends FCommand {
@@ -60,14 +59,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())
.replaceAll("&", "§"))
.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

@@ -1,25 +1,14 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.massivecraft.factions.*; import com.massivecraft.factions.*;
import com.massivecraft.factions.cmd.audit.FLogType;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.FPlayerJoinEvent; import com.massivecraft.factions.event.FPlayerJoinEvent;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.util.CC;
import com.massivecraft.factions.zcore.frame.fupgrades.UpgradeType; import com.massivecraft.factions.zcore.frame.fupgrades.UpgradeType;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.exceptions.HierarchyException;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
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);
@@ -56,7 +45,7 @@ public class CmdJoin extends FCommand {
return; return;
} }
if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= getFactionMemberLimit(faction)) { if (!faction.altInvited(fplayer) && Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= getFactionMemberLimit(faction)) {
context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), getFactionMemberLimit(faction), fplayer.describeTo(context.fPlayer, false)); context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), getFactionMemberLimit(faction), fplayer.describeTo(context.fPlayer, false));
return; return;
} }
@@ -127,28 +116,13 @@ public class CmdJoin extends FCommand {
} }
faction.deinvite(fplayer); faction.deinvite(fplayer);
try {
context.fPlayer.setRole(faction.getDefaultRole()); 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

@@ -115,6 +115,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 +128,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,7 +42,6 @@ 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());
@@ -100,6 +99,7 @@ public class CmdList extends FCommand {
String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]); 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)); header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount));
lines.add(FactionsPlugin.getInstance().txt.parse(header)); lines.add(FactionsPlugin.getInstance().txt.parse(header));
@@ -111,7 +111,6 @@ public class CmdList extends FCommand {
lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2])))); lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2]))));
} }
context.sendMessage(lines); 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

@@ -6,6 +6,7 @@ import com.massivecraft.factions.FPlayers;
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.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.Cooldown;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public class CmdOpen extends FCommand { public class CmdOpen extends FCommand {
@@ -38,12 +39,19 @@ public class CmdOpen extends FCommand {
String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString();
if (Cooldown.isOnCooldown(context.fPlayer.getPlayer(), "openCooldown") && !context.fPlayer.isAdminBypassing()) {
context.msg(TL.COMMAND_COOLDOWN);
return;
}
// Inform // Inform
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) {
if (fplayer.getFactionId().equals(context.faction.getId())) { if (fplayer.getFactionId().equals(context.faction.getId())) {
fplayer.msg(TL.COMMAND_OPEN_CHANGES, context.fPlayer.getName(), open); fplayer.msg(TL.COMMAND_OPEN_CHANGES, context.fPlayer.getName(), open);
Cooldown.setCooldown(fplayer.getPlayer(), "openCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-open"));
continue; continue;
} }
if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-open-broadcast")) return;
fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.getTag(fplayer.getFaction()), open); fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.getTag(fplayer.getFaction()), open);
} }
}); });

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

@@ -24,6 +24,7 @@ public class CmdSaveAll extends FCommand {
Factions.getInstance().forceSave(false); Factions.getInstance().forceSave(false);
Board.getInstance().forceSave(false); Board.getInstance().forceSave(false);
Conf.save(); Conf.save();
FactionsPlugin.getInstance().getTimerManager().saveTimerData();
try { try {
FactionsPlugin.instance.getFlogManager().saveLogs(); FactionsPlugin.instance.getFlogManager().saveLogs();
} catch (Exception e) { } catch (Exception e) {

View File

@@ -1,12 +1,12 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
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.ParticleEffect; import com.massivecraft.factions.util.ParticleEffect;
import com.massivecraft.factions.util.VisualizeUtil; import com.massivecraft.factions.util.VisualizeUtil;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;

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,15 +76,19 @@ 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;
Faction finalFaction = faction;
instance.getServer().getScheduler().runTaskAsynchronously(instance, () -> {
for (String raw : finalShow) {
String parsed = TagUtil.parsePlain(finalFaction, context.fPlayer, raw); // use relations
if (parsed == null) { if (parsed == null) {
continue; // Due to minimal f show. continue; // Due to minimal f show.
} }
@@ -89,9 +98,9 @@ public class CmdShow extends FCommand {
} }
if (TagUtil.hasFancy(parsed)) { if (TagUtil.hasFancy(parsed)) {
List<FancyMessage> fancy = TagUtil.parseFancy(faction, context.fPlayer, parsed); List<FancyMessage> localFancy = TagUtil.parseFancy(finalFaction, context.fPlayer, parsed);
if (fancy != null) if (localFancy != null)
context.sendFancyMessage(fancy); fancy.addAll(localFancy);
continue; continue;
} }
@@ -103,9 +112,13 @@ public class CmdShow extends FCommand {
if (parsed.contains("%")) { if (parsed.contains("%")) {
parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it.
} }
context.msg(FactionsPlugin.getInstance().txt.parse(parsed)); parsed = FactionsPlugin.getInstance().txt.parse(parsed);
FancyMessage localFancy = instance.txt.parseFancy(parsed);
fancy.add(localFancy);
} }
} }
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

@@ -7,6 +7,7 @@ import com.massivecraft.factions.event.FactionRenameEvent;
import com.massivecraft.factions.scoreboards.FTeamWrapper; import com.massivecraft.factions.scoreboards.FTeamWrapper;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.Cooldown;
import com.massivecraft.factions.util.MiscUtil; import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -53,6 +54,11 @@ public class CmdTag extends FCommand {
return; return;
} }
if (Cooldown.isOnCooldown(context.player, "tagCooldown") && !context.fPlayer.isAdminBypassing()) {
context.msg(TL.COMMAND_COOLDOWN);
return;
}
// trigger the faction rename event (cancellable) // trigger the faction rename event (cancellable)
FactionRenameEvent renameEvent = new FactionRenameEvent(context.fPlayer, tag); FactionRenameEvent renameEvent = new FactionRenameEvent(context.fPlayer, tag);
Bukkit.getServer().getPluginManager().callEvent(renameEvent); Bukkit.getServer().getPluginManager().callEvent(renameEvent);
@@ -65,8 +71,10 @@ public class CmdTag extends FCommand {
return; return;
} }
String oldtag = context.faction.getTag(); String oldtag = context.faction.getTag();
context.faction.setTag(tag); context.faction.setTag(tag);
Discord.changeFactionTag(context.faction, oldtag); Discord.changeFactionTag(context.faction, oldtag);
FactionsPlugin.instance.logFactionEvent(context.faction, FLogType.FTAG_EDIT, context.fPlayer.getName(), tag); FactionsPlugin.instance.logFactionEvent(context.faction, FLogType.FTAG_EDIT, context.fPlayer.getName(), tag);
@@ -75,6 +83,7 @@ public class CmdTag extends FCommand {
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) {
if (fplayer.getFactionId().equals(context.faction.getId())) { if (fplayer.getFactionId().equals(context.faction.getId())) {
fplayer.msg(TL.COMMAND_TAG_FACTION, context.fPlayer.describeTo(context.faction, true), context.faction.getTag(context.faction)); fplayer.msg(TL.COMMAND_TAG_FACTION, context.fPlayer.describeTo(context.faction, true), context.faction.getTag(context.faction));
Cooldown.setCooldown(fplayer.getPlayer(), "tagCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-tag"));
continue; continue;
} }
// Broadcast the tag change (if applicable) // Broadcast the tag change (if applicable)

View File

@@ -48,7 +48,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

@@ -8,7 +8,6 @@ import com.massivecraft.factions.cmd.check.CmdCheck;
import com.massivecraft.factions.cmd.check.CmdWeeWoo; import com.massivecraft.factions.cmd.check.CmdWeeWoo;
import com.massivecraft.factions.cmd.chest.CmdChest; import com.massivecraft.factions.cmd.chest.CmdChest;
import com.massivecraft.factions.cmd.claim.*; import com.massivecraft.factions.cmd.claim.*;
import com.massivecraft.factions.cmd.configsf.CmdConvertConfig;
import com.massivecraft.factions.cmd.econ.CmdMoney; import com.massivecraft.factions.cmd.econ.CmdMoney;
import com.massivecraft.factions.cmd.grace.CmdGrace; import com.massivecraft.factions.cmd.grace.CmdGrace;
import com.massivecraft.factions.cmd.logout.CmdLogout; import com.massivecraft.factions.cmd.logout.CmdLogout;
@@ -20,6 +19,7 @@ import com.massivecraft.factions.cmd.relational.CmdRelationTruce;
import com.massivecraft.factions.cmd.reserve.CmdReserve; import com.massivecraft.factions.cmd.reserve.CmdReserve;
import com.massivecraft.factions.cmd.roles.CmdDemote; import com.massivecraft.factions.cmd.roles.CmdDemote;
import com.massivecraft.factions.cmd.roles.CmdPromote; import com.massivecraft.factions.cmd.roles.CmdPromote;
import com.massivecraft.factions.cmd.shields.CmdShield;
import com.massivecraft.factions.cmd.tnt.CmdTnt; import com.massivecraft.factions.cmd.tnt.CmdTnt;
import com.massivecraft.factions.cmd.tnt.CmdTntFill; import com.massivecraft.factions.cmd.tnt.CmdTntFill;
import com.massivecraft.factions.cmd.wild.CmdWild; import com.massivecraft.factions.cmd.wild.CmdWild;
@@ -27,6 +27,7 @@ import com.massivecraft.factions.discord.CmdInviteBot;
import com.massivecraft.factions.discord.CmdSetGuild; import com.massivecraft.factions.discord.CmdSetGuild;
import com.massivecraft.factions.missions.CmdMissions; import com.massivecraft.factions.missions.CmdMissions;
import com.massivecraft.factions.shop.CmdShop; import com.massivecraft.factions.shop.CmdShop;
import com.massivecraft.factions.shop.ShopGUIFrame;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import me.lucko.commodore.CommodoreProvider; import me.lucko.commodore.CommodoreProvider;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -156,7 +157,6 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
public CmdCheck cmdCheck = new CmdCheck(); public CmdCheck cmdCheck = new CmdCheck();
public CmdWeeWoo cmdWeeWoo = new CmdWeeWoo(); public CmdWeeWoo cmdWeeWoo = new CmdWeeWoo();
public CmdWild cmdWild = new CmdWild(); public CmdWild cmdWild = new CmdWild();
public CmdConvertConfig cmdConvertConfig = new CmdConvertConfig();
public CmdSpawnerLock cmdSpawnerLock = new CmdSpawnerLock(); public CmdSpawnerLock cmdSpawnerLock = new CmdSpawnerLock();
public CmdSetDiscord cmdSetDiscord = new CmdSetDiscord(); public CmdSetDiscord cmdSetDiscord = new CmdSetDiscord();
public CmdSeeDiscord cmdSeeDiscord = new CmdSeeDiscord(); public CmdSeeDiscord cmdSeeDiscord = new CmdSeeDiscord();
@@ -171,6 +171,8 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
public CmdDelHome cmdDelHome = new CmdDelHome(); public CmdDelHome cmdDelHome = new CmdDelHome();
public CmdClaimFill cmdClaimFill = new CmdClaimFill(); public CmdClaimFill cmdClaimFill = new CmdClaimFill();
public CmdNotifications cmdNotifications = new CmdNotifications(); public CmdNotifications cmdNotifications = new CmdNotifications();
public CmdFriendlyFire cmdFriendlyFire = new CmdFriendlyFire();
public CmdShield cmdShield = new CmdShield();
//Variables to know if we already setup certain sub commands //Variables to know if we already setup certain sub commands
public Boolean discordEnabled = false; public Boolean discordEnabled = false;
@@ -301,11 +303,12 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
this.addSubCommand(this.cmdCorner); this.addSubCommand(this.cmdCorner);
this.addSubCommand(this.cmdFGlobal); this.addSubCommand(this.cmdFGlobal);
this.addSubCommand(this.cmdViewChest); this.addSubCommand(this.cmdViewChest);
this.addSubCommand(this.cmdConvertConfig);
this.addSubCommand(this.cmdSpawnerLock); this.addSubCommand(this.cmdSpawnerLock);
this.addSubCommand(this.cmdDrain); this.addSubCommand(this.cmdDrain);
this.addSubCommand(this.cmdLookup); this.addSubCommand(this.cmdLookup);
this.addSubCommand(this.cmdNotifications); this.addSubCommand(this.cmdNotifications);
this.addSubCommand(this.cmdFriendlyFire);
this.addSubCommand(this.cmdShield);
addVariableCommands(); addVariableCommands();
if (CommodoreProvider.isSupported()) brigadierManager.build(); if (CommodoreProvider.isSupported()) brigadierManager.build();
} }
@@ -378,6 +381,7 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
} }
if (FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled", false) && !fShopEnabled) { if (FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled", false) && !fShopEnabled) {
this.addSubCommand(this.cmdShop); this.addSubCommand(this.cmdShop);
new ShopGUIFrame(null).checkShopConfig();
fShopEnabled = true; fShopEnabled = true;
} }
if (FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled", false) && !invSeeEnabled) { if (FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled", false) && !invSeeEnabled) {
@@ -400,7 +404,7 @@ 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;
} }

View File

@@ -1,7 +1,7 @@
package com.massivecraft.factions.cmd.audit; package com.massivecraft.factions.cmd.audit;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.XMaterial;
import org.bukkit.Material; import org.bukkit.Material;
/** /**

View File

@@ -1,11 +1,11 @@
package com.massivecraft.factions.cmd.check; package com.massivecraft.factions.cmd.check;
import com.cryptomorin.xseries.XMaterial;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.zcore.frame.FactionGUI; import com.massivecraft.factions.zcore.frame.FactionGUI;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;

View File

@@ -1,10 +1,10 @@
package com.massivecraft.factions.cmd.check; package com.massivecraft.factions.cmd.check;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.zcore.frame.FactionGUI; import com.massivecraft.factions.zcore.frame.FactionGUI;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;

View File

@@ -27,9 +27,10 @@ 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()) {
if (clicked == e.getWhoClicked().getInventory()) { if (clicked == clicker) {
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());
@@ -38,11 +39,17 @@ public class AntiChestListener implements Listener {
} }
} }
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;
@@ -62,12 +63,16 @@ 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));
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); context.fPlayer.attemptClaim(forFaction, context.fPlayer.getPlayer().getLocation(), true);
} }
}
@Override @Override
public TL getUsageTranslation() { public TL getUsageTranslation() {

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;
@@ -59,8 +56,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,24 +71,33 @@ 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();
return false; return false;
} }
return true; return true;
} }
public void finish() {
if (FactionsPlugin.cachedRadiusClaim) {
if (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;
@@ -71,6 +68,7 @@ public class CmdClaimLine extends FCommand {
} }
final Faction forFaction = context.argAsFaction(2, context.faction); final Faction forFaction = context.argAsFaction(2, context.faction);
Faction at = Board.getInstance().getFactionAt(new FLocation(context.fPlayer.getPlayer().getLocation()));
if (forFaction != context.fPlayer.getFaction()) { if (forFaction != context.fPlayer.getFaction()) {
if (!context.fPlayer.isAdminBypassing()) { if (!context.fPlayer.isAdminBypassing()) {
@@ -84,11 +82,20 @@ public class CmdClaimLine extends FCommand {
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++) {
if (FactionsPlugin.cachedRadiusClaim && context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), false)) {
claims++;
} else {
context.fPlayer.attemptClaim(forFaction, location, true); context.fPlayer.attemptClaim(forFaction, location, true);
claims++;
}
location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16); location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16);
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

@@ -63,6 +63,11 @@ public class CmdUnclaim extends FCommand {
boolean didUnClaim = unClaim(new FLocation(context.player), context); boolean didUnClaim = unClaim(new FLocation(context.player), context);
if (didUnClaim && !context.fPlayer.canFlyAtLocation()) if (didUnClaim && !context.fPlayer.canFlyAtLocation())
context.fPlayer.setFFlying(false, false); context.fPlayer.setFFlying(false, false);
for(FPlayer fPlayer : context.faction.getFPlayersWhereOnline(true)){
if(!fPlayer.canFlyAtLocation())
fPlayer.setFFlying(false, false);
}
} else { } else {
// radius claim // radius claim
if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { if (!Permission.CLAIM_RADIUS.has(context.sender, false)) {
@@ -83,10 +88,13 @@ public class CmdUnclaim extends FCommand {
this.stop(); this.stop();
return false; return false;
} }
return true; return true;
} }
}; };
boolean didUnClaim = unClaim(new FLocation(context.player), context);
if (didUnClaim && !context.fPlayer.canFlyAtLocation())
context.fPlayer.setFFlying(false, false);
} }
} }

View File

@@ -57,15 +57,9 @@ public class CmdUnclaimall extends FCommand {
} }
if (Econ.shouldBeUsed()) { if (Econ.shouldBeUsed()) {
double refund = Econ.calculateTotalLandRefund(target.getLandRounded()); double refund = Econ.calculateTotalLandRefund(target.getLandRounded());
if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) {
if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) {
return; return;
} }
} else {
if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) {
return;
}
}
} }
LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(target, context.fPlayer); LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(target, context.fPlayer);

View File

@@ -1,29 +0,0 @@
package com.massivecraft.factions.cmd.configsf;
import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements;
import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
public class CmdConvertConfig extends FCommand {
public CmdConvertConfig() {
super();
this.aliases.add("convertconfig");
this.requirements = new CommandRequirements.Builder(Permission.CONVERTCONFIG)
.playerOnly()
.build();
}
@Override
public void perform(CommandContext context) {
ConvertConfigHandler.convertconfig(context.player);
}
@Override
public TL getUsageTranslation() {
return TL.COMMAND_CONVERTCONFIG_DESCRIPTION;
}
}

View File

@@ -1,147 +0,0 @@
package com.massivecraft.factions.cmd.configsf;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
public class ConvertConfigHandler {
static File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml");
static FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile);
static File configFile = new File("plugins/Factions/config.yml");
static FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile);
static JavaPlugin plugin = JavaPlugin.getProvidingPlugin(FactionsPlugin.class);
public static void setString(String s) {
sb.set(s, sv.getString(s));
}
public static void setInt(String s) {
sb.set(s, sv.getInt(s));
}
public static void setConfigSec(String s) {
ConfigurationSection cs = sv.getConfigurationSection(s);
sb.set(s, cs);
}
public static void setBoolean(String s) {
sb.set(s, sv.getBoolean(s));
}
public static void convertconfig(Player player) {
if (new File("plugins/Factions/SavageFactions/config.yml").exists()) {
BukkitScheduler scheduler = plugin.getServer().getScheduler();
scheduler.scheduleAsyncDelayedTask(plugin, () -> {
File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml");
FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile);
File configFile = new File("plugins/Factions/config.yml");
FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile);
sb.set("ConfigConvertedFromSavageFactions", true);
sb.set("debug", sv.getBoolean("debug"));
ConfigurationSection ffe = sv.getConfigurationSection("findfactionsexploit");
sb.set("findfactionsexploit", ffe);
setString("default-relation");
ConfigurationSection pC = sv.getConfigurationSection("portals");
sb.set("portals", pC);
sb.set("maxwarps", sv.getInt("maxwarps"));
setConfigSec("warp-cost");
setBoolean("enable-faction-flight");
setBoolean("ffly.AutoEnable");
setInt("fly-falldamage-cooldown");
setBoolean("disable-pistons-in-territory");
setConfigSec("tooltips");
setConfigSec("scoreboard");
sb.set("scoreboard.also-send-chat", true);
setConfigSec("warmups");
setConfigSec("max-relations");
setInt("world-border.buffer");
setConfigSec("hcf");
sb.set("show", sv.getStringList("show"));
setBoolean("show-exempt");
sb.set("map", sv.getStringList("map"));
setConfigSec("list");
setBoolean("use-old-help");
setConfigSec("help");
setConfigSec("fperm-gui");
sb.set("fperm-gui.action.slots.check", 50);
setConfigSec("fwarp-gui");
setBoolean("faction-creation-broadcast");
setBoolean("faction-disband-broadcast");
setBoolean("See-Invisible-Faction-Members");
setConfigSec("frules");
setConfigSec("ftnt");
setBoolean("fpaypal.Enabled");
setBoolean("checkpoints.Enabled");
setConfigSec("fnear");
setConfigSec("ffocus");
setConfigSec("fvualt");
setString("fupgrades.MainMenu.Title");
setString("fupgrades.MainMenu.DummyItem.Name");
setString("fupgrades.MainMenu.DummyItem.Type");
List<String> l = sv.getStringList("fupgrades.MainMenu.DummyItem.Lore");
sb.set("fupgrades.MainMenu.DummyItem.Lore", l);
setConfigSec("fupgrades.MainMenu.Crops.Crop-Boost");
setConfigSec("fupgrades.MainMenu.Crops.Cost");
sb.set("fupgrades.MainMenu.Crops.CropItem", sv.getConfigurationSection("fupgrades.MainMenu.Crops.DisplayItem"));
setConfigSec("fupgrades.MainMenu.EXP.EXP-Boost");
setConfigSec("fupgrades.MainMenu.EXP.Cost");
sb.set("fupgrades.MainMenu.EXP.EXPItem", sv.getConfigurationSection("fupgrades.MainMenu.EXP.DisplayItem"));
setConfigSec("fupgrades.MainMenu.Power.Power-Boost");
setConfigSec("fupgrades.MainMenu.Power.Cost");
sb.set("fupgrades.MainMenu.Power.PowerItem", sv.getConfigurationSection("fupgrades.MainMenu.Power.DisplayItem"));
List<Integer> p = new ArrayList();
p.add(sv.getInt("fupgrades.MainMenu.Power.DisplayItem.Slot"));
sb.set("fupgrades.MainMenu.Power.PowerItem.slots", p);
sb.set("fupgrades.MainMenu.Power.PowerItem.Amount", 1);
sb.set("fupgrades.MainMenu.Power.PowerItem.Damage", 0);
sb.set("fupgrades.MainMenu.Power.PowerItem.Slot", null);
sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost"));
setConfigSec("fupgrades.MainMenu.Spawners.Spawner-Boost");
setConfigSec("fupgrades.MainMenu.Spawners.Cost");
sb.set("fupgrades.MainMenu.Spawners.SpawnerItem", sv.getConfigurationSection("fupgrades.MainMenu.Spawners.DisplayItem"));
setConfigSec("fupgrades.MainMenu.Chest.Chest-Size");
setConfigSec("fupgrades.MainMenu.Chest.Cost");
sb.set("fupgrades.MainMenu.Chest.ChestItem", sv.getConfigurationSection("fupgrades.MainMenu.Chest.DisplayItem"));
setConfigSec("fupgrades.MainMenu.Members.Cost");
sb.set("fupgrades.MainMenu.Members.MembersItem", sv.getConfigurationSection("fupgrades.MainMenu.Members.DisplayItem"));
sb.set("fupgrades.MainMenu.Members.MembersItem.Amount", 1);
sb.set("fupgrades.MainMenu.Members.MembersItem.Damage", 0);
if (sv.getString("fupgrades.MainMenu.Members.DisplayItem.Type").equalsIgnoreCase("PLAYER_HEAD"))
sb.set("fupgrades.MainMenu.Members.MembersItem.Type", "PAPER");
List<Integer> x = new ArrayList();
x.add(sv.getInt("fupgrades.MainMenu.Members.DisplayItem.Slot"));
sb.set("fupgrades.MainMenu.Members.MembersItem.slots", x);
sb.set("fupgrades.MainMenu.Members.MembersItem.Slot", null);
sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost"));
setConfigSec("fbanners");
setConfigSec("see-chunk");
setConfigSec("Tntfill");
try {
sb.save(configFile);
plugin.reloadConfig();
} catch (IOException e) {
player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAIL.toString());
Bukkit.getLogger().log(Level.SEVERE, Arrays.toString(e.getStackTrace()));
}
player.sendMessage(TL.COMMAND_CONVERTCONFIG_SUCCESS.toString());
}, 0L);
} else {
player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAILCONFIGMISSING.toString());
}
}
}

View File

@@ -37,7 +37,7 @@ public class CmdMoneyDeposit extends FCommand {
double amount = context.argAsDouble(0, 0d); double amount = context.argAsDouble(0, 0d);
EconomyParticipator faction = context.argAsFaction(1, context.faction); EconomyParticipator faction = context.argAsFaction(1, context.faction);
if(amount <= 0){ if (amount <= 0) {
return; return;
} }

View File

@@ -34,7 +34,7 @@ public class CmdMoneyTransferFf extends FCommand {
public void perform(CommandContext context) { public void perform(CommandContext context) {
double amount = context.argAsDouble(0, 0d); double amount = context.argAsDouble(0, 0d);
if(amount <= 0){ if (amount <= 0) {
return; return;
} }

View File

@@ -33,7 +33,7 @@ public class CmdMoneyTransferFp extends FCommand {
public void perform(CommandContext context) { public void perform(CommandContext context) {
double amount = context.argAsDouble(0, 0d); double amount = context.argAsDouble(0, 0d);
if(amount <= 0){ if (amount <= 0) {
return; return;
} }

View File

@@ -33,7 +33,7 @@ public class CmdMoneyTransferPf extends FCommand {
public void perform(CommandContext context) { public void perform(CommandContext context) {
double amount = context.argAsDouble(0, 0d); double amount = context.argAsDouble(0, 0d);
if(amount <= 0){ if (amount <= 0) {
return; return;
} }

View File

@@ -40,7 +40,7 @@ public class CmdMoneyWithdraw extends FCommand {
public void perform(CommandContext context) { public void perform(CommandContext context) {
double amount = context.argAsDouble(0, 0d); double amount = context.argAsDouble(0, 0d);
if(amount <= 0){ if (amount <= 0) {
return; return;
} }

View File

@@ -1,35 +1,73 @@
package com.massivecraft.factions.cmd.grace; package com.massivecraft.factions.cmd.grace;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
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;
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.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.util.timer.TimerManager;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import java.util.concurrent.TimeUnit;
public class CmdGrace extends FCommand { public class CmdGrace extends FCommand {
/** /**
* @author Driftay * @author Driftay
*/ */
//TODO: Make Timed Format For Grace Period
public CmdGrace() { public CmdGrace() {
super(); super();
this.aliases.addAll(Aliases.grace); this.aliases.addAll(Aliases.grace);
this.optionalArgs.put("on/off", "toggle");
this.requirements = new CommandRequirements.Builder(Permission.GRACE) this.requirements = new CommandRequirements.Builder(Permission.GRACE)
.build(); .build();
} }
@Override @Override
public void perform(CommandContext context) { public void perform(CommandContext context) {
Conf.gracePeriod = !Conf.gracePeriod; if (!Conf.useGraceSystem) {
context.msg(TL.COMMAND_GRACE_TOGGLE, Conf.gracePeriod ? FactionsPlugin.getInstance().color("&aEnabled") : FactionsPlugin.getInstance().color("&4Disabled")); context.msg(TL.GENERIC_DISABLED, "factions grace");
return;
} }
if (context.args.size() == 1) {
if (context.sender.hasPermission(String.valueOf(Permission.GRACETOGGLE))) {
if (context.argAsString(0).equalsIgnoreCase("on") || context.argAsString(0).equalsIgnoreCase("start")) {
FactionsPlugin.getInstance().getTimerManager().graceTimer.setPaused(false);
FactionsPlugin.getInstance().getTimerManager().graceTimer.setRemaining(TimeUnit.DAYS.toMillis(Conf.gracePeriodTimeDays), true);
if (Conf.broadcastGraceToggles) {
for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers())
follower.msg(TL.COMMAND_GRACE_ENABLED_FORMAT, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)));
}
return;
}
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.setPaused(false);
if (Conf.broadcastGraceToggles) {
for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers())
follower.msg(TL.COMMAND_GRACE_DISABLED_FORMAT);
}
return;
}
}
}
if (FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining() <= 0L) {
context.fPlayer.msg(TL.COMMAND_GRACE_DISABLED_NO_FORMAT.toString());
} else {
context.fPlayer.msg(TL.COMMAND_GRACE_TIME_REMAINING, String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true)));
}
}
@Override @Override
public TL getUsageTranslation() { public TL getUsageTranslation() {

View File

@@ -32,7 +32,7 @@ public class CmdPointsBalance extends FCommand {
if (context.argIsSet(0)) { if (context.argIsSet(0)) {
faction = context.argAsFaction(0); faction = context.argAsFaction(0);
} else if(context.faction.isNormal()){ } else if (context.faction.isNormal()) {
context.msg(TL.COMMAND_POINTS_SHOW_OWN, context.faction.getPoints()); context.msg(TL.COMMAND_POINTS_SHOW_OWN, context.faction.getPoints());
return; return;
} else { } else {

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);

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

@@ -0,0 +1,42 @@
package com.massivecraft.factions.cmd.shields;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements;
import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.cmd.shields.struct.frame.ShieldFrame;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class CmdShield extends FCommand {
public CmdShield() {
this.aliases.add("shield");
this.requirements = new CommandRequirements.Builder(Permission.SHIELD)
.playerOnly()
.memberOnly()
.withAction(PermissableAction.SHIELD)
.build();
}
public void perform(CommandContext context) {
if (!Conf.useFShieldSystem) {
context.msg(TL.GENERIC_DISABLED);
return;
}
(new ShieldFrame()).build(context.fPlayer);
}
public TL getUsageTranslation() {
return TL.COMMAND_SHIELD_DESCRIPTION;
}
}

View File

@@ -0,0 +1,41 @@
package com.massivecraft.factions.cmd.shields.struct;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.cmd.shields.struct.frame.ShieldFramePersistence;
import java.util.ArrayList;
import java.util.List;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class ShieldTCMP {
private static ShieldTCMP instance;
private List<ShieldFramePersistence> frames = new ArrayList<>();
public ShieldTCMP() {
instance = this;
for (int x = 0; x <= 23; x++) {
int end = (x + Conf.shieldTimeHours > 23) ? (x + Conf.shieldTimeHours - 24) : (x + Conf.shieldTimeHours);
this.frames.add(new ShieldFramePersistence(x, end));
}
}
public static ShieldTCMP getInstance() {
return instance;
}
public ShieldFramePersistence getByStart(int start) {
if (start > 23) return null;
return this.frames.get(start);
}
public List<ShieldFramePersistence> getFrames() {
return this.frames;
}
}

View File

@@ -0,0 +1,75 @@
package com.massivecraft.factions.cmd.shields.struct.frame;
import com.cryptomorin.xseries.XMaterial;
import com.github.stefvanschie.inventoryframework.Gui;
import com.github.stefvanschie.inventoryframework.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.PaginatedPane;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.shields.struct.tasks.ShieldManagement;
import com.massivecraft.factions.util.ItemBuilder;
import com.massivecraft.factions.util.Placeholder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class ShieldConfirmationFrame {
private Gui gui;
public ShieldConfirmationFrame() {
this.gui = new Gui(FactionsPlugin.getInstance(),
FactionsPlugin.getInstance().getConfig().getInt("Shields.Frame.Change.Size"),
FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("Shields.Frame.Change.Title")));
}
public void build(FPlayer fme, ShieldFramePersistence frame) {
PaginatedPane pane = new PaginatedPane(0, 0, 9, this.gui.getRows());
List<GuiItem> GUIItems = new ArrayList<>();
for (int x = 0; x <= this.gui.getRows() * 9 - 1; ) {
GUIItems.add(new GuiItem(XMaterial.AIR.parseItem(), e -> e.setCancelled(true)));
x++;
}
ItemStack[] assets = buildAssets(frame);
GUIItems.set(4, new GuiItem(assets[0], e -> e.setCancelled(true)));
GUIItems.set(11, new GuiItem(assets[1], e -> {
e.setCancelled(true);
fme.getFaction().setupShieldChange(frame);
(new ShieldFrame()).build(fme);
}));
GUIItems.set(15, new GuiItem(assets[2], e -> {
e.setCancelled(true);
(new ShieldFrame()).build(fme);
}));
pane.populateWithGuiItems(GUIItems);
this.gui.addPane(pane);
this.gui.update();
this.gui.show(fme.getPlayer());
}
private ItemStack[] buildAssets(ShieldFramePersistence frame) {
String path = "Shields.Frame.Change.Items.";
return new ItemStack[]{new ItemBuilder(
XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(path + "Info.Type")).get().parseItem())
.name(FactionsPlugin.getInstance().getConfig().getString(path + "Info.Display-Name"))
.lore(FactionsPlugin.getInstance().replacePlaceholders(FactionsPlugin.getInstance().getConfig().getStringList(path + "Info.Lore"),
new Placeholder("{start-time}", frame.getStartTime()),
new Placeholder("{end-time}", frame.getEndTime()),
new Placeholder("{current-time}", ShieldManagement.getCurrentTime()))).build(),
new ItemBuilder(
XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(path + "Accept.Type")).get().parseItem())
.name(FactionsPlugin.getInstance().getConfig().getString(path + "Accept.Display-Name"))
.lore(FactionsPlugin.getInstance().getConfig().getStringList(path + "Accept.Lore")).build(),
new ItemBuilder(XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(path + "Deny.Type")).get().parseItem())
.name(FactionsPlugin.getInstance().getConfig().getString(path + "Deny.Display-Name"))
.lore(FactionsPlugin.getInstance().getConfig().getStringList(path + "Deny.Lore")).build()};
}
}

View File

@@ -0,0 +1,171 @@
package com.massivecraft.factions.cmd.shields.struct.frame;
import com.cryptomorin.xseries.XMaterial;
import com.github.stefvanschie.inventoryframework.Gui;
import com.github.stefvanschie.inventoryframework.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.PaginatedPane;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.shields.struct.ShieldTCMP;
import com.massivecraft.factions.cmd.shields.struct.tasks.ShieldManagement;
import com.massivecraft.factions.util.ItemBuilder;
import com.massivecraft.factions.util.Placeholder;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/21/2020
*/
public class ShieldFrame {
public Gui gui;
public ShieldFrame() {
this.gui = new Gui(FactionsPlugin.getInstance(), 5, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("Shields.Frame.Main-Menu.Title")));
}
public static String formatTimeMilliseconds(long milliseconds) {
long seconds = milliseconds / 1000L;
long minutes = seconds / 60L;
seconds %= 60L;
long hours = minutes / 60L;
minutes %= 60L;
long days = hours / 24L;
hours %= 24L;
long months = days / 31L;
days %= 31L;
if (months != 0L)
return months + "M " + days + "d " + hours + "h ";
if (days != 0L)
return days + "d " + hours + "h " + minutes + "m ";
if (hours != 0L)
return hours + "h " + minutes + "m " + seconds + "s";
if (minutes != 0L)
return minutes + "m " + seconds + "s";
if (seconds != 0L)
return seconds + "s";
return "";
}
public void build(FPlayer fme) {
PaginatedPane pane = new PaginatedPane(0, 0, 9, this.gui.getRows());
List<GuiItem> GUIItems = new ArrayList<>();
for (int x = 0; x <= this.gui.getRows() * 9 - 1; x++)
GUIItems.add(new GuiItem(new ItemStack(Material.AIR), e -> e.setCancelled(true)));
for (int slot : FactionsPlugin.getInstance().getConfig().getIntegerList("Shields.Frame.Frame-Type.Barrier.Slots")) {
GUIItems.set(slot, new GuiItem(buildBarrierDummyItem(), e -> e.setCancelled(true)));
}
int x = 0;
for (ShieldFramePersistence frame : ShieldTCMP.getInstance().getFrames()) {
ItemStack item = buildShieldFrames(fme.getFaction(), frame);
if (fme.getFaction().getShieldFrame() != null &&
fme.getFaction().getShieldFrame().equals(frame)) {
GUIItems.set(x, new GuiItem(item, e -> e.setCancelled(true)));
x++;
continue;
}
if (fme.getFaction().getNewFrame() != null &&
fme.getFaction().getNewFrame().equals(frame)) {
GUIItems.set(x, new GuiItem(item, e -> e.setCancelled(true)));
x++;
continue;
}
GUIItems.set(x, new GuiItem(item, e -> {
e.setCancelled(true);
(new ShieldConfirmationFrame()).build(fme, frame);
}));
x++;
}
ItemStack[] assets = getAssets(fme.getFaction());
GUIItems.set(39, new GuiItem(assets[0], e -> e.setCancelled(true)));
GUIItems.set(41, new GuiItem(assets[1], e -> e.setCancelled(true)));
pane.populateWithGuiItems(GUIItems);
this.gui.addPane(pane);
this.gui.update();
this.gui.show(fme.getPlayer());
}
private ItemStack[] getAssets(Faction f) {
ItemStack change;
ConfigurationSection sec = FactionsPlugin.getInstance().getConfig().getConfigurationSection("Shields.Frame.Frame-Type.");
assert sec != null;
ItemStack info = (new ItemBuilder(XMaterial.matchXMaterial(sec.getString("Info-Item.Type")).get().parseItem()).name(sec.getString("Info-Item.Display-Name")).lore(sec.getStringList("Info-Item.Lore")).build());
if (f.pendingShieldChange()) {
change = (new ItemBuilder(XMaterial.matchXMaterial(sec.getString("Shield-Pending.Type")).get().parseItem()).name(sec.getString("Shield-Pending.Display-Name")).lore(FactionsPlugin.getInstance().replacePlaceholders(sec.getStringList("Shield-Pending.Lore"),
new Placeholder("{remaining-time}", timeUntilChange(f)),
new Placeholder("{new-start}", f.getNewFrame().getStartTime()),
new Placeholder("{new-end}", f.getNewFrame().getEndTime())))).build();
} else {
change = (new ItemBuilder(XMaterial.matchXMaterial(sec.getString("NoShield-Pending.Type")).get().parseItem()).name(sec.getString("NoShield-Pending.Display-Name")).lore(sec.getStringList("NoShield-Pending.Lore")).build());
}
return new ItemStack[]{info, change};
}
private String timeUntilChange(Faction f) {
long time = f.getShieldChangeTime();
time -= System.currentTimeMillis();
return formatTimeMilliseconds(time);
}
private ItemStack buildShieldFrames(Faction faction, ShieldFramePersistence frame) {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("Shields.Frame.Frame-Type");
if (faction.getShieldFrame() != null && faction.getShieldFrame().equals(frame)) {
ItemStack item = XMaterial.matchXMaterial(config.getString("Current-Frame.Type")).get().parseItem();
ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().replacePlaceholders(config.getStringList("Current-Frame.Lore"),
new Placeholder("{time-currently}", ShieldManagement.getCurrentTime()),
new Placeholder("{remaining-time}", timeUntilChange(faction)),
new Placeholder("{start-time}", frame.getStartTime()),
new Placeholder("{end-time}", frame.getEndTime()))));
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Current-Frame.Display-Name")));
item.setItemMeta(meta);
return item;
}
if (faction.getNewFrame() != null && faction.getNewFrame().equals(frame)) {
ItemStack item = XMaterial.matchXMaterial(config.getString("New-Frame.Type")).get().parseItem();
ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().replacePlaceholders(config.getStringList("New-Frame.Lore"),
new Placeholder("{time-currently}", ShieldManagement.getCurrentTime()),
new Placeholder("{remaining-time}", timeUntilChange(faction)),
new Placeholder("{start-time}", frame.getStartTime()),
new Placeholder("{end-time}", frame.getEndTime()))));
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("New-Frame.Display-Name")));
item.setItemMeta(meta);
return item;
}
ItemStack item = XMaterial.matchXMaterial(config.getString("Regular-Frame.Type")).get().parseItem();
ItemMeta meta = item.getItemMeta();
meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().replacePlaceholders(config.getStringList("Regular-Frame.Lore"),
new Placeholder("{time-currently}", ShieldManagement.getCurrentTime()),
new Placeholder("{remaining-time}", timeUntilChange(faction)),
new Placeholder("{start-time}", frame.getStartTime()),
new Placeholder("{end-time}", frame.getEndTime()))));
meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Regular-Frame.Display-Name")));
item.setItemMeta(meta);
return item;
}
private ItemStack buildBarrierDummyItem() {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("Shields.Frame.Frame-Type.Barrier.");
ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem();
ItemMeta meta = item.getItemMeta();
if (meta != null) {
List<String> lore = new ArrayList<>();
for (String s : config.getStringList("Lore")) lore.add(FactionsPlugin.getInstance().color(s));
meta.setLore(lore);
meta.setDisplayName(FactionsPlugin.getInstance().color(Objects.requireNonNull(config.getString("Name"))));
item.setItemMeta(meta);
}
return item;
}
}

View File

@@ -0,0 +1,54 @@
package com.massivecraft.factions.cmd.shields.struct.frame;
import com.massivecraft.factions.cmd.shields.struct.tasks.ShieldManagement;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class ShieldFramePersistence {
private int start;
private int end;
public ShieldFramePersistence(int start, int end) {
this.start = start;
this.end = end;
}
public int getEndParsed() {
return this.end;
}
public int getStartParsed() {
return this.start;
}
public String getStartTime() {
return toClockFormat(this.start);
}
public String getEndTime() {
return toClockFormat(this.end);
}
public boolean isHourProtected(int hour) {
if (this.end < this.start) return hour >= this.start;
return (hour >= this.start && hour < this.end);
}
public boolean isProtectedCurrent() {
return isHourProtected(ShieldManagement.getCurrentHour());
}
public String toClockFormat(int x) {
if (x == 0) return "12:00 am";
if (x == 12) return "12:00 pm";
if (x > 12) return (x - 12) + ":00 pm";
return x + ":00 am";
}
}

View File

@@ -0,0 +1,57 @@
package com.massivecraft.factions.cmd.shields.struct.tasks;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.shields.struct.ShieldTCMP;
import org.bukkit.Bukkit;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class ShieldManagement implements Runnable {
private static DateTimeZone zone = DateTimeZone.forID("Canada/Eastern");
private int lastHour;
public ShieldManagement() {
new ShieldTCMP();
this.lastHour = 25;
Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), this, 20L, 1200L);
}
public static int getCurrentHour() {
DateTime time = new DateTime(zone);
return time.getHourOfDay();
}
public static String getCurrentTime() {
DateTime time = new DateTime(zone);
int hour = time.getHourOfDay();
if (hour == 0) hour = 12;
if (hour > 12)
return (hour - 12) + ":" + ((time.getMinuteOfHour() < 10) ? ("0" + time.getMinuteOfHour()) : Integer.valueOf(time.getMinuteOfHour())) + " pm";
return hour + ":" + ((time.getMinuteOfHour() < 10) ? ("0" + time.getMinuteOfHour()) : Integer.valueOf(time.getMinuteOfHour())) + " am";
}
public void run() {
DateTime time = new DateTime(zone);
int hour = time.getHourOfDay();
if (this.lastHour == 25 || this.lastHour != hour) {
long now = System.currentTimeMillis();
Factions.getInstance().getAllFactions().forEach(faction -> {
if (faction.pendingShieldChange() && faction.getShieldChangeTime() < now) faction.applyShield();
if (faction.getShieldFrame() != null) {
if (faction.getShieldFrame().isHourProtected(hour)) faction.setProtected();
} else {
faction.setUnprotected();
}
});
}
}
}

View File

@@ -1,5 +1,6 @@
package com.massivecraft.factions.cmd.tnt; package com.massivecraft.factions.cmd.tnt;
import com.cryptomorin.xseries.XMaterial;
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;
@@ -7,7 +8,6 @@ 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.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.util.XMaterial;
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; import org.bukkit.Material;

View File

@@ -20,7 +20,6 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
public class CmdTntFill extends FCommand { public class CmdTntFill extends FCommand {

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,8 +19,12 @@ 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;
public static HashSet<Player> teleporting; public static HashSet<Player> teleporting;
@@ -44,8 +45,6 @@ public class CmdWild extends FCommand implements WaitedTask {
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 +54,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 +73,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 +91,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 +113,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

@@ -1,11 +1,11 @@
package com.massivecraft.factions.cmd.wild; package com.massivecraft.factions.cmd.wild;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.wait.WaitExecutor; import com.massivecraft.factions.util.wait.WaitExecutor;
import com.massivecraft.factions.util.wait.WaitTask; import com.massivecraft.factions.util.wait.WaitTask;
import com.massivecraft.factions.zcore.frame.FactionGUI; import com.massivecraft.factions.zcore.frame.FactionGUI;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -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

@@ -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,20 +41,15 @@ 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)
if (!Conf.econEnabled) {
FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true");
}
//FactionsPlugin.getInstance().cmdBase.cmdHelp.updateHelp(); //FactionsPlugin.getInstance().cmdBase.cmdHelp.updateHelp();
} }
@@ -68,26 +62,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,37 +90,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!;,,; // 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 +115,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 +129,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 +151,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 +160,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 +193,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 +216,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());
}
} else {
acc = Bukkit.getOfflinePlayer(ep.getAccountId());
}
String You = ep.describeTo(ep, true); String You = ep.describeTo(ep, true);
if (delta == 0) { if (delta == 0) return true;
// no money actually transferred? else if (delta > 0) {
// 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 +280,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 +293,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 +317,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 +327,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.
if (player == null) return false;
boolean vanish = false;
if (essentials != null) {
User user = essentials.getUser(player); User user = essentials.getUser(player);
return user != null && user.isVanished(); 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

@@ -8,7 +8,6 @@ import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.association.Associables; import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.protection.association.RegionAssociable; import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
@@ -22,7 +21,9 @@ import org.bukkit.plugin.Plugin;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/* /*
* WorldGuard Permission Checking. * WorldGuard Permission Checking.
@@ -34,10 +35,6 @@ import java.util.*;
public class Worldguard { public class Worldguard {
private static Worldguard instance; private static Worldguard instance;
/**
* @author FactionsUUID Team
*/
private Object worldGuard; private Object worldGuard;
private WorldGuardPlugin worldGuardPlugin; private WorldGuardPlugin worldGuardPlugin;
private Object regionContainer; private Object regionContainer;
@@ -59,7 +56,7 @@ public class Worldguard {
Plugin p = Bukkit.getPluginManager().getPlugin("WorldGuard"); Plugin p = Bukkit.getPluginManager().getPlugin("WorldGuard");
if (p == null) { if (p == null) {
FactionsPlugin.instance.log("Could not find WorldGuard! Support will not be added."); FactionsPlugin.getInstance().log("Could not find WorldGuard! Support will not be added.");
return; return;
} }
if (p instanceof WorldGuardPlugin) { if (p instanceof WorldGuardPlugin) {
@@ -69,9 +66,9 @@ public class Worldguard {
Class<?> worldGuardClass = Class.forName("com.sk89q.worldguard.WorldGuard"); Class<?> worldGuardClass = Class.forName("com.sk89q.worldguard.WorldGuard");
Method getInstanceMethod = worldGuardClass.getMethod("getInstance"); Method getInstanceMethod = worldGuardClass.getMethod("getInstance");
worldGuard = getInstanceMethod.invoke(null); worldGuard = getInstanceMethod.invoke(null);
FactionsPlugin.instance.log("Found WorldGuard 7+"); FactionsPlugin.getInstance().log("Found WorldGuard 7+");
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("Found WorldGuard <7"); FactionsPlugin.getInstance().log("Found WorldGuard <7");
} }
} }
} }
@@ -95,42 +92,6 @@ public class Worldguard {
return associable; return associable;
} }
public static boolean isPvPDisabled(Location l) {
try {
ApplicableRegionSet regionSet = Objects.requireNonNull(instance.getRegionManager(l.getWorld())).getApplicableRegions(l);
if (regionSet.size() < 1) {
try {
return Objects.requireNonNull(Objects.requireNonNull(instance.getRegionManager(l.getWorld())).getRegion("__global__")).getFlags().get(DefaultFlag.PVP) == StateFlag.State.DENY;
} catch (Exception e) {
if (!(e instanceof NullPointerException)) {
e.printStackTrace();
}
return false;
}
} else {
boolean return_flag = false;
int return_priority = -1;
for (ProtectedRegion region : regionSet) {
if (region.getFlags().containsKey(DefaultFlag.PVP)) {
StateFlag.State pvp_flag = (StateFlag.State) region.getFlags().get(DefaultFlag.PVP);
int region_priority = region.getPriority();
if (return_priority == -1) {
return_flag = pvp_flag == StateFlag.State.DENY;
return_priority = region_priority;
} else if (region_priority > return_priority) {
return_flag = pvp_flag == StateFlag.State.DENY;
return_priority = region_priority;
}
}
}
return return_flag;
}
} catch (Exception e) {
return false;
}
}
/** /**
* Credits to the people listed above for using reflections to load WorldGuard 6.0 & 7.0 in 1 class! * Credits to the people listed above for using reflections to load WorldGuard 6.0 & 7.0 in 1 class!
*/ */
@@ -159,8 +120,8 @@ public class Worldguard {
breakFlag = (StateFlag) flagsClass.getField("BREAK").get(null); breakFlag = (StateFlag) flagsClass.getField("BREAK").get(null);
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("We failed to load some part of World Guard. Support will be removed!"); FactionsPlugin.getInstance().log("We failed to load some part of World Guard. Support will be removed!");
FactionsPlugin.instance.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; return;
} }
@@ -178,8 +139,8 @@ public class Worldguard {
breakFlag = (StateFlag) flagsClass.getField("BREAK").get(null); breakFlag = (StateFlag) flagsClass.getField("BREAK").get(null);
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("We failed to load some part of World Guard. Support will be removed!"); FactionsPlugin.getInstance().log("We failed to load some part of World Guard. Support will be removed!");
FactionsPlugin.instance.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; return;
} }
@@ -195,8 +156,8 @@ public class Worldguard {
vectorConstructorAsAMethodBecauseWhyNot = vectorClass.getMethod("at", Double.TYPE, Double.TYPE, Double.TYPE); vectorConstructorAsAMethodBecauseWhyNot = vectorClass.getMethod("at", Double.TYPE, Double.TYPE, Double.TYPE);
regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass); regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass);
} catch (Exception sodonewiththis) { } catch (Exception sodonewiththis) {
FactionsPlugin.instance.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.instance.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; return;
} }
@@ -216,7 +177,7 @@ public class Worldguard {
regionManager = (RegionManager) regionContainerGetMethod.invoke(regionContainer, world); regionManager = (RegionManager) regionContainerGetMethod.invoke(regionContainer, world);
} }
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("An error occurred looking up a WorldGuard RegionManager"); FactionsPlugin.getInstance().log("An error occurred looking up a WorldGuard RegionManager");
} }
return regionManager; return regionManager;
} }
@@ -230,8 +191,8 @@ public class Worldguard {
: vectorConstructorAsAMethodBecauseWhyNot.invoke(null, location.getX(), location.getY(), location.getZ()); : vectorConstructorAsAMethodBecauseWhyNot.invoke(null, location.getX(), location.getY(), location.getZ());
return (ApplicableRegionSet) regionManagerGetMethod.invoke(regionManager, vector); return (ApplicableRegionSet) regionManagerGetMethod.invoke(regionManager, vector);
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("An error occurred looking up a WorldGuard ApplicableRegionSet"); FactionsPlugin.getInstance().log("An error occurred looking up a WorldGuard ApplicableRegionSet");
FactionsPlugin.instance.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!");
} }
return null; return null;
} }
@@ -255,8 +216,8 @@ public class Worldguard {
} else } else
return (boolean) regionQueryTestStateMethod.invoke(query, location, getAssociable(player), new StateFlag[]{buildFlag}); return (boolean) regionQueryTestStateMethod.invoke(query, location, getAssociable(player), new StateFlag[]{buildFlag});
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("An error occurred querying WorldGuard! Report this issue to SF Developers!"); FactionsPlugin.getInstance().log("An error occurred querying WorldGuard! Report this issue to SF Developers!");
FactionsPlugin.instance.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!");
} }
} }
return true; return true;
@@ -281,8 +242,8 @@ public class Worldguard {
return (boolean) regionQueryTestStateMethod.invoke(query, location, getAssociable(player), new StateFlag[]{breakFlag}); return (boolean) regionQueryTestStateMethod.invoke(query, location, getAssociable(player), new StateFlag[]{breakFlag});
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("An error occurred querying WorldGuard! Report this issue to SF Developers!"); FactionsPlugin.getInstance().log("An error occurred querying WorldGuard! Report this issue to SF Developers!");
FactionsPlugin.instance.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!");
} }
} }
return true; return true;
@@ -320,8 +281,8 @@ public class Worldguard {
return overlaps != null && !overlaps.isEmpty(); return overlaps != null && !overlaps.isEmpty();
} catch (Exception ex) { } catch (Exception ex) {
FactionsPlugin.instance.log("An error occurred querying WorldGuard! Report this issue to SF Developers!"); FactionsPlugin.getInstance().log("An error occurred querying WorldGuard! Report this issue to SF Developers!");
FactionsPlugin.instance.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!");
} }
} }
return false; return false;

View File

@@ -12,6 +12,8 @@ import org.dynmap.DynmapAPI;
import org.dynmap.markers.*; import org.dynmap.markers.*;
import org.dynmap.utils.TileFlags; import org.dynmap.utils.TileFlags;
import java.awt.*;
import java.util.List;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -50,6 +52,8 @@ public class EngineDynmap {
public MarkerAPI markerApi; public MarkerAPI markerApi;
public MarkerSet markerset; public MarkerSet markerset;
List<List<Point>> polyLine = new ArrayList<List<Point>>();
private EngineDynmap() { private EngineDynmap() {
} }
@@ -80,9 +84,7 @@ public class EngineDynmap {
for (int i = 0; i < string.length(); i++) { for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i); char c = string.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("&#") out.append("&#").append((int) c).append(';');
.append((int) c)
.append(';');
} else { } else {
out.append(c); out.append(c);
} }
@@ -121,10 +123,12 @@ public class EngineDynmap {
} }
// Shedule non thread safe sync at the end! // Shedule non thread safe sync at the end!
Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () ->
{
final Map<String, TempMarker> homes = createHomes(); final Map<String, TempMarker> homes = createHomes();
final Map<String, TempAreaMarker> areas = createAreas(); final Map<String, TempAreaMarker> areas = createAreas();
final Map<String, TempPolyLineMarker> polys = createPolys(areas);
final Map<String, Set<String>> playerSets = createPlayersets(); final Map<String, Set<String>> playerSets = createPlayersets();
if (!updateCore()) { if (!updateCore()) {
@@ -138,6 +142,7 @@ public class EngineDynmap {
updateHomes(homes); updateHomes(homes);
updateAreas(areas); updateAreas(areas);
updatePolys(polys);
updatePlayersets(playerSets); updatePlayersets(playerSets);
}, 100L, 100L); }, 100L, 100L);
} }
@@ -239,6 +244,7 @@ public class EngineDynmap {
// NOTE: That way what is left at the end will be outdated markers to remove. // NOTE: That way what is left at the end will be outdated markers to remove.
Marker marker = markers.remove(markerId); Marker marker = markers.remove(markerId);
if (marker == null) { if (marker == null) {
marker = temp.create(this.markerApi, this.markerset, markerId);
marker = temp.create(this.markerApi, this.markerset, markerId); marker = temp.create(this.markerApi, this.markerset, markerId);
if (marker == null) { if (marker == null) {
EngineDynmap.severe("Could not get/create the home marker " + markerId); EngineDynmap.severe("Could not get/create the home marker " + markerId);
@@ -260,6 +266,29 @@ public class EngineDynmap {
// -------------------------------------------- // // -------------------------------------------- //
// Thread Safe: YES // Thread Safe: YES
public Map<String, TempPolyLineMarker> createPolys(Map<String, TempAreaMarker> areas) {
Map<String, TempPolyLineMarker> ret = new HashMap<String, TempPolyLineMarker>();
for (Entry<String, TempAreaMarker> entry : areas.entrySet()) {
String markerID = entry.getKey();
TempAreaMarker area = entry.getValue();
int counter = 0;
for (List<Point> points : area.getPolyLine()) {
markerID = markerID + "_poly_" + counter;
TempPolyLineMarker tempPoly = new TempPolyLineMarker();
tempPoly.polyLine = points;
tempPoly.lineColor = area.lineColor;
tempPoly.lineOpacity = area.lineOpacity;
tempPoly.lineWeight = area.lineWeight;
tempPoly.world = area.world;
ret.put(markerID, tempPoly);
counter++;
}
}
return ret;
}
public Map<String, TempAreaMarker> createAreas() { public Map<String, TempAreaMarker> createAreas() {
Map<String, Map<Faction, Set<FLocation>>> worldFactionChunks = createWorldFactionChunks(); Map<String, Map<Faction, Set<FLocation>>> worldFactionChunks = createWorldFactionChunks();
return createAreas(worldFactionChunks); return createAreas(worldFactionChunks);
@@ -351,12 +380,11 @@ public class EngineDynmap {
// Loop through until we don't find more areas // Loop through until we don't find more areas
while (allChunks != null) { while (allChunks != null) {
TileFlags ourChunkFlags = null; TileFlags ourChunkFlags = null;
LinkedList<FLocation> ourChunks = null; LinkedList<FLocation> ourChunks = null;
LinkedList<FLocation> newChunks = null; LinkedList<FLocation> newChunks = null;
int minimumX = Integer.MAX_VALUE;
int minimumZ = Integer.MAX_VALUE;
for (FLocation chunk : allChunks) { for (FLocation chunk : allChunks) {
int chunkX = (int) chunk.getX(); int chunkX = (int) chunk.getX();
int chunkZ = (int) chunk.getZ(); int chunkZ = (int) chunk.getZ();
@@ -367,18 +395,10 @@ public class EngineDynmap {
ourChunks = new LinkedList<>(); ourChunks = new LinkedList<>();
floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape
ourChunks.add(chunk); // Add it to our chunk list ourChunks.add(chunk); // Add it to our chunk list
minimumX = chunkX;
minimumZ = chunkZ;
} }
// If shape found, and we're in it, add to our node list // If shape found, and we're in it, add to our node list
else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) {
ourChunks.add(chunk); ourChunks.add(chunk);
if (chunkX < minimumX) {
minimumX = chunkX;
minimumZ = chunkZ;
} else if (chunkX == minimumX && chunkZ < minimumZ) {
minimumZ = chunkZ;
}
} }
// Else, keep it in the list for the next polygon // Else, keep it in the list for the next polygon
else { else {
@@ -391,86 +411,129 @@ public class EngineDynmap {
// Replace list (null if no more to process) // Replace list (null if no more to process)
allChunks = newChunks; allChunks = newChunks;
if (ourChunkFlags == null) { if (ourChunkFlags == null) {
continue; continue;
} }
List<TempLine> outputLines = new ArrayList<TempLine>();
Map<TempLine, Integer> lines = new HashMap<TempLine, Integer>();
// Trace outline of blocks - start from minx, minz going to x+ if (ourChunks == null) {
int initialX = minimumX; continue;
int initialZ = minimumZ;
int currentX = minimumX;
int currentZ = minimumZ;
Direction direction = Direction.XPLUS;
ArrayList<int[]> linelist = new ArrayList<>();
linelist.add(new int[]{initialX, initialZ}); // Add start point
while ((currentX != initialX) || (currentZ != initialZ) || (direction != Direction.ZMINUS)) {
switch (direction) {
case XPLUS: // Segment in X+ direction
if (!ourChunkFlags.getFlag(currentX + 1, currentZ)) { // Right turn?
linelist.add(new int[]{currentX + 1, currentZ}); // Finish line
direction = Direction.ZPLUS; // Change direction
} else if (!ourChunkFlags.getFlag(currentX + 1, currentZ - 1)) { // Straight?
currentX++;
} else { // Left turn
linelist.add(new int[]{currentX + 1, currentZ}); // Finish line
direction = Direction.ZMINUS;
currentX++;
currentZ--;
} }
break;
case ZPLUS: // Segment in Z+ direction for (FLocation loc : ourChunks) {
if (!ourChunkFlags.getFlag(currentX, currentZ + 1)) { // Right turn? int x = loc.getChunk().getX();
linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line int z = loc.getChunk().getZ();
direction = Direction.XMINUS; // Change direction
} else if (!ourChunkFlags.getFlag(currentX + 1, currentZ + 1)) { // Straight? TempLine line = new TempLine(new Point(x * 16, z * 16), new Point(x * 16 + 16, z * 16));
currentZ++; if (lines.containsKey(line)) {
} else { // Left turn lines.put(line, lines.get(line) + 1);
linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line } else {
direction = Direction.XPLUS; lines.put(line, 1);
currentX++;
currentZ++;
} }
break;
case XMINUS: // Segment in X- direction line = new TempLine(new Point(x * 16 + 16, z * 16), new Point(x * 16 + 16, z * 16 + 16));
if (!ourChunkFlags.getFlag(currentX - 1, currentZ)) { // Right turn? if (lines.containsKey(line)) {
linelist.add(new int[]{currentX, currentZ + 1}); // Finish line lines.put(line, lines.get(line) + 1);
direction = Direction.ZMINUS; // Change direction } else {
} else if (!ourChunkFlags.getFlag(currentX - 1, currentZ + 1)) { // Straight? lines.put(line, 1);
currentX--;
} else { // Left turn
linelist.add(new int[]{currentX, currentZ + 1}); // Finish line
direction = Direction.ZPLUS;
currentX--;
currentZ++;
} }
break;
case ZMINUS: // Segment in Z- direction line = new TempLine(new Point(x * 16 + 16, z * 16 + 16), new Point(x * 16, z * 16 + 16));
if (!ourChunkFlags.getFlag(currentX, currentZ - 1)) { // Right turn? if (lines.containsKey(line)) {
linelist.add(new int[]{currentX, currentZ}); // Finish line lines.put(line, lines.get(line) + 1);
direction = Direction.XPLUS; // Change direction } else {
} else if (!ourChunkFlags.getFlag(currentX - 1, currentZ - 1)) { // Straight? lines.put(line, 1);
currentZ--;
} else { // Left turn
linelist.add(new int[]{currentX, currentZ}); // Finish line
direction = Direction.XMINUS;
currentX--;
currentZ--;
} }
break;
line = new TempLine(new Point(x * 16, z * 16 + 16), new Point(x * 16, z * 16));
if (lines.containsKey(line)) {
lines.put(line, lines.get(line) + 1);
} else {
lines.put(line, 1);
} }
} }
int sz = linelist.size(); Iterator<Entry<TempLine, Integer>> iterator = lines.entrySet().iterator();
double[] x = new double[sz];
double[] z = new double[sz]; List<TempLine> lineList = new ArrayList<TempLine>();
for (int i = 0; i < sz; i++) { lineList.addAll(lines.keySet());
int[] line = linelist.get(i);
x[i] = (double) line[0] * (double) BLOCKS_PER_CHUNK; while (iterator.hasNext()) {
z[i] = (double) line[1] * (double) BLOCKS_PER_CHUNK; Entry<TempLine, Integer> entry = iterator.next();
if (entry.getValue() > 1) {
lineList.remove(entry.getKey());
} }
}
// Find the leftmost MCRWPoint
TempLine l = null;
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine tl = it.next();
if (l == null || tl.getP1().x < l.getP1().x)
l = tl;
}
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine tl = it.next();
if (tl.getP2().x < l.getP2().x)
l = tl;
}
outputLines.add(l);
lineList.remove(l);
while (lineList.size() > 0) {
// MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1);
// MCRWPointWLines.get(targetp);
TempLine nextLine = null;
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine line = it.next();
if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) {
nextLine = line;
}
}
if (nextLine != null) {
outputLines.add(nextLine);
lineList.remove(nextLine);
l = nextLine;
} else {
outputLines.get(outputLines.size() - 1).addAdditionLines(CamScan1(lineList));
break;
}
}
List<Point> outputPoints = new ArrayList<Point>();
List<Point> polyPoints = new ArrayList<Point>();
for (int i = 0; i < outputLines.size(); i++) {
Point p = new Point(outputLines.get(i).getP1().x, outputLines.get(i).getP1().y);
outputPoints.add(p);
polyPoints.add(p);
if (outputLines.get(i).getConnectedLines().size() > 0) {
outputPoints.addAll(addRecursivePoints(new Point(outputLines.get(i).getP1().x, outputLines.get(i).getP1().y), outputLines.get(i)));
}
p = new Point(outputLines.get(i).getP2().x, outputLines.get(i).getP2().y);
outputPoints.add(p);
polyPoints.add(p);
}
polyLine.add(polyPoints);
// Build information for specific area // Build information for specific area
double[] x = new double[outputPoints.size()];
double[] z = new double[outputPoints.size()];
for (int i = 0; i < outputPoints.size(); i++) {
x[i] = outputPoints.get(i).x;
z[i] = outputPoints.get(i).y;
}
String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex;
TempAreaMarker temp = new TempAreaMarker(); TempAreaMarker temp = new TempAreaMarker();
@@ -488,8 +551,10 @@ public class EngineDynmap {
temp.fillOpacity = style.getFillOpacity(); temp.fillOpacity = style.getFillOpacity();
temp.boost = style.getBoost(); temp.boost = style.getBoost();
temp.setPolyLine(polyLine);
ret.put(markerId, temp); ret.put(markerId, temp);
polyLine.clear();
markerIndex++; markerIndex++;
} }
@@ -497,10 +562,114 @@ public class EngineDynmap {
return ret; return ret;
} }
public List<Point> addRecursivePoints(Point returnPoint, TempLine line) {
List<Point> ret = new ArrayList<Point>();
boolean shouldReturn = false;
List<TempLine> connectedLines = line.getConnectedLines();
List<Point> polyPoints = new ArrayList<Point>();
for (TempLine line2 : connectedLines) {
Point p = new Point(line2.getP1().x, line2.getP1().y);
ret.add(p);
polyPoints.add(p);
shouldReturn = true;
if (line2.getConnectedLines().size() > 0) {
ret.addAll(addRecursivePoints(new Point(line2.getP1().x, line2.getP1().y), line2));
}
p = new Point(line2.getP2().x, line2.getP2().y);
ret.add(p);
polyPoints.add(p);
}
if (shouldReturn) {
ret.add(returnPoint);
}
polyLine.add(polyPoints);
return ret;
}
private List<TempLine> CamScan1(List<TempLine> lineList) {
List<TempLine> ret = new ArrayList<TempLine>();
// Find the leftmost MCRWPoint
TempLine l = null;
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine tl = it.next();
if (l == null || tl.getP1().x < l.getP1().x)
l = tl;
}
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine tl = it.next();
if (tl.getP2().x < l.getP2().x)
l = tl;
}
ret.add(l);
lineList.remove(l);
while (lineList.size() > 0) {
// MCRWPoint targetp = new MCRWPoint((int) lastLine.x1, (int) lastLine.y1);
// MCRWPointWLines.get(targetp);
TempLine thisChunkLine = null;
for (Iterator<TempLine> it = lineList.iterator(); it.hasNext(); ) {
TempLine line = it.next();
if (l.getP2().x == line.getP1().x && l.getP2().y == line.getP1().y) {
thisChunkLine = line;
}
}
if (thisChunkLine != null) {
ret.add(thisChunkLine);
lineList.remove(thisChunkLine);
l = thisChunkLine;
} else {
// break;
ret.get(ret.size() - 1).addAdditionLines(CamScan1(lineList));
}
}
return ret;
}
// -------------------------------------------- // // -------------------------------------------- //
// UTIL & SHARED // UTIL & SHARED
// -------------------------------------------- // // -------------------------------------------- //
public void updatePolys(Map<String, TempPolyLineMarker> polys) {
// Map Current
Map<String, PolyLineMarker> markers = new HashMap<>();
for (PolyLineMarker marker : this.markerset.getPolyLineMarkers()) {
markers.put(marker.getMarkerID(), marker);
}
// Loop New
for (Entry<String, TempPolyLineMarker> entry : polys.entrySet()) {
String markerId = entry.getKey();
TempPolyLineMarker temp = entry.getValue();
// Get Creative
// NOTE: I remove from the map created just in the beginning of this method.
// NOTE: That way what is left at the end will be outdated markers to remove.
PolyLineMarker marker = markers.remove(markerId);
if (marker == null) {
marker = temp.create(this.markerset, markerId);
if (marker == null) {
severe("Could not get/create the area marker " + markerId);
}
} else {
temp.update(marker);
}
}
// Only old/outdated should now be left. Delete them.
for (PolyLineMarker marker : markers.values()) {
marker.deleteMarker();
}
}
// Thread Safe: NO // Thread Safe: NO
public void updateAreas(Map<String, TempAreaMarker> areas) { public void updateAreas(Map<String, TempAreaMarker> areas) {
// Map Current // Map Current
@@ -658,7 +827,6 @@ public class EngineDynmap {
money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); money = String.format("%.2f", Econ.getBalance(faction.getAccountId()));
ret = ret.replace("%money%", money); ret = ret.replace("%money%", money);
// Players // Players
Set<FPlayer> playersList = faction.getFPlayers(); Set<FPlayer> playersList = faction.getFPlayers();
String playersCount = String.valueOf(playersList.size()); String playersCount = String.valueOf(playersList.size());
@@ -675,7 +843,6 @@ public class EngineDynmap {
String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); String playersModeratorsCount = String.valueOf(playersModeratorsList.size());
String playersModerators = getHtmlPlayerString(playersModeratorsList); String playersModerators = getHtmlPlayerString(playersModeratorsList);
ArrayList<FPlayer> playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); ArrayList<FPlayer> playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL);
String playersNormalsCount = String.valueOf(playersNormalsList.size()); String playersNormalsCount = String.valueOf(playersNormalsList.size());
String playersNormals = getHtmlPlayerString(playersNormalsList); String playersNormals = getHtmlPlayerString(playersNormalsList);

View File

@@ -3,6 +3,10 @@ package com.massivecraft.factions.integration.dynmap;
import org.dynmap.markers.AreaMarker; import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.MarkerSet; import org.dynmap.markers.MarkerSet;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class TempAreaMarker { public class TempAreaMarker {
/** /**
@@ -18,15 +22,13 @@ public class TempAreaMarker {
public double[] x; public double[] x;
public double[] z; public double[] z;
public String description; public String description;
public int lineColor; public int lineColor;
public double lineOpacity; public double lineOpacity;
public int lineWeight; public int lineWeight;
public int fillColor; public int fillColor;
public double fillOpacity; public double fillOpacity;
public boolean boost; public boolean boost;
private List<List<Point>> polyLine = new ArrayList<List<Point>>();
// -------------------------------------------- // // -------------------------------------------- //
// CREATE // CREATE
@@ -54,6 +56,15 @@ public class TempAreaMarker {
return true; return true;
} }
public List<List<Point>> getPolyLine() {
return polyLine;
}
public void setPolyLine(List<List<Point>> points) {
polyLine.clear();
polyLine.addAll(points);
}
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE // UPDATE
// -------------------------------------------- // // -------------------------------------------- //
@@ -61,16 +72,17 @@ public class TempAreaMarker {
public AreaMarker create(MarkerSet markerset, String markerId) { public AreaMarker create(MarkerSet markerset, String markerId) {
AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent
); );
if (ret == null) { if (ret == null) {
return null; return null;
} }
int counter = 0;
// Description // Description
ret.setDescription(this.description); ret.setDescription(this.description);
// Line Style // Line Style
ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); ret.setLineStyle(0, 0, 0);
// Fill Style // Fill Style
ret.setFillStyle(this.fillOpacity, this.fillColor); ret.setFillStyle(this.fillOpacity, this.fillColor);
@@ -80,7 +92,6 @@ public class TempAreaMarker {
return ret; return ret;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UTIL // UTIL
// -------------------------------------------- // // -------------------------------------------- //
@@ -95,18 +106,15 @@ public class TempAreaMarker {
if (!marker.getLabel().equals(this.label)) { if (!marker.getLabel().equals(this.label)) {
marker.setLabel(this.label); marker.setLabel(this.label);
} }
// Description
if (!marker.getDescription().equals(this.description)) { if (!marker.getDescription().equals(this.description)) {
marker.setDescription(this.description); marker.setDescription(this.description);
} }
// Line Style // // Line Style
if (marker.getLineWeight() != this.lineWeight || // if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor)
marker.getLineOpacity() != this.lineOpacity || // {
marker.getLineColor() != this.lineColor) { // marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); // }
}
// Fill Style // Fill Style
if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) {

View File

@@ -0,0 +1,49 @@
package com.massivecraft.factions.integration.dynmap;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class TempLine {
private Point p1;
private Point p2;
private List<TempLine> connectedLines = new ArrayList<TempLine>();
TempLine(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public void addAdditionLines(List<TempLine> connectedLines) {
this.connectedLines = connectedLines;
}
public List<TempLine> getConnectedLines() {
return connectedLines;
}
@Override
public boolean equals(Object o) {
TempLine line = (TempLine) o;
if (line.p1.x == this.p1.x && line.p2.x == this.p2.x && line.p1.y == this.p1.y && line.p2.y == this.p2.y) {
return true;
}
return line.p1.x == this.p2.x && line.p2.x == this.p1.x && line.p1.y == this.p2.y && line.p2.y == this.p1.y;
}
@Override
public int hashCode() {
String test = "" + (p1.x + p2.x);
test += " " + (p1.y + p2.y);
return test.hashCode();
}
}

View File

@@ -0,0 +1,99 @@
package com.massivecraft.factions.integration.dynmap;
import org.dynmap.markers.MarkerSet;
import org.dynmap.markers.PolyLineMarker;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class TempPolyLineMarker {
/**
* @author FactionsUUID Team
*/
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
public String world;
public List<Point> polyLine = new ArrayList<Point>();
public int lineColor;
public double lineOpacity;
public int lineWeight;
// -------------------------------------------- //
// CREATE
// -------------------------------------------- //
public static boolean equals(PolyLineMarker marker, List<Point> points) {
int length = marker.getCornerCount();
if (points.size() != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (marker.getCornerX(i) != points.get(i).x) {
return false;
}
if (marker.getCornerZ(i) != points.get(i).y) {
return false;
}
}
return true;
}
// -------------------------------------------- //
// UPDATE
// -------------------------------------------- //
public PolyLineMarker create(MarkerSet markerset, String markerId) {
double[] polyX = new double[polyLine.size()];
double[] polyY = new double[polyLine.size()];
double[] polyZ = new double[polyLine.size()];
for (int i = 0; i < polyLine.size(); i++) {
Point p = polyLine.get(i);
polyX[i] = p.getX();
polyY[i] = 64;
polyZ[i] = p.getY();
}
PolyLineMarker poly = markerset.createPolyLineMarker(markerId, "", false, this.world, polyX, polyY, polyZ, false);
// Poly Line Style
if (poly != null) {
poly.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
}
return poly;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public void update(PolyLineMarker marker) {
// Corner Locations
if (!equals(marker, polyLine)) {
double[] polyX = new double[polyLine.size()];
double[] polyY = new double[polyLine.size()];
double[] polyZ = new double[polyLine.size()];
for (int i = 0; i < polyLine.size(); i++) {
Point p = polyLine.get(i);
polyX[i] = p.getX();
polyY[i] = 64;
polyZ[i] = p.getY();
}
marker.setCornerLocations(polyX, polyY, polyZ);
marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
}
// Line Style
if (marker.getLineWeight() != this.lineWeight || marker.getLineOpacity() != this.lineOpacity || marker.getLineColor() != this.lineColor) {
marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
}
}
}

View File

@@ -1,5 +1,6 @@
package com.massivecraft.factions.listeners; package com.massivecraft.factions.listeners;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.*; import com.massivecraft.factions.*;
import com.massivecraft.factions.cmd.audit.FLogManager; import com.massivecraft.factions.cmd.audit.FLogManager;
import com.massivecraft.factions.cmd.audit.LogTimer; import com.massivecraft.factions.cmd.audit.LogTimer;
@@ -8,7 +9,6 @@ import com.massivecraft.factions.struct.Permission;
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.ItemBuilder; import com.massivecraft.factions.util.ItemBuilder;
import com.massivecraft.factions.util.XMaterial;
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;
@@ -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;
@@ -94,26 +93,23 @@ 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 { else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) {
String replace = TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString());
if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) {
me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc)));
if (shouldHurt) { if (shouldHurt) {
player.damage(Conf.actionDeniedPainAmount); player.damage(Conf.actionDeniedPainAmount);
me.msg(replace.replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction)));
} }
return false; return false;
} else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway } else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway
if (shouldHurt) { if (shouldHurt) {
player.damage(Conf.actionDeniedPainAmount); player.damage(Conf.actionDeniedPainAmount);
if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null) if ((Board.getInstance().getFactionAt(loc).getTag(myFaction)) != null)
me.msg(replace.replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction)));
} }
if (myFaction.getTag(me.getFaction()) != null && action != null) if (myFaction.getTag(me.getFaction()) != null && action != null)
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString()));
return false; return false;
} else if (access == Access.ALLOW) return true; } else if (access == Access.ALLOW) return true;
}
me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString()));
return false; return false;
} }
@@ -183,12 +179,18 @@ public class FactionsBlockListener implements Listener {
@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.getBlock().isLiquid()) {
if (event.getToBlock().isEmpty()) { if (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.isSystemFaction()) {
event.setCancelled(true);
return;
}
if (to.isNormal()) { if (to.isNormal()) {
if (from.isNormal() && from.getRelationTo(to).isAlly()) { if (from.isNormal() && from.getRelationTo(to).isAlly()) {
return; return;
@@ -416,9 +418,8 @@ public class FactionsBlockListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onFrostWalker(EntityBlockFormEvent event) { public void onFrostWalker(EntityBlockFormEvent event) {
if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null) { if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null)
return; return;
}
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
Location location = event.getBlock().getLocation(); Location location = event.getBlock().getLocation();
@@ -426,15 +427,12 @@ public class FactionsBlockListener implements Listener {
// only notify every 10 seconds // only notify every 10 seconds
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis();
if (!justCheck) { if (!justCheck) fPlayer.setLastFrostwalkerMessage();
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)) { if (!playerCanBuildDestroyBlock(player, location, PermissableAction.FROST_WALK.toString(), justCheck))
event.setCancelled(true); event.setCancelled(true);
} }
}
@EventHandler @EventHandler
public void onFallingBlock(EntityChangeBlockEvent event) { public void onFallingBlock(EntityChangeBlockEvent event) {
@@ -448,29 +446,6 @@ public class FactionsBlockListener implements Listener {
} }
} }
//Grace
@EventHandler
public void onBreak(EntityExplodeEvent e) {
if (!Conf.gracePeriod) return;
e.setCancelled(true);
}
@EventHandler
public void onTNTPlace(BlockPlaceEvent e1) {
FPlayer fp = FPlayers.getInstance().getByPlayer(e1.getPlayer());
if (!Conf.gracePeriod) return;
if (!fp.isAdminBypassing()) {
if (e1.getBlock().getType().equals(Material.TNT)) {
e1.setCancelled(true);
fp.msg(TL.COMMAND_GRACE_ENABLED, e1.getBlockPlaced().getType().toString());
}
}
}
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));
@@ -493,7 +468,6 @@ public class FactionsBlockListener implements Listener {
Faction at = Board.getInstance().getFactionAt(new FLocation(block)); Faction at = Board.getInstance().getFactionAt(new FLocation(block));
boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial()); boolean isSpawner = event.getBlock().getType().equals(XMaterial.SPAWNER.parseMaterial());
if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) {
event.setCancelled(true); event.setCancelled(true);
return; return;
@@ -538,6 +512,7 @@ public class FactionsBlockListener implements Listener {
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

@@ -7,7 +7,6 @@ import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.*; import org.bukkit.entity.*;
import org.bukkit.entity.minecart.ExplosiveMinecart; import org.bukkit.entity.minecart.ExplosiveMinecart;
@@ -95,11 +94,9 @@ public class FactionsEntityListener implements Listener {
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof EntityDamageByEntityEvent) { if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event; EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event;
if (!this.canDamagerHurtDamagee(sub, true)) { if (!this.canDamagerHurtDamagee(sub, true)) event.setCancelled(true);
event.setCancelled(true);
}
// event is not cancelled by factions
// event is not cancelled by factions
Entity damagee = sub.getEntity(); Entity damagee = sub.getEntity();
Entity damager = sub.getDamager(); Entity damager = sub.getDamager();
if (damagee instanceof Player) { if (damagee instanceof Player) {
@@ -126,15 +123,12 @@ public class FactionsEntityListener implements Listener {
// this should disable the fly so // this should disable the fly so
return; return;
} }
} else { } else return; // this should trigger if the attacker shootin the arrow is a mob
// this should trigger if the attacker shootin the arrow is a mob
return;
}
} }
} }
} else { } else {
// Protect armor stands/item frames from being damaged in protected territories // Protect armor stands/item frames from being damaged in protected territories
if (damagee.getType() == EntityType.ITEM_FRAME || damagee.getType().name().equals("armor_stand")) { if (damagee.getType() == EntityType.ITEM_FRAME || damagee.getType() == EntityType.ARMOR_STAND) {
// Manage projectiles launched by players // Manage projectiles launched by players
if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Entity) { if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Entity) {
damager = (Entity) ((Projectile) damager).getShooter(); damager = (Entity) ((Projectile) damager).getShooter();
@@ -142,37 +136,22 @@ public class FactionsEntityListener implements Listener {
// Run the check for a player // Run the check for a player
if (damager instanceof Player) { if (damager instanceof Player) {
Player player = (Player) damager;
Material material = null; if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) damager, damagee.getLocation(), "destroy", false))
switch (sub.getEntity().getType()) {
case ITEM_FRAME:
material = Material.ITEM_FRAME;
break;
case ARMOR_STAND:
material = Material.ARMOR_STAND;
break;
}
if (material != null && !FactionsBlockListener.playerCanBuildDestroyBlock(player, damagee.getLocation(), "destroy " + material.toString().toLowerCase(), false)) {
event.setCancelled(true); event.setCancelled(true);
}
} 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
return; return;
} }
//this one should trigger if something other than a player takes damage //this one should trigger if something other than a player takes damage
if (damager instanceof Player) { if (damager instanceof Player) return;
// now itll only go here if the damage is dealt by a player
return;
// we cancel it so fly isnt removed when you hit a mob etc
}
} }
if (damagee != null && damagee instanceof Player) { if (damagee != null && damagee instanceof Player) {
cancelFStuckTeleport((Player) damagee); cancelFStuckTeleport((Player) damagee);
@@ -216,6 +195,7 @@ public class FactionsEntityListener implements Listener {
} }
} }
private void cancelFFly(Player player) { private void cancelFFly(Player player) {
if (player == null) return; if (player == null) return;
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
@@ -277,6 +257,7 @@ public class FactionsEntityListener implements Listener {
private boolean checkExplosionForBlock(Entity boomer, Block block) { private boolean checkExplosionForBlock(Entity boomer, Block block) {
Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation()));
if (faction.isProtected()) return false;
if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom))
return false; return false;
@@ -347,7 +328,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();
} }
@@ -358,29 +338,34 @@ 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) {
FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager);
if (defender == null || defender.getPlayer() == null) return true; if (defender == null || defender.getPlayer() == null) return true;
if (attacker.getFaction() == defender.getFaction()) {
if (attacker.hasFriendlyFire() && defender.hasFriendlyFire()) return true;
if (attacker.hasFriendlyFire() && !defender.hasFriendlyFire()) {
attacker.msg(TL.FRIENDLY_FIRE_OFF_ATTACKER, defender.getName());
return false;
} else if (!attacker.hasFriendlyFire() && defender.hasFriendlyFire()) {
attacker.msg(TL.FRIENDLY_FIRE_YOU_MUST);
return false;
}
}
}
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;
if (!(projectile.getShooter() instanceof Entity)) return true; if (!(projectile.getShooter() instanceof Entity)) return true;
damager = (Entity) projectile.getShooter(); damager = (Entity) projectile.getShooter();
} }
if (damager == damagee) return true; // ender pearl usage and other self-inflicted damage if (damager == damagee) return true; // ender pearl usage and other self-inflicted damage
// Players can not take attack damage in a SafeZone, or possibly peaceful territory // Players can not take attack damage in a SafeZone or peaceful territory depending on Conf options.
if (defLocFaction.noPvPInTerritory()) { if (defLocFaction.noPvPInTerritory()) {
if (damager instanceof Player) { if (damager instanceof Player) {
if (notify) { if (notify) {
@@ -394,19 +379,14 @@ public class FactionsEntityListener implements Listener {
if (!(damager instanceof Player)) return true; if (!(damager instanceof Player)) return true;
FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager);
if (attacker == null || attacker.getPlayer() == null) return true; if (attacker == null || attacker.getPlayer() == null) return true;
if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true; if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true;
if (attacker.hasLoginPvpDisabled()) { if (attacker.hasLoginPvpDisabled()) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin);
attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin);
}
return false; return false;
} }
@@ -414,47 +394,32 @@ public class FactionsEntityListener implements Listener {
// so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be?
if (locFaction.noPvPInTerritory()) { if (locFaction.noPvPInTerritory()) {
if (notify) { if (notify)
attacker.msg(TL.PLAYER_CANTHURT, (locFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); attacker.msg(TL.PLAYER_CANTHURT, (locFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString()));
}
return false; return false;
} }
if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) return true; if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) return true;
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) return true; if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) return true;
Faction defendFaction = defender.getFaction(); Faction defendFaction = defender.getFaction();
Faction attackFaction = attacker.getFaction(); Faction attackFaction = attacker.getFaction();
if (attackFaction.isWilderness() && Conf.disablePVPForFactionlessPlayers) { if (attackFaction.isWilderness() && Conf.disablePVPForFactionlessPlayers) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_REQUIREFACTION);
attacker.msg(TL.PLAYER_PVP_REQUIREFACTION);
}
return false; return false;
} else if (defendFaction.isWilderness()) { } else if (defendFaction.isWilderness()) {
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) {
// Allow PVP vs. Factionless in attacker's faction territory // Allow PVP vs. Factionless in attacker's faction territory
return true; return true;
} else if (Conf.disablePVPForFactionlessPlayers) { } else if (Conf.disablePVPForFactionlessPlayers) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_FACTIONLESS);
attacker.msg(TL.PLAYER_PVP_FACTIONLESS);
}
return false; return false;
} }
} }
if (defendFaction.isPeaceful()) { if (defendFaction.isPeaceful() || attackFaction.isPeaceful()) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_PEACEFUL);
attacker.msg(TL.PLAYER_PVP_PEACEFUL);
}
return false;
} else if (attackFaction.isPeaceful()) {
if (notify) {
attacker.msg(TL.PLAYER_PVP_PEACEFUL);
}
return false; return false;
} }
@@ -462,21 +427,16 @@ public class FactionsEntityListener implements Listener {
// You can not hurt neutral factions // You can not hurt neutral factions
if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_NEUTRAL);
attacker.msg(TL.PLAYER_PVP_NEUTRAL);
}
return false; return false;
} }
// Players without faction may be hurt anywhere // Players without faction may be hurt anywhere
if (!defender.hasFaction()) return true; if (!defender.hasFaction()) return true;
// You can never hurt faction members or allies // You can never hurt faction members or allies
if (relation.isMember() || relation.isAlly() || relation.isTruce()) { if (relation.isMember() || relation.isAlly()) {
if (notify) { if (notify) attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker));
attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker));
}
return false; return false;
} }
@@ -490,23 +450,10 @@ public class FactionsEntityListener implements Listener {
} }
return false; return false;
} }
// Damage will be dealt. However check if the damage should be reduced.
/*
if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) {
double newDamage = Math.ceil(damage * (1D - Conf.territoryShieldFactor));
sub.setDamage(newDamage);
// Send message
if (notify) {
String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly??
defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc);
}
} */
return true; return true;
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) { public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.getLocation() == null) return; if (event.getLocation() == null) return;
@@ -557,14 +504,10 @@ public class FactionsEntityListener implements Listener {
@EventHandler @EventHandler
public void onHangerBreak(HangingBreakByEntityEvent e) { public void onHangerBreak(HangingBreakByEntityEvent e) {
if (e.getRemover() == null) return;
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().equals(EntityType.PAINTING)) {
if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME) {
e.setCancelled(true);
}
} else if (e.getEntity().getType().equals(EntityType.ITEM_FRAME)) {
if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) {
e.setCancelled(true); e.setCancelled(true);
} }
@@ -572,48 +515,38 @@ public class FactionsEntityListener implements Listener {
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPaintingPlace(HangingPlaceEvent event) { public void onPaintingPlace(HangingPlaceEvent e) {
if (event.getEntity().getType().equals(EntityType.PAINTING)) { if (e.getPlayer() == null) return;
if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) {
event.setCancelled(true); if (e.getEntity().getType() == EntityType.PAINTING || e.getEntity().getType() == EntityType.ITEM_FRAME) {
// Fix: update player's inventory to avoid items glitches if (!FactionsBlockListener.playerCanBuildDestroyBlock(e.getPlayer(), e.getBlock().getLocation(), "build", false)) {
event.getPlayer().updateInventory(); e.setCancelled(true);
} e.getPlayer().updateInventory();
} else if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) {
if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getEntity().getLocation(), "build", false)) {
event.setCancelled(true);
// Fix: update player's inventory to avoid items glitches
event.getPlayer().updateInventory();
} }
} }
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent e) {
Entity entity = event.getEntity(); Entity entity = e.getEntity();
Location loc = e.getBlock().getLocation();
// for now, only interested in Enderman and Wither boss tomfoolery // for now, only interested in Enderman and Wither boss tomfoolery
if (!(entity instanceof Enderman) && !(entity instanceof Wither)) return; if (entity.getType() == EntityType.ENDERMAN) {
if (stopEndermanBlockManipulation(loc)) e.setCancelled(true);
} else if (entity.getType() == EntityType.WITHER) {
Location loc = event.getBlock().getLocation();
if (entity instanceof Enderman) {
if (stopEndermanBlockManipulation(loc)) {
event.setCancelled(true);
}
} else if (entity instanceof Wither) {
Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); Faction faction = Board.getInstance().getFactionAt(new FLocation(loc));
// it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever
if ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || if ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) ||
(faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) ||
(faction.isWarZone() && Conf.warZoneBlockFireballs) || (faction.isWarZone() && Conf.warZoneBlockFireballs) ||
faction.isSafeZone()) { faction.isSafeZone()) {
event.setCancelled(true); e.setCancelled(true);
} }
} }
} }
/* /*
@EventHandler @EventHandler
public void onTravel(PlayerPortalEvent event) { public void onTravel(PlayerPortalEvent event) {

View File

@@ -1,7 +1,7 @@
package com.massivecraft.factions.listeners; package com.massivecraft.factions.listeners;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.util.XMaterial;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;

View File

@@ -1,5 +1,6 @@
package com.massivecraft.factions.listeners; package com.massivecraft.factions.listeners;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.*; 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;
@@ -19,12 +20,11 @@ import com.massivecraft.factions.struct.Permission;
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.CC; import com.massivecraft.factions.util.CC;
import com.massivecraft.factions.util.wait.WaitExecutor;
import com.massivecraft.factions.zcore.frame.FactionGUI;
import com.massivecraft.factions.util.VisualizeUtil; import com.massivecraft.factions.util.VisualizeUtil;
import com.massivecraft.factions.util.XMaterial; import com.massivecraft.factions.util.wait.WaitExecutor;
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.frame.FactionGUI;
import com.massivecraft.factions.zcore.persist.MemoryFPlayer; import com.massivecraft.factions.zcore.persist.MemoryFPlayer;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import com.massivecraft.factions.zcore.util.TagUtil; import com.massivecraft.factions.zcore.util.TagUtil;
@@ -54,9 +54,9 @@ import java.util.logging.Level;
public class FactionsPlayerListener implements Listener { public class FactionsPlayerListener implements Listener {
public final static Map<UUID, Location> lastLocations = new HashMap<>();
public static Set<FLocation> corners; public static Set<FLocation> corners;
public static BukkitTask positionTask = null; public static BukkitTask positionTask = null;
public static Map<UUID, Location> lastLocations = new HashMap<>();
/** /**
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
@@ -308,7 +308,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) {
@@ -335,129 +335,37 @@ public class FactionsPlayerListener implements Listener {
} }
private static PermissableAction GetPermissionFromUsableBlock(Material material) { private static PermissableAction GetPermissionFromUsableBlock(Material material) {
// Check for doors that might have diff material name in old version. if (material.name().contains("_BUTTON")
if (material.name().contains("DOOR") || material.name().contains("FENCE_GATE")) || material.name().contains("COMPARATOR")
return PermissableAction.DOOR; || material.name().contains("PRESSURE")
if (material.name().toUpperCase().contains("BUTTON") || material.name().toUpperCase().contains("PRESSURE") || material.name().contains("DIODE") || material.name().contains("COMPARATOR")) || material.name().contains("REPEATER")
return PermissableAction.BUTTON; || material.name().contains("DIODE")) return PermissableAction.BUTTON;
if (FactionsPlugin.instance.mc113 || FactionsPlugin.instance.mc114 || FactionsPlugin.getInstance().mc115) { if (material.name().contains("_DOOR")
|| material.name().contains("_TRAPDOOR")
|| material.name().contains("_FENCE_GATE")
|| material.name().startsWith("FENCE_GATE")) return PermissableAction.DOOR;
if (material.name().contains("SHULKER_BOX")
|| material.name().endsWith("ANVIL")
|| material.name().startsWith("CHEST_MINECART")
|| material.name().endsWith("CHEST")
|| material.name().endsWith("JUKEBOX")
|| material.name().endsWith("CAULDRON")
|| material.name().endsWith("FURNACE")
|| material.name().endsWith("HOPPER")
|| material.name().endsWith("BEACON")
|| material.name().startsWith("TRAPPED_CHEST")
|| material.name().equalsIgnoreCase("ENCHANTING_TABLE")
|| material.name().equalsIgnoreCase("ENCHANTMENT_TABLE")
|| material.name().endsWith("BREWING_STAND")
|| material.name().equalsIgnoreCase("BARREL")) return PermissableAction.CONTAINER;
if (material.name().endsWith("LEVER")) return PermissableAction.LEVER;
switch (material) { switch (material) {
case LEVER:
return PermissableAction.LEVER;
case ACACIA_BUTTON:
case BIRCH_BUTTON:
case DARK_OAK_BUTTON:
case JUNGLE_BUTTON:
case OAK_BUTTON:
case SPRUCE_BUTTON:
case STONE_BUTTON:
case COMPARATOR:
case REPEATER:
return PermissableAction.BUTTON;
case ACACIA_DOOR:
case BIRCH_DOOR:
case IRON_DOOR:
case JUNGLE_DOOR:
case OAK_DOOR:
case SPRUCE_DOOR:
case DARK_OAK_DOOR:
case ACACIA_TRAPDOOR:
case BIRCH_TRAPDOOR:
case DARK_OAK_TRAPDOOR:
case IRON_TRAPDOOR:
case JUNGLE_TRAPDOOR:
case OAK_TRAPDOOR:
case SPRUCE_TRAPDOOR:
case ACACIA_FENCE_GATE:
case BIRCH_FENCE_GATE:
case DARK_OAK_FENCE_GATE:
case JUNGLE_FENCE_GATE:
case OAK_FENCE_GATE:
case SPRUCE_FENCE_GATE:
return PermissableAction.DOOR;
case CHEST:
case TRAPPED_CHEST:
case CHEST_MINECART:
case BARREL:
case SHULKER_BOX:
case BLACK_SHULKER_BOX:
case BLUE_SHULKER_BOX:
case BROWN_SHULKER_BOX:
case CYAN_SHULKER_BOX:
case GRAY_SHULKER_BOX:
case GREEN_SHULKER_BOX:
case LIGHT_BLUE_SHULKER_BOX:
case LIGHT_GRAY_SHULKER_BOX:
case LIME_SHULKER_BOX:
case MAGENTA_SHULKER_BOX:
case ORANGE_SHULKER_BOX:
case PINK_SHULKER_BOX:
case PURPLE_SHULKER_BOX:
case RED_SHULKER_BOX:
case WHITE_SHULKER_BOX:
case YELLOW_SHULKER_BOX:
case FURNACE:
case BLAST_FURNACE:
case SMOKER:
case DROPPER:
case DISPENSER: case DISPENSER:
case ENCHANTING_TABLE: case DROPPER:
case BREWING_STAND:
case CAULDRON:
case HOPPER:
case BEACON:
case JUKEBOX:
case ANVIL:
case CHIPPED_ANVIL:
case DAMAGED_ANVIL:
return PermissableAction.CONTAINER; return PermissableAction.CONTAINER;
default: default:
return null; return null;
} }
} else {
switch (material) {
case LEVER:
return PermissableAction.LEVER;
case DARK_OAK_DOOR:
case ACACIA_DOOR:
case BIRCH_DOOR:
case IRON_DOOR:
case JUNGLE_DOOR:
case SPRUCE_DOOR:
case ACACIA_FENCE_GATE:
case BIRCH_FENCE_GATE:
case OAK_FENCE_GATE:
case DARK_OAK_FENCE_GATE:
case JUNGLE_FENCE_GATE:
case SPRUCE_FENCE_GATE:
return PermissableAction.DOOR;
case CHEST:
case ENDER_CHEST:
case TRAPPED_CHEST:
case DISPENSER:
case ENCHANTING_TABLE:
case DROPPER:
case FURNACE:
case BLAST_FURNACE:
case SMOKER:
case HOPPER:
case ANVIL:
case CHIPPED_ANVIL:
case DAMAGED_ANVIL:
case BREWING_STAND:
return PermissableAction.CONTAINER;
default:
return null;
}
}
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
@@ -473,6 +381,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()));
@@ -529,6 +439,7 @@ public class FactionsPlayerListener implements Listener {
@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.
@@ -545,6 +456,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();
@@ -571,13 +484,13 @@ public class FactionsPlayerListener implements Listener {
} }
public void checkCanFly(FPlayer me) { public void checkCanFly(FPlayer me) {
if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) return; if (!me.canFlyAtLocation() || me.checkIfNearbyEnemies()) {
if (me.isFlying() && !me.isVanished() && (!me.canFlyAtLocation() || me.checkIfNearbyEnemies())) { if (me.isFlying())
me.setFFlying(false, false); me.setFFlying(false, false);
me.msg(TL.COMMAND_FLY_NO_ACCESS, Board.getInstance().getFactionAt(me.getLastStoodAt()).getTag());
return; return;
} }
if (me.isFlying() || !FactionsPlugin.instance.getConfig().getBoolean("ffly.AutoEnable")) return; if (me.isFlying() || !FactionsPlugin.instance.getConfig().getBoolean("ffly.AutoEnable"))
return;
me.setFFlying(true, false); me.setFFlying(true, false);
CmdFly.flyMap.put(me.getName(), true); CmdFly.flyMap.put(me.getName(), true);
if (CmdFly.particleTask == null) if (CmdFly.particleTask == null)
@@ -647,42 +560,13 @@ public class FactionsPlayerListener implements Listener {
} }
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());
if (player != null) {
refreshPosition(player, check.getValue(), player.getLocation());
lastLocations.put(player.getUniqueId(), player.getLocation()); lastLocations.put(player.getUniqueId(), player.getLocation());
continue;
}
refreshPosition(player, lastLocations.get(player.getUniqueId()), player.getLocation());
lastLocations.put(player.getUniqueId(), player.getLocation());
if (CmdFly.flyMap.containsKey(player.getName())) {
String name = player.getName();
if (!player.isFlying()
|| player.getGameMode() == GameMode.CREATIVE
|| !FactionsPlugin.instance.mc17 && player.getGameMode() == GameMode.SPECTATOR) {
continue;
}
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
Faction myFaction = fPlayer.getFaction();
if (myFaction.isWilderness()) {
Bukkit.getScheduler().runTask(FactionsPlugin.instance, () -> fPlayer.setFlying(false));
CmdFly.flyMap.remove(player.getName());
continue;
}
Bukkit.getScheduler().runTask(FactionsPlugin.instance, () -> {
if (!fPlayer.checkIfNearbyEnemies()) {
FLocation myFloc = new FLocation(player.getLocation());
if (Board.getInstance().getFactionAt(myFloc) != myFaction) {
if (!CmdFly.checkFly(fPlayer, player, Board.getInstance().getFactionAt(myFloc))) {
fPlayer.setFFlying(false, false);
CmdFly.flyMap.remove(name);
}
}
}
});
}
} }
} }
}, 5L, 10L); }, 5L, 10L);
@@ -747,10 +631,16 @@ public class FactionsPlayerListener implements Listener {
}, 5); }, 5);
} }
} }
this.checkCanFly(me);
checkCanFly(me);
Faction at = Board.getInstance().getFactionAt(new FLocation(me.getPlayer().getLocation()));
if (me.getAutoClaimFor() != null) { if (me.getAutoClaimFor() != null) {
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); 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()) {
@@ -825,7 +715,11 @@ public class FactionsPlayerListener implements Listener {
Material type; Material type;
if (event.getItem() != null) { if (event.getItem() != null) {
// Convert 1.8 Material Names -> 1.15 // Convert 1.8 Material Names -> 1.15
try {
type = XMaterial.matchXMaterial(event.getItem().getType().toString()).get().parseMaterial(); type = XMaterial.matchXMaterial(event.getItem().getType().toString()).get().parseMaterial();
} catch (NullPointerException npe) {
type = null;
}
} else { } else {
type = null; type = null;
} }
@@ -863,15 +757,12 @@ 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();
@@ -991,7 +882,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();

View File

@@ -1,9 +1,9 @@
package com.massivecraft.factions.missions; package com.massivecraft.factions.missions;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.zcore.frame.FactionGUI; import com.massivecraft.factions.zcore.frame.FactionGUI;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;

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

@@ -1,5 +1,6 @@
package com.massivecraft.factions.shop; package com.massivecraft.factions.shop;
import com.cryptomorin.xseries.XMaterial;
import com.github.stefvanschie.inventoryframework.Gui; import com.github.stefvanschie.inventoryframework.Gui;
import com.github.stefvanschie.inventoryframework.GuiItem; import com.github.stefvanschie.inventoryframework.GuiItem;
import com.github.stefvanschie.inventoryframework.pane.PaginatedPane; import com.github.stefvanschie.inventoryframework.pane.PaginatedPane;
@@ -7,14 +8,12 @@ import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -22,7 +21,9 @@ 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; import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ShopGUIFrame { public class ShopGUIFrame {
@@ -34,29 +35,30 @@ public class ShopGUIFrame {
private Gui gui; private Gui gui;
public ShopGUIFrame(Faction f) { public ShopGUIFrame(Faction f) {
gui = new Gui(FactionsPlugin.getInstance(), gui = new Gui(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Rows", 4), FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("F-Shop.GUI.Name")));
FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Rows", 4),
FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("F-Shop.GUI.Name")));
} }
public void buildGUI(FPlayer fplayer) { public void buildGUI(FPlayer fplayer) {
PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows());
List<GuiItem> GUIItems = new ArrayList<>(); List<GuiItem> GUIItems = new ArrayList<>();
ItemStack dummy = buildDummyItem(fplayer.getFaction()); ItemStack dummy = buildDummyItem(fplayer.getFaction());
for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true))); for (int x = 0; x <= (gui.getRows() * 9) - 1; x++)
GUIItems.add(new GuiItem(dummy, e -> e.setCancelled(true)));
Set<String> items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false);
for (String s : items) {
if (!checkShopConfig(s)) {
continue;
}
int items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false).size();
for (int a = 1; a <= items; a++) {
String s = a + "";
int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".slot"); int slot = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".slot");
ItemStack material = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".block")).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".block")).get().parseItem();
int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".cost"); int cost = FactionsPlugin.getInstance().getFileManager().getShop().fetchInt("items." + s + ".cost");
String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".name"); String name = FactionsPlugin.getInstance().getFileManager().getShop().fetchString("items." + s + ".name");
boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean("items." + s + ".glowing"); boolean glowing = FactionsPlugin.getInstance().getFileManager().getShop().fetchBoolean("items." + s + ".glowing");
List<String> lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".lore"); List<String> lore = FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".lore");
assert item != null;
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(FactionsPlugin.instance.color(name)); meta.setDisplayName(FactionsPlugin.instance.color(name));
meta.addItemFlags(); meta.addItemFlags();
@@ -64,23 +66,26 @@ public class ShopGUIFrame {
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
meta.addEnchant(Enchantment.DURABILITY, 1, true); meta.addEnchant(Enchantment.DURABILITY, 1, true);
} }
if (!glowing) meta.removeEnchant(Enchantment.DURABILITY); if (!glowing)
meta.removeEnchant(Enchantment.DURABILITY);
List<String> replacedLore = lore.stream().map(t -> t.replace("{cost}", cost + "")).collect(Collectors.toList()); List<String> replacedLore = lore.stream().map(t -> t.replace("{cost}", cost + "")).collect(Collectors.toList());
meta.setLore(FactionsPlugin.instance.colorList(replacedLore)); meta.setLore(FactionsPlugin.instance.colorList(replacedLore));
item.setItemMeta(meta); item.setItemMeta(meta);
GUIItems.set(slot, new GuiItem(item, e -> { GUIItems.set(slot, new GuiItem(item, e ->
{
e.setCancelled(true); e.setCancelled(true);
FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked());
if (fplayer.getFaction().getPoints() >= cost) { if (fplayer.getFaction().getPoints() >= cost) {
if (runCommands(FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".cmds"), fplayer.getPlayer())) {
fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost); fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost);
runCommands(FactionsPlugin.getInstance().getFileManager().getShop().fetchStringList("items." + s + ".cmds"), fplayer.getPlayer());
for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) { for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) {
fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString() fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString().replace("{player}", fplayer.getPlayer().getName()).replace("{item}", ChatColor.stripColor(FactionsPlugin.getInstance().color(name)))
.replace("{player}", fplayer.getPlayer().getName())
.replace("{item}", ChatColor.stripColor(FactionsPlugin.getInstance().color(name)))
.replace("{cost}", cost + "")); .replace("{cost}", cost + ""));
} }
buildGUI(fme); buildGUI(fme);
} else {
fplayer.msg(TL.SHOP_ERROR_DURING_PURCHASE);
}
} else { } else {
fplayer.msg(TL.SHOP_NOT_ENOUGH_POINTS); fplayer.msg(TL.SHOP_NOT_ENOUGH_POINTS);
} }
@@ -92,7 +97,6 @@ public class ShopGUIFrame {
} }
} }
private ItemStack buildDummyItem(Faction f) { private ItemStack buildDummyItem(Faction f) {
ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("F-Shop.GUI.dummy-item"); ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("F-Shop.GUI.dummy-item");
ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem(); ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).get().parseItem();
@@ -105,10 +109,83 @@ public class ShopGUIFrame {
return item; return item;
} }
public void runCommands(List<String> list, Player p) { public boolean checkShopConfig() {
boolean ret = true;
Set<String> items = FactionsPlugin.getInstance().getFileManager().getShop().getConfig().getConfigurationSection("items").getKeys(false);
for (String s : items) {
if (checkShopConfig(s) == false) {
ret = false;
}
}
return ret;
}
public boolean checkShopConfig(String s) {
boolean ret = true;
if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".slot")) {
FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing slot variable");
ret = false;
}
if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".block")) {
FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing block variable");
ret = false;
}
if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cmds")) {
FactionsPlugin.getInstance().log(Level.WARNING, "Problee with config item '" + s + "' missing cmds variable");
ret = false;
}
if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".cost")) {
FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing cost variable this item will cost 0");
}
if (!FactionsPlugin.getInstance().getFileManager().getShop().containsKey("items." + s + ".name")) {
FactionsPlugin.getInstance().log(Level.WARNING, "Problem with config item '" + s + "' missing name variable");
ret = false;
}
return ret;
}
/**
* @param list The list of commands to be ran.
* @param p The player that is using the shop
* @return if all commands are able to be ran or if they did run.
*/
public boolean runCommands(List<String> list, Player p) {
for (String cmd : list) {
cmd = cmd.replace("%player%", p.getName());
if (cmd.toLowerCase().startsWith("give")) {
String[] args = cmd.split(" ");
if (args.length == 4) {
Material material = Material.matchMaterial(args[2]);
int amount = Integer.parseInt(args[3]);
Player player = Bukkit.getPlayer(args[1]);
if (!player.isOnline()) {
return false;
}
// See if the player has this item in their inventory;
if (player.getInventory().contains(material) && player.getInventory().firstEmpty() < 0) {
int spacesAvailable = 0;
Map<Integer, ? extends ItemStack> contents = player.getInventory().all(material);
for (ItemStack stack : contents.values()) {
spacesAvailable += stack.getMaxStackSize() - stack.getAmount();
}
if (spacesAvailable < amount) {
return false;
}
} else {
if (player.getInventory().firstEmpty() < 0) {
return false;
}
}
}
}
}
for (String cmd : list) { for (String cmd : list) {
cmd = cmd.replace("%player%", p.getName()); cmd = cmd.replace("%player%", p.getName());
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd);
} }
return true;
} }
} }

View File

@@ -54,8 +54,10 @@ public enum Permission {
FLY_TRUCE("fly.truce"), FLY_TRUCE("fly.truce"),
FLY_NEUTRAL("fly.neutral"), FLY_NEUTRAL("fly.neutral"),
FOCUS("focus"), FOCUS("focus"),
FRIENDLYFIRE("friendlyfire"),
GLOBALCHAT("globalchat"), GLOBALCHAT("globalchat"),
GRACE("grace"), GRACE("grace"),
GRACETOGGLE("gracetoggle"),
HELP("help"), HELP("help"),
HOME("home"), HOME("home"),
INVITE("invite"), INVITE("invite"),
@@ -132,6 +134,7 @@ public enum Permission {
SCOREBOARD("scoreboard"), SCOREBOARD("scoreboard"),
SEECHUNK("seechunk"), SEECHUNK("seechunk"),
SETWARP("setwarp"), SETWARP("setwarp"),
SHIELD("shield"),
SHOP("shop"), SHOP("shop"),
TOP("top"), TOP("top"),
VIEWCHEST("viewchest"), VIEWCHEST("viewchest"),

View File

@@ -1,8 +1,8 @@
package com.massivecraft.factions.struct; package com.massivecraft.factions.struct;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.fperms.Permissable; import com.massivecraft.factions.zcore.fperms.Permissable;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;

View File

@@ -1,8 +1,8 @@
package com.massivecraft.factions.struct; package com.massivecraft.factions.struct;
import com.cryptomorin.xseries.XMaterial;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.fperms.Permissable; import com.massivecraft.factions.zcore.fperms.Permissable;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;

View File

@@ -149,10 +149,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

@@ -18,6 +18,7 @@ public enum FancyTag implements Tag {
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
NEUTRAL_LIST("{neutral-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.NEUTRAL)),
ALLIES_LIST("{allies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ALLY)), ALLIES_LIST("{allies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ALLY)),
ENEMIES_LIST("{enemies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ENEMY)), ENEMIES_LIST("{enemies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ENEMY)),
TRUCES_LIST("{truces-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.TRUCE)), TRUCES_LIST("{truces-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.TRUCE)),

View File

@@ -2,6 +2,7 @@ package com.massivecraft.factions.tag;
import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.timer.TimerManager;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -12,7 +13,7 @@ public enum GeneralTag implements Tag {
/** /**
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
GRACE_TIMER("{grace-time}", () -> String.valueOf(TimerManager.getRemaining(FactionsPlugin.getInstance().getTimerManager().graceTimer.getRemaining(), true))),
MAX_WARPS("{max-warps}", () -> String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5))), MAX_WARPS("{max-warps}", () -> String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5))),
MAX_ALLIES("{max-allies}", () -> getRelation("ally")), MAX_ALLIES("{max-allies}", () -> getRelation("ally")),
MAX_ENEMIES("{max-enemies}", () -> getRelation("enemy")), MAX_ENEMIES("{max-enemies}", () -> getRelation("enemy")),

View File

@@ -1,7 +1,6 @@
package com.massivecraft.factions.tag; package com.massivecraft.factions.tag;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.apache.commons.lang.time.DurationFormatUtils; import org.apache.commons.lang.time.DurationFormatUtils;
@@ -16,19 +15,13 @@ public enum PlayerTag implements Tag {
/** /**
* @author FactionsUUID Team * @author FactionsUUID Team
*/ */
GROUP("{group}", (fp) -> {
if (fp.isOnline()) {
return FactionsPlugin.getInstance().getPrimaryGroup(fp.getPlayer());
} else {
return "";
}
}),
LAST_SEEN("{lastSeen}", (fp) -> { LAST_SEEN("{lastSeen}", (fp) -> {
String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX;
return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized);
}), }),
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

@@ -5,6 +5,7 @@ import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.tag.FactionTag; import com.massivecraft.factions.tag.FactionTag;
import com.massivecraft.factions.tag.Tag; import com.massivecraft.factions.tag.Tag;
import com.massivecraft.factions.util.timer.TimerManager;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.clip.placeholderapi.expansion.Relational; import me.clip.placeholderapi.expansion.Relational;
@@ -13,10 +14,16 @@ 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.UUID; import java.util.UUID;
import java.util.logging.Level;
public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational { public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational {
private static void logInvalid(String placeholder) {
FactionsPlugin.getInstance().getLogger().log(Level.INFO, "Invalid request through PlaceholderAPI for placeholder '" + placeholder + "'");
}
// Identifier for this expansion // Identifier for this expansion
@Override @Override
public String getIdentifier() { public String getIdentifier() {
@@ -209,16 +216,41 @@ 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": case "grace_time":
return Conf.gracePeriod ? "Enabled" : "Disabled"; 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
return null; 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 TL.PLACEHOLDERAPI_NULL.toString();
}
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

@@ -0,0 +1,82 @@
package com.massivecraft.factions.util;
import com.massivecraft.factions.FactionsPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.Objects;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public class Config extends YamlConfiguration {
private String fileName;
private FactionsPlugin plugin;
public Config(FactionsPlugin plugin, String fileName) {
this(plugin, fileName, ".yml");
}
public Config(FactionsPlugin plugin, String fileName, String fileExtension) {
this.plugin = plugin;
this.fileName = fileName + (fileName.endsWith(fileExtension) ? "" : fileExtension);
this.createFile();
}
public String getFileName() {
return this.fileName;
}
public FactionsPlugin getPlugin() {
return this.plugin;
}
private void createFile() {
File folder = this.plugin.getDataFolder();
try {
File ex = new File(folder, this.fileName);
if (!ex.exists()) {
if (this.plugin.getResource(this.fileName) != null) {
this.plugin.saveResource(this.fileName, false);
} else {
this.save(ex);
}
} else {
this.load(ex);
this.save(ex);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void save() {
File folder = this.plugin.getDataFolder();
try {
this.save(new File(folder, this.fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Config)) {
return false;
}
Config config = (Config) o;
if (this.fileName != null) {
if (this.fileName.equals(config.fileName)) {
return Objects.equals(this.plugin, config.plugin);
}
} else if (config.fileName == null) {
return Objects.equals(this.plugin, config.plugin);
}
return false;
}
}

View File

@@ -0,0 +1,26 @@
package com.massivecraft.factions.util;
import com.massivecraft.factions.FactionsPlugin;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.concurrent.TimeUnit;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/6/2020
*/
public class Cooldown {
public static void setCooldown(Player player, String name, int seconds) {
player.setMetadata(name, new FixedMetadataValue(FactionsPlugin.getInstance(), System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds)));
}
public static boolean isOnCooldown(Player player, String name) {
if (!player.hasMetadata(name) || player.getMetadata(name).size() <= 0) return false;
long time = player.getMetadata(name).get(0).asLong();
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

@@ -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;
} }
} }

View File

@@ -5,7 +5,8 @@ package com.massivecraft.factions.util;
* All rights reserved 2020. * All rights reserved 2020.
* Creation Date: 4/4/2020 * Creation Date: 4/4/2020
*/ */
import com.massivecraft.factions.util.XMaterial;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.Location; import org.bukkit.Location;

View File

@@ -5,6 +5,7 @@ package com.massivecraft.factions.util;
* All rights reserved 2020. * All rights reserved 2020.
* Creation Date: 4/4/2020 * Creation Date: 4/4/2020
*/ */
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;

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);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
package com.massivecraft.factions.util.adapters;
import com.google.gson.*;
import com.massivecraft.factions.cmd.shields.struct.ShieldTCMP;
import com.massivecraft.factions.cmd.shields.struct.frame.ShieldFramePersistence;
import java.lang.reflect.Type;
/**
* Factions - Developed by ImCarib.
* All rights reserved 2020.
* Creation Date: 5/23/2020
*/
public class ShieldFrameAdapter implements JsonDeserializer<ShieldFramePersistence>, JsonSerializer<ShieldFramePersistence> {
public ShieldFramePersistence deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
JsonObject obj = json.getAsJsonObject();
int frame = obj.get("id").getAsInt();
return ShieldTCMP.getInstance().getByStart(frame);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public JsonElement serialize(ShieldFramePersistence src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
try {
obj.addProperty("id", src.getStartParsed());
return obj;
} catch (Exception ex) {
ex.printStackTrace();
return obj;
}
}
}

View File

@@ -0,0 +1,29 @@
package com.massivecraft.factions.util.timer;
import com.massivecraft.factions.Conf;
import org.apache.commons.lang.time.FastDateFormat;
import java.text.DecimalFormat;
import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public final class DateTimeFormats {
public static final TimeZone SERVER_TIME_ZONE = TimeZone.getTimeZone(Conf.serverTimeZone);
public static final ZoneId SERVER_ZONE_ID = SERVER_TIME_ZONE.toZoneId();
public static final FastDateFormat DAY_MTH_HR_MIN_SECS = FastDateFormat.getInstance("dd/MM HH:mm:ss", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat DAY_MTH_YR_HR_MIN_AMPM = FastDateFormat.getInstance("dd/MM/yy hh:mma", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat DAY_MTH_HR_MIN_AMPM = FastDateFormat.getInstance("dd/MM hh:mma", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat HR_MIN_AMPM = FastDateFormat.getInstance("hh:mma", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat HR_MIN_AMPM_TIMEZONE = FastDateFormat.getInstance("hh:mma z", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat HR_MIN = FastDateFormat.getInstance("hh:mm", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final FastDateFormat MIN_SECS = FastDateFormat.getInstance("mm:ss", SERVER_TIME_ZONE, Locale.ENGLISH);
public static final ThreadLocal<DecimalFormat> SECONDS = ThreadLocal.withInitial(() -> new DecimalFormat("0"));
public static final ThreadLocal<DecimalFormat> REMAINING_SECONDS = ThreadLocal.withInitial(() -> new DecimalFormat("0.#"));
public static final ThreadLocal<DecimalFormat> REMAINING_SECONDS_TRAILING = ThreadLocal.withInitial(() -> new DecimalFormat("0.0"));
}

View File

@@ -0,0 +1,67 @@
package com.massivecraft.factions.util.timer;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public abstract class GlobalTimer extends Timer {
private TimerRunnable runnable;
public GlobalTimer(String name, long defaultCooldown) {
super(name, defaultCooldown);
}
public boolean clearCooldown() {
if (this.runnable != null) {
this.runnable.cancel();
this.runnable = null;
return true;
}
return false;
}
public boolean isPaused() {
return (this.runnable != null) && (this.runnable.isPaused());
}
public void setPaused(boolean paused) {
if ((this.runnable != null) && (this.runnable.isPaused() != paused)) {
this.runnable.setPaused(paused);
}
}
public long getRemaining() {
return this.runnable == null ? 0L : this.runnable.getRemaining();
}
public long getRemaining(long now) {
return this.runnable == null ? 0L : this.runnable.getRemaining(now);
}
public boolean setRemaining() {
return setRemaining(this.defaultCooldown, false);
}
public boolean setRemaining(long duration, boolean overwrite) {
boolean hadCooldown = false;
if (this.runnable != null) {
if (!overwrite) {
return false;
}
hadCooldown = this.runnable.getRemaining() > 0L;
this.runnable.setRemaining(duration);
} else {
this.runnable = new TimerRunnable(this, duration);
}
return !hadCooldown;
}
}

View File

@@ -0,0 +1,30 @@
package com.massivecraft.factions.util.timer;
import com.massivecraft.factions.util.Config;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public abstract class Timer {
public final long defaultCooldown;
protected final String name;
public Timer(String name, long defaultCooldown) {
this.name = name;
this.defaultCooldown = defaultCooldown;
}
public String getName() {
return this.name;
}
public void load(Config config) {
}
public void save(Config config) {
}
}

View File

@@ -0,0 +1,86 @@
package com.massivecraft.factions.util.timer;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.util.Config;
import com.massivecraft.factions.util.timer.type.GraceTimer;
import org.apache.commons.lang.time.DurationFormatUtils;
import org.bukkit.event.Listener;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public class TimerManager implements Listener, Runnable {
private static final long MINUTE = TimeUnit.MINUTES.toMillis(1L);
private static final long HOUR = TimeUnit.HOURS.toMillis(1L);
private static final long MULTI_HOUR = TimeUnit.HOURS.toMillis(10);
private final Set<Timer> timers;
private final FactionsPlugin plugin;
private final List<TimerRunnable> timerRunnableList = new ArrayList<>();
public GraceTimer graceTimer;
private Config config;
public TimerManager(FactionsPlugin plugin) {
this.timers = new HashSet<>();
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
if (Conf.useGraceSystem) {
this.registerTimer(this.graceTimer = new GraceTimer());
}
plugin.getServer().getScheduler().runTaskTimer(plugin, this, 4, 4);
}
public static String getRemaining(long millis, boolean milliseconds) {
return getRemaining(millis, milliseconds, true);
}
public static String getRemaining(long duration, boolean milliseconds, boolean trail) {
if ((milliseconds) && (duration < MINUTE)) {
return ((trail ? DateTimeFormats.REMAINING_SECONDS_TRAILING : DateTimeFormats.REMAINING_SECONDS).get()).format(duration * 0.001D) + 's';
}
return DurationFormatUtils.formatDuration(duration, (duration >= HOUR ? (duration >= MULTI_HOUR ? "d" : "") + "d:" : "") + "HH:mm:ss");
}
public Collection<Timer> getTimers() {
return this.timers;
}
public void registerTimer(Timer timer) {
this.timers.add(timer);
if (timer instanceof Listener) {
this.plugin.getServer().getPluginManager().registerEvents((Listener) timer, this.plugin);
}
}
public void unregisterTimer(Timer timer) {
this.timers.remove(timer);
}
public void reloadTimerData() {
this.config = new Config(this.plugin, "timers");
for (Timer timer : this.timers) {
timer.load(this.config);
}
}
public void saveTimerData() {
for (Timer timer : this.timers) {
timer.save(this.config);
}
this.config.save();
}
public void run() {
long now = System.currentTimeMillis();
timerRunnableList.removeIf(next -> next.check(now));
}
public List<TimerRunnable> getTimerRunnableList() {
return timerRunnableList;
}
}

View File

@@ -0,0 +1,115 @@
package com.massivecraft.factions.util.timer;
import com.massivecraft.factions.FactionsPlugin;
import java.util.UUID;
/**
* Factions - Developed by Driftay.
* All rights reserved 2020.
* Creation Date: 4/7/2020
*/
public class TimerRunnable {
private final Timer timer;
private long expiryMillis;
private long pauseMillis;
private boolean cancelled = false;
public TimerRunnable(Timer timer, long duration) {
this.timer = timer;
setRemaining(duration);
FactionsPlugin plugin = FactionsPlugin.getInstance();
plugin.getTimerManager().getTimerRunnableList().add(this);
}
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() {
return cancelled;
}
public Timer getTimer() {
return this.timer;
}
public long getRemaining() {
return getRemaining(false);
}
public void setRemaining(long remaining) {
setExpiryMillis(remaining);
}
public long getRemaining(long now) {
return getRemaining(false, now);
}
public long getRemaining(boolean ignorePaused) {
if ((!ignorePaused) && (this.pauseMillis != 0L)) return this.pauseMillis;
return this.expiryMillis - System.currentTimeMillis();
}
public long getRemaining(boolean ignorePaused, long now) {
if ((!ignorePaused) && (this.pauseMillis != 0L)) return this.pauseMillis;
return this.expiryMillis - now;
}
public long getExpiryMillis() {
return this.expiryMillis;
}
private void setExpiryMillis(long remainingMillis) {
long expiryMillis = System.currentTimeMillis() + remainingMillis;
if (expiryMillis == this.expiryMillis) return;
this.expiryMillis = expiryMillis;
}
public boolean check(long now) {
if (cancelled) return true;
return getRemaining(false, now) <= 0;
}
public long getPauseMillis() {
return this.pauseMillis;
}
public void setPauseMillis(long pauseMillis) {
this.pauseMillis = pauseMillis;
}
public boolean isPaused() {
return this.pauseMillis != 0L;
}
public void setPaused(boolean paused) {
if (paused == isPaused()) return;
if (paused) {
this.pauseMillis = getRemaining(true);
cancel();
} else {
setExpiryMillis(this.pauseMillis);
this.pauseMillis = 0L;
}
}
public void cancel() {
cancelled = true;
}
}

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