Compare commits

...

46 Commits

Author SHA1 Message Date
YouHaveTrouble 42f8f92a6a added -pre suffix to the plugin version to indicate it's not yet production ready 2024-04-16 17:41:48 +02:00
YouHaveTrouble d3e8b590cb folia scheduling part MXIV 2024-04-16 17:24:10 +02:00
YouHaveTrouble 88917d65c3 actually save changes to sqlite lol 2024-04-16 17:23:51 +02:00
YouHaveTrouble 4096cfe152 more folia support shenanigans 2024-04-16 16:46:52 +02:00
YouHaveTrouble 7f74826e2c Add return statement after plugin disablement
Added a return statement after the plugin disablement step in the PreventStabby main class. This ensures that the execution of the function is explicitly stopped if there are any issues with command registration.
2024-04-16 16:29:43 +02:00
YouHaveTrouble c369c110e5 possible workaround for folia compatibility 2024-04-16 16:29:26 +02:00
YouHaveTrouble 375ef3de4e Update worldguard-bukkit dependency version
The version of the "worldguard-bukkit" dependency in the pom.xml has been updated from 7.0.4-SNAPSHOT to 7.0.9-SNAPSHOT. This upgrade ensures the project is using the latest and possibly more stable or feature-rich version of the dependency.
2024-04-07 16:29:38 +02:00
YouHaveTrouble 292b7b1b77 Add block stopper to PreventStabby configuration and listeners
A block stopper feature has been added to the PreventStabby plugin. This prevents the placement of dangerous blocks near players with PvP turned off. The functionality has been integrated into the ConfigCache configuration class and EnvironmentalListener. This fine-tunes environmental controls in PvP gameplay scenarios, improving the player's safety and the overall game experience.
2024-03-04 20:56:31 +01:00
YouHaveTrouble 47ade3e0c0 Refactor PreventStabby plugin to enhance PvP and environment controls
Reconfiguration of the PreventStabby plugin involved removal of PlayerDamageListener and the introduction of two new listeners: EnvironmentalListener and PvpListener. This restructuring allows more efficient management of entity damage and environmental interactions. EnvironmentalListener specifically caters for dangerous situations such as bucket spills and block fires. PvpListener effectively manages PvP related activities including damages, splash potion effects, cloud area effects, and fishing events ensuring a more streamlined control and response for better PvP gameplay.
2024-03-04 18:24:22 +01:00
YouHaveTrouble 7d8d27b1ef Replace PlayerDamageListener with EnvironmentalListener and PvpListener
Removed PlayerDamageListener and introduced two new listeners, EnvironmentalListener and PvpListener to manage entity damage. EnvironmentalListener prevents dangerous bucket dumps and block ignitions. PvpListener handles entity damages, potion splash events, area effect cloud applications and fishing events, all with distinct conditions and responses for better PvP management.
2024-03-03 14:52:49 +01:00
YouHaveTrouble 096599081b Improve exception handling and PvP process in DatabaseSQLite and PlayerManager
Refactored exception handling in DatabaseSQLite to use logger instead of printStackTrace() for better error tracking. Streamlined player PvP process in PlayerManager with clear conditions and appropriate responses. Enhancements in other classes were also made to ensure smooth execution and maintain code standards.
2024-03-02 16:57:32 +01:00
YouHaveTrouble 7b155d0b3e Add UtilListener to track player interactions with entities
The UtilListener class has been added to the project. It provides various event handlers which tag entities (such as ExplosiveMinecart, TNTPrimed, EnderCrystal) with the UUID of the player who either placed, nudged, primed or hit the entity. Changes have also been made to the Target class, adding methods for getting and assigning a player source ID for entities.
2024-03-02 00:40:35 +01:00
YouHaveTrouble 58a4a9f25d combat tracking is working again! 2024-02-28 20:09:56 +01:00
YouHaveTrouble 3c7904786e Implement SQL database and refactor onEnable method
In this commit, an SQLite database is set up in the onEnable method of the PreventStabby class, which will be used to store plugin data. To facilitate this, java.io.File is being imported. By doing this, we ensure that the database file exists and is connected to as soon as the plugin is enabled.
2024-02-24 19:36:55 +01:00
YouHaveTrouble 1aeb245666 Refactor damage source checking and restructure player management
The source of damage detection for PvP interactions has been updated to improve accuracy and flexibility. A 'Target' sub-class has been implemented in the PlayerManager class, removing the need for a separate DamageCheck class. The PlayerManager class was also moved to the 'data' package. Distribution of feedback messages has been simplified using the new DamageCheckResult class.
2024-02-24 19:23:54 +01:00
YouHaveTrouble b9e2aefc40 Remove several game listeners and utility files
The commit includes the deletion of several listeners and utility files. These were mainly related to handling specific game events such as interactions with lava and fireworks, combat commands, and actions related to player pets and mounts. The removal is due to refactoring damage source check system
2024-02-14 20:22:07 +01:00
YouHaveTrouble 8df1fe54e4 Remove redundant SmartCache and refactor related classes
The SmartCache class has been removed, and logic within it has been moved to relevant classes to reduce redundancy. This involved utilizing the PlayerManager for player data, instead of invalidating a separate cache in the now-removed SmartCache. Other classes that interacted with SmartCache, such as API, listeners and PreventStabby, have been updated to use the newly refactored system.
2024-01-11 00:44:58 +01:00
YouHaveTrouble b414f96257 new shared logic to determine attacker and victim 2023-06-23 00:28:44 +02:00
YouHaveTrouble c11c455c53 use util for harmful effects list 2023-06-22 19:06:15 +02:00
YouHaveTrouble d859fd0aaa refactors, code style fixes, rpeventing events from firing when not needed 2023-06-22 18:41:16 +02:00
YouHaveTrouble 3919b0f44b use logger, use try with resources 2023-06-22 16:45:31 +02:00
YouHaveTrouble 0290629d27 relocate into me.youhavetrouble.preventstabby to avoid conflicts 2023-06-22 16:20:39 +02:00
YouHaveTrouble 4590b1d532 only fire PlayerEnterCombatEvent if there are registered listeners for it 2023-06-22 16:02:34 +02:00
YouHaveTrouble 8ae6e9212c actually check for empty string and not for null 2023-06-22 15:36:08 +02:00
YouHaveTrouble fec1dd2ab6 bump version 2023-06-22 15:32:09 +02:00
YouHaveTrouble fba2f03aab don't send messages or action bars if the message content is empty 2023-06-22 15:28:41 +02:00
YouHaveTrouble e30437694c bump version 2023-05-23 00:09:14 +02:00
YouHaveTrouble 8fcf34e310 more fixes for #15 2023-05-20 12:06:16 +02:00
YouHaveTrouble aac1f99374 potential fix for #15 2023-05-20 00:09:02 +02:00
YouHaveTrouble 7f1da79444 bump version 2023-05-03 21:49:15 +02:00
YouHaveTrouble 244ceb4dcc don't send the message if tempting was cancelled 2023-05-03 21:29:07 +02:00
YouHaveTrouble ac1cafe0d9 tempting horses should not cause player to enter combat 2023-05-03 21:26:38 +02:00
YouHaveTrouble b3ce1913fd add placeholder for forced pvp state 2023-05-03 19:18:02 +02:00
YouHaveTrouble 9a707b34a3 bump version 2023-03-26 03:17:46 +02:00
YouHaveTrouble d52648b4ff Merge pull request #13 from YouHaveTrouble/api-changes
Api changes + worldguard flag fix for 1.19.4
2023-03-26 03:15:42 +02:00
YouHaveTrouble 7d2c41646e make worldguard hook register on load 2023-03-26 03:09:07 +02:00
YouHaveTrouble 61908b8fab more api changes and javadocs 2022-12-31 17:09:20 +01:00
YouHaveTrouble 5abf99cd6c semi-major api changes, javadocs 2022-12-31 16:44:50 +01:00
YouHaveTrouble 3c014304ba implement PlayerTogglePvpEvent 2022-12-31 15:58:06 +01:00
YouHaveTrouble b361681600 bump version 2022-12-31 15:03:15 +01:00
YouHaveTrouble 7ada9eab29 permission for help command 2022-12-31 15:03:09 +01:00
YouHaveTrouble 78504ee097 command without arguments now acts as toggle subcommand 2022-12-31 14:43:44 +01:00
YouHaveTrouble 7da6ff0ac9 placeholder for pvp state and offline player fallbacks to not cause sync db calls 2022-12-31 13:46:01 +01:00
YouHaveTrouble c83888837b fix dependency issues on older server versions 2022-12-04 22:26:45 +01:00
YouHaveTrouble 4052afe4d3 version bump 2022-08-07 12:13:15 +02:00
YouHaveTrouble 93efa37e77 flip the conditional 2022-08-07 11:59:22 +02:00
66 changed files with 1519 additions and 2609 deletions
+12 -62
View File
@@ -6,14 +6,14 @@
<groupId>me.youhavetrouble</groupId> <groupId>me.youhavetrouble</groupId>
<artifactId>PreventStabby</artifactId> <artifactId>PreventStabby</artifactId>
<version>1.7.0</version> <version>2.0.0-pre-1</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>PreventStabby</name> <name>PreventStabby</name>
<description>Stop people from getting stabbed!</description> <description>Stop people from getting stabbed!</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
@@ -31,7 +31,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version> <version>3.3.0</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
@@ -41,13 +41,9 @@
<configuration> <configuration>
<createDependencyReducedPom>false</createDependencyReducedPom> <createDependencyReducedPom>false</createDependencyReducedPom>
<relocations> <relocations>
<relocation>
<pattern>io.github.thatsmusic99</pattern>
<shadedPattern>configurationmaster</shadedPattern>
</relocation>
<relocation> <relocation>
<pattern>org.bstats</pattern> <pattern>org.bstats</pattern>
<shadedPattern>bstats</shadedPattern> <shadedPattern>me.youhavetrouble.preventstabby.bstats</shadedPattern>
</relocation> </relocation>
</relocations> </relocations>
</configuration> </configuration>
@@ -65,16 +61,8 @@
<repositories> <repositories>
<repository> <repository>
<id>spigotmc-repo</id> <id>papermc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
<repository>
<id>bs-repo</id>
<url>https://ci.pluginwiki.us/plugin/repository/everything/</url>
</repository> </repository>
<repository> <repository>
<id>sk89q-repo</id> <id>sk89q-repo</id>
@@ -88,37 +76,22 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>io.papermc.paper</groupId>
<artifactId>spigot-api</artifactId> <artifactId>paper-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version> <version>1.20.4-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
<dependency>
<groupId>com.github.thatsmusic99</groupId>
<artifactId>ConfigurationMaster</artifactId>
<version>v1.0.3</version>
</dependency>
<dependency> <dependency>
<groupId>org.bstats</groupId> <groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId> <artifactId>bstats-bukkit</artifactId>
<version>3.0.0</version> <version>3.0.2</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q.worldguard</groupId> <groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId> <artifactId>worldguard-bukkit</artifactId>
<version>7.0.4-SNAPSHOT</version> <version>7.0.9-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -127,28 +100,5 @@
<version>2.11.1</version> <version>2.11.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-platform-bukkit</artifactId>
<version>4.1.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-minimessage</artifactId>
<version>4.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-serializer-legacy</artifactId>
<version>4.11.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -2,68 +2,43 @@ package me.youhavetrouble.preventstabby;
import me.youhavetrouble.preventstabby.commands.MainCommand; import me.youhavetrouble.preventstabby.commands.MainCommand;
import me.youhavetrouble.preventstabby.config.ConfigCache; import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.hooks.PlacoholderApiHook; import me.youhavetrouble.preventstabby.hooks.PlaceholderApiHook;
import me.youhavetrouble.preventstabby.hooks.WorldGuardHook; import me.youhavetrouble.preventstabby.hooks.WorldGuardHook;
import me.youhavetrouble.preventstabby.players.PlayerManager; import me.youhavetrouble.preventstabby.data.PlayerListener;
import me.youhavetrouble.preventstabby.players.SmartCache; import me.youhavetrouble.preventstabby.data.PlayerManager;
import me.youhavetrouble.preventstabby.util.PluginMessages; import me.youhavetrouble.preventstabby.listeners.EnvironmentalListener;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.listeners.PvpListener;
import me.youhavetrouble.preventstabby.util.DatabaseSQLite; import me.youhavetrouble.preventstabby.listeners.UtilListener;
import lombok.Getter; import me.youhavetrouble.preventstabby.util.*;
import me.youhavetrouble.preventstabby.util.Util;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.reflections.Reflections;
import java.io.File; import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
public final class PreventStabby extends JavaPlugin { public final class PreventStabby extends JavaPlugin {
@Getter private static PreventStabby plugin; private static PreventStabby plugin;
private ConfigCache configCache; private ConfigCache configCache;
private PlayerManager playerManager; private PlayerManager playerManager;
private DatabaseSQLite sqLite; private DatabaseSQLite sqLite;
private SmartCache smartCache;
private static boolean worldGuardHook; private static boolean worldGuardHook;
private static BukkitAudiences adventure;
@Override @Override
public void onEnable() { public void onEnable() {
plugin = this; plugin = this;
Util.initData();
reloadPluginConfig(); reloadPluginConfig();
File dbFile = new File("plugins/PreventStabby"); File dbFile = new File("plugins/PreventStabby");
sqLite = new DatabaseSQLite("jdbc:sqlite:plugins/PreventStabby/database.db", dbFile); sqLite = new DatabaseSQLite("jdbc:sqlite:plugins/PreventStabby/database.db", dbFile, getLogger());
sqLite.createDatabaseFile(); playerManager = new PlayerManager(this);
if (!sqLite.testConnection()) {
getLogger().severe("Error with accessing database. Check if server has write rights.");
getLogger().severe("Plugin will now disable.");
getServer().getPluginManager().disablePlugin(this);
return;
}
adventure = BukkitAudiences.create(this);
playerManager = new PlayerManager();
smartCache = new SmartCache();
smartCache.runSmartCache();
// Register listeners // Register listeners
Reflections reflections = new Reflections((Object[]) new String[]{"me.youhavetrouble.preventstabby"}); getServer().getPluginManager().registerEvents(new UtilListener(), this);
Set<Class<?>> listenerClasses = reflections.getTypesAnnotatedWith(PreventStabbyListener.class); getServer().getPluginManager().registerEvents(new PlayerListener(), this);
listenerClasses.forEach((listener)-> { getServer().getPluginManager().registerEvents(new EnvironmentalListener(this), this);
try {
getServer().getPluginManager().registerEvents((org.bukkit.event.Listener) listener.getConstructor().newInstance(), this); getServer().getPluginManager().registerEvents(new PvpListener(this), this);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
getLogger().severe("Error with registering listeners.");
getLogger().severe("Plugin will now disable.");
getServer().getPluginManager().disablePlugin(this);
}
});
// Register command // Register command
PluginCommand pvpCommand = getCommand("pvp"); PluginCommand pvpCommand = getCommand("pvp");
@@ -71,35 +46,41 @@ public final class PreventStabby extends JavaPlugin {
getLogger().severe("Error with registering commands."); getLogger().severe("Error with registering commands.");
getLogger().severe("Plugin will now disable."); getLogger().severe("Plugin will now disable.");
getServer().getPluginManager().disablePlugin(this); getServer().getPluginManager().disablePlugin(this);
return;
} }
MainCommand mainCommand = new MainCommand(); MainCommand mainCommand = new MainCommand();
pvpCommand.setExecutor(mainCommand); pvpCommand.setExecutor(mainCommand);
pvpCommand.setTabCompleter(mainCommand); pvpCommand.setTabCompleter(mainCommand);
try {
WorldGuardHook.init();
worldGuardHook = true;
} catch (NoClassDefFoundError e) {
worldGuardHook = false;
}
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PlacoholderApiHook(this).register(); new PlaceholderApiHook(this).register();
} }
Metrics metrics = new Metrics(this, 14074); Metrics metrics = new Metrics(this, 14074);
} }
@Override
public void onLoad() {
if (getServer().getPluginManager().getPlugin("WorldGuard") != null) {
try {
WorldGuardHook.init();
worldGuardHook = true;
} catch (NoClassDefFoundError e) {
worldGuardHook = false;
}
}
}
public static boolean worldGuardHookEnabled() { public static boolean worldGuardHookEnabled() {
return worldGuardHook; return worldGuardHook;
} }
public void reloadPluginConfig() { public void reloadPluginConfig() {
configCache = new ConfigCache(); configCache = new ConfigCache(this);
} }
public void reloadPluginConfig(CommandSender commandSender) { public void reloadPluginConfig(CommandSender commandSender) {
getServer().getScheduler().runTaskAsynchronously(this, () -> { getServer().getAsyncScheduler().runNow(this, (task) -> {
reloadPluginConfig(); reloadPluginConfig();
PluginMessages.sendMessage(commandSender, "PreventStabby configuration reloaded."); PluginMessages.sendMessage(commandSender, "PreventStabby configuration reloaded.");
}); });
@@ -115,11 +96,8 @@ public final class PreventStabby extends JavaPlugin {
public DatabaseSQLite getSqLite() {return sqLite;} public DatabaseSQLite getSqLite() {return sqLite;}
public SmartCache getSmartCache() { public static PreventStabby getPlugin() {
return smartCache; return plugin;
} }
public static BukkitAudiences getAudiences() {
return adventure;
}
} }
@@ -1,147 +1,12 @@
package me.youhavetrouble.preventstabby.api; package me.youhavetrouble.preventstabby.api;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer; import me.youhavetrouble.preventstabby.data.DamageCheckResult;
import me.youhavetrouble.preventstabby.util.PvpState; import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.entity.Player; import org.bukkit.entity.Entity;
import javax.annotation.Nullable;
import java.util.UUID;
public class PreventStabbyAPI { public class PreventStabbyAPI {
/**
* Sets players PvP state. This will always save to database.
* @param player Player to set pvp state to
* @param newState State to set
*/
public static void setPvpEnabled(Player player, boolean newState) {
PreventStabby.getPlugin().getSmartCache().setPlayerPvpState(player.getUniqueId(), newState);
}
/**
* Sets players PvP state. This will always save to database.
* @param uuid UUID of player to set pvp state to
* @param newState State to set
*/
public static void setPvpEnabled(UUID uuid, boolean newState) {
PreventStabby.getPlugin().getSmartCache().setPlayerPvpState(uuid, newState);
}
/**
* Gets player's PvP state. If player is not cached this will query the database.
* @param uuid UUID of the player to get data from.
* @return True if enabled, false if disabled
*/
public static boolean getPvpEnabled(UUID uuid) {
return PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).isPvpEnabled();
}
/**
* Gets player's PvP state. If player is not cached this will query the database.
* @param player Player to get data from.
* @return True if enabled, false if disabled
*/
public static boolean getPvpEnabled(Player player) {
return PreventStabby.getPlugin().getSmartCache().getPlayerData(player.getUniqueId()).isPvpEnabled();
}
/**
* Checks if player can be damaged by another. Providing UUID of entity other than player may result in exceptions
* @param attackerUuid Attacker's UUID
* @param victimUuid Victim's UUID
* @param sendDenyMessage True if check should send deny message to attacker
* @return True if victim can be attacked by attacker, false if not
*/
public static boolean canDamage(UUID attackerUuid, UUID victimUuid, boolean sendDenyMessage) {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attackerUuid, victimUuid, sendDenyMessage);
}
/**
* Checks if player can be damaged by another.
* @param attacker Attacker
* @param victim Victim
* @param sendDenyMessage True if check should send deny message to attacker
* @return True if victim can be attacked by attacker, false if not
*/
public static boolean canDamage(Player attacker, Player victim, boolean sendDenyMessage) {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attacker.getUniqueId(), victim.getUniqueId(), sendDenyMessage);
}
/**
* Checks if player can be damaged by another. Providing UUID of entity other than player may result in exceptions
* @param attackerUuid Attacker's UUID
* @param victimUuid Victim's UUID
* @return True if victim can be attacked by attacker, false if not
*/
public static boolean canDamage(UUID attackerUuid, UUID victimUuid) {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attackerUuid, victimUuid, false);
}
/**
* Checks if player can be damaged by another.
* @param attacker Attacker
* @param victim Victim
* @return True if victim can be attacked by attacker, false if not
*/
public static boolean canDamage(Player attacker, Player victim) {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attacker.getUniqueId(), victim.getUniqueId(), false);
}
/**
* Checks if player has login protection.
* @param uuid UUID of player to check
* @return True if player has login protection, false if not
*/
public static boolean hasLoginProtection(UUID uuid) {
return PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(uuid);
}
/**
* Checks if player has teleport protection.
* @param player Player to check
* @return True if player has teleport protection, false if not
*/
public static boolean hasTeleportProtection(Player player) {
return PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(player.getUniqueId());
}
/**
* Checks if player has teleport protection.
* @param uuid UUID of player to check
* @return True if player has teleport protection, false if not
*/
public static boolean hasTeleportProtection(UUID uuid) {
return PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(uuid);
}
/**
* Checks if player has login protection.
* @param player Player to check
* @return True if player has login protection, false if not
*/
public static boolean hasLoginProtection(Player player) {
return PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(player.getUniqueId());
}
/**
* Checks if player is in combat.
* @param uuid UUID of player to check
* @return True if player is in combat, false if they are not or if they are offline
*/
public static boolean isInCombat(UUID uuid) {
return CombatTimer.isInCombat(uuid);
}
/**
* Checks if player is in combat.
* @param player Player to check
* @return True if player is in combat, false if they are not or if they are offline
*/
public static boolean isInCombat(Player player) {
return CombatTimer.isInCombat(player.getUniqueId());
}
/** /**
* @return Current state of forced PvP * @return Current state of forced PvP
*/ */
@@ -156,5 +21,9 @@ public class PreventStabbyAPI {
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(newForcedPvpState); PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(newForcedPvpState);
} }
public static DamageCheckResult canDamage(Entity attacker, Entity victim) {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attacker, victim);
}
} }
@@ -1,7 +1,7 @@
package me.youhavetrouble.preventstabby.api.event; package me.youhavetrouble.preventstabby.api.event;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData; import me.youhavetrouble.preventstabby.data.PlayerData;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
@@ -45,4 +45,9 @@ public class PlayerEnterCombatEvent extends Event implements Cancellable {
public HandlerList getHandlers() { public HandlerList getHandlers() {
return HANDLERS; return HANDLERS;
} }
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
} }
@@ -1,7 +1,7 @@
package me.youhavetrouble.preventstabby.api.event; package me.youhavetrouble.preventstabby.api.event;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData; import me.youhavetrouble.preventstabby.data.PlayerData;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
@@ -45,4 +45,10 @@ public class PlayerLeaveCombatEvent extends Event implements Cancellable {
public HandlerList getHandlers() { public HandlerList getHandlers() {
return HANDLERS; return HANDLERS;
} }
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
} }
@@ -1,42 +1,55 @@
package me.youhavetrouble.preventstabby.api.event; package me.youhavetrouble.preventstabby.api.event;
import org.bukkit.entity.Player; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.data.PlayerData;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* NOT IMPLEMENTED YET * Fired when player gets their personal pvp state toggled.
*/ */
@Deprecated
public class PlayerTogglePvpEvent extends Event { public class PlayerTogglePvpEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList(); private static final HandlerList HANDLERS = new HandlerList();
private final Player player; private final OfflinePlayer player;
private boolean newState, sendMessage; private final boolean newState;
private boolean sendMessage;
public PlayerTogglePvpEvent(Player player, boolean newState, boolean sendMessage) { public PlayerTogglePvpEvent(OfflinePlayer player, boolean newState, boolean sendMessage) {
this.player = player; this.player = player;
this.newState = newState; this.newState = newState;
this.sendMessage = sendMessage; this.sendMessage = sendMessage;
} }
public Player getPlayer() { public OfflinePlayer getPlayer() {
return player; return player;
} }
public PlayerData getPlayerData() {
return PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
}
/**
* Returns the state player's pvp state was toggled to.
* @return The state player's pvp state was toggled to.
*/
public boolean newState() { public boolean newState() {
return newState; return newState;
} }
public void setNewState(boolean newState) { /**
this.newState = newState; * Returns true if the state message will be sent to the player, false otherwise
} * @return True if the state message will be sent to the player, false otherwise
*/
public boolean isSendMessage() { public boolean isSendMessage() {
return sendMessage; return sendMessage;
} }
/**
* If this is true at the end of event pipeline, message with the current state will be sent to player.
*/
public void setSendMessage(boolean sendMessage) { public void setSendMessage(boolean sendMessage) {
this.sendMessage = sendMessage; this.sendMessage = sendMessage;
} }
@@ -46,4 +59,10 @@ public class PlayerTogglePvpEvent extends Event {
public HandlerList getHandlers() { public HandlerList getHandlers() {
return HANDLERS; return HANDLERS;
} }
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
} }
@@ -11,9 +11,9 @@ import java.util.Locale;
public class GlobalToggleCommand { public class GlobalToggleCommand {
public static void globalToggle(CommandSender sender, String[] args) { public static void globalToggle(CommandSender sender, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getAsyncScheduler().runNow(PreventStabby.getPlugin(), (task) -> {
if (!PreventStabbyPermission.COMMAND_GLOBAL_TOGGLE.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_GLOBAL_TOGGLE.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
@@ -27,15 +27,15 @@ public class GlobalToggleCommand {
switch (pvpState) { switch (pvpState) {
case ENABLED: case ENABLED:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.ENABLED); PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.ENABLED);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_on()); PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().force_pvp_on);
break; break;
case DISABLED: case DISABLED:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.DISABLED); PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.DISABLED);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_off()); PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().force_pvp_off);
break; break;
case NONE: case NONE:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.NONE); PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.NONE);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_none()); PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().force_pvp_none);
break; break;
default: default:
PluginMessages.sendMessage(sender, "Try /pvp override <enabled/disabled/none>"); PluginMessages.sendMessage(sender, "Try /pvp override <enabled/disabled/none>");
@@ -3,14 +3,19 @@ package me.youhavetrouble.preventstabby.commands;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.PreventStabbyPermission; import me.youhavetrouble.preventstabby.config.PreventStabbyPermission;
import me.youhavetrouble.preventstabby.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class HelpCommand { public class HelpCommand {
public static void help(CommandSender sender, String[] args) { public static void help(CommandSender sender, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getAsyncScheduler().runNow(PreventStabby.getPlugin(), (task) -> {
if (!PreventStabbyPermission.COMMAND_HELP.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return;
}
Component helpComponent = PluginMessages.MINIMESSAGE Component helpComponent = PluginMessages.MINIMESSAGE
.deserialize("<aqua><strikethrough> </strikethrough> PreventStabby Help <strikethrough> </strikethrough>") .deserialize("<aqua><strikethrough> </strikethrough> PreventStabby Help <strikethrough> </strikethrough>")
.append(Component.newline()) .append(Component.newline())
@@ -23,7 +28,7 @@ public class HelpCommand {
.append(Component.newline()) .append(Component.newline())
.append(PluginMessages.MINIMESSAGE.deserialize("<blue>/pvp <aqua><bold>toggle</bold> <white>- toggles PvP status")); .append(PluginMessages.MINIMESSAGE.deserialize("<blue>/pvp <aqua><bold>toggle</bold> <white>- toggles PvP status"));
} }
PreventStabby.getAudiences().sender(sender).sendMessage(helpComponent, MessageType.SYSTEM); sender.sendMessage(helpComponent);
}); });
} }
@@ -20,7 +20,7 @@ public class MainCommand implements TabExecutor {
private final HashMap<String, PreventStabbyPermission> subCommands = new HashMap<>(); private final HashMap<String, PreventStabbyPermission> subCommands = new HashMap<>();
public MainCommand() { public MainCommand() {
subCommands.put("help", PreventStabbyPermission.COMMAND); subCommands.put("help", PreventStabbyPermission.COMMAND_HELP);
subCommands.put("toggle", PreventStabbyPermission.COMMAND_TOGGLE); subCommands.put("toggle", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("on", PreventStabbyPermission.COMMAND_TOGGLE); subCommands.put("on", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("enable", PreventStabbyPermission.COMMAND_TOGGLE); subCommands.put("enable", PreventStabbyPermission.COMMAND_TOGGLE);
@@ -33,37 +33,38 @@ public class MainCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("preventstabby.command")) { if (!sender.hasPermission("preventstabby.command")) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return true; return true;
} }
if (args.length >= 1) { if (args.length == 0) {
switch (args[0].toLowerCase()) { PvpToggleCommand.toggle(sender, args);
case "help": return true;
HelpCommand.help(sender, args); }
break;
case "toggle": switch (args[0].toLowerCase()) {
PvpToggleCommand.toggle(sender, args); case "help":
break; HelpCommand.help(sender, args);
case "on": break;
case "enable": case "toggle":
PvpToggleCommand.enable(sender, args); PvpToggleCommand.toggle(sender, args);
break; break;
case "off": case "on":
case "disable": case "enable":
PvpToggleCommand.disable(sender, args); PvpToggleCommand.enable(sender, args);
break; break;
case "reload": case "off":
ReloadCommand.reload(sender); case "disable":
break; PvpToggleCommand.disable(sender, args);
case "override": break;
GlobalToggleCommand.globalToggle(sender, args); case "reload":
break; ReloadCommand.reload(sender);
default: break;
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_such_command()); case "override":
break; GlobalToggleCommand.globalToggle(sender, args);
} break;
} else { default:
HelpCommand.help(sender, args); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_such_command);
break;
} }
return true; return true;
} }
@@ -1,8 +1,9 @@
package me.youhavetrouble.preventstabby.commands; package me.youhavetrouble.preventstabby.commands;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.api.event.PlayerTogglePvpEvent;
import me.youhavetrouble.preventstabby.config.PreventStabbyPermission; import me.youhavetrouble.preventstabby.config.PreventStabbyPermission;
import me.youhavetrouble.preventstabby.util.CombatTimer; import me.youhavetrouble.preventstabby.data.PlayerManager;
import me.youhavetrouble.preventstabby.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -10,39 +11,47 @@ import org.bukkit.entity.Player;
public class PvpToggleCommand { public class PvpToggleCommand {
private static final PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
public static void toggle(CommandSender sender, String[] args) { public static void toggle(CommandSender sender, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getAsyncScheduler().runNow(PreventStabby.getPlugin(), (task) -> {
if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
if (args.length == 1) { if (args.length <= 1) {
if (sender instanceof Player) { if (!(sender instanceof Player player)) {
Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return;
}
boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId());
if (currentState) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
} else {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_disabled());
}
} else {
PluginMessages.sendMessage(sender, "Try /pvp toggle <player>"); PluginMessages.sendMessage(sender, "Try /pvp toggle <player>");
}
} else if (args.length == 2) {
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
return; return;
} }
if (sender instanceof Player) { if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
Player player = (Player) sender; PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
if (CombatTimer.isInCombat(player.getUniqueId())) { return;
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat()); }
playerManager.togglePlayerPvpState(player.getUniqueId()).thenAccept(newState -> {
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, newState, true);
Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task1) -> {
if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
Bukkit.getPluginManager().callEvent(toggleEvent);
}
if (!toggleEvent.isSendMessage()) return;
if (newState) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().pvp_enabled);
} else {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().pvp_disabled);
}
});
});
} else if (args.length == 2) {
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return;
}
if (sender instanceof Player player) {
if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
return; return;
} }
} }
@@ -52,50 +61,65 @@ public class PvpToggleCommand {
PluginMessages.sendMessage(sender, "<red>Player offline."); PluginMessages.sendMessage(sender, "<red>Player offline.");
return; return;
} }
boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId()); playerManager.togglePlayerPvpState(player.getUniqueId()).thenAccept(newState -> {
String message; PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, newState, false);
if (currentState) { Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task1) -> {
message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other(); if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
} else { Bukkit.getPluginManager().callEvent(toggleEvent);
message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other(); }
} if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message)); if (newState) {
} else { PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().pvp_enabled);
if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) { } else {
PluginMessages.sendMessage(sender, "Try /pvp toggle <player>"); PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().pvp_disabled);
} else { }
PluginMessages.sendMessage(sender, "Try /pvp toggle"); }
} String message;
if (newState) {
message = PreventStabby.getPlugin().getConfigCache().pvp_enabled_other;
} else {
message = PreventStabby.getPlugin().getConfigCache().pvp_disabled_other;
}
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
});
});
} }
}); });
} }
public static void enable(CommandSender sender, String[] args) { public static void enable(CommandSender sender, String[] args) {
if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
if (args.length == 1) { if (args.length == 1) {
if (sender instanceof Player) { if (!(sender instanceof Player player)) {
Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return;
}
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true);
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
} else {
PluginMessages.sendMessage(sender, "Try /pvp enable <player>"); PluginMessages.sendMessage(sender, "Try /pvp enable <player>");
}
} else if (args.length == 2) {
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
return; return;
} }
if (sender instanceof Player) { if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
Player player = (Player) sender; PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
if (CombatTimer.isInCombat(player.getUniqueId())) { return;
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat()); }
playerManager.setPlayerPvpState(player.getUniqueId(), true);
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, true, true);
Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task) -> {
if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
Bukkit.getPluginManager().callEvent(toggleEvent);
}
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().pvp_enabled);
}
});
} else if (args.length == 2) {
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return;
}
if (sender instanceof Player player) {
if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
return; return;
} }
} }
@@ -104,9 +128,18 @@ public class PvpToggleCommand {
PluginMessages.sendMessage(sender, "<red>Player offline."); PluginMessages.sendMessage(sender, "<red>Player offline.");
return; return;
} }
String message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other(); String message = PreventStabby.getPlugin().getConfigCache().pvp_enabled_other;
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message)); PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true); playerManager.setPlayerPvpState(player.getUniqueId(), true);
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, true, false);
Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task) -> {
if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
Bukkit.getPluginManager().callEvent(toggleEvent);
}
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().pvp_enabled);
}
});
} else { } else {
if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) { if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, "Try /pvp enable <player>"); PluginMessages.sendMessage(sender, "Try /pvp enable <player>");
@@ -118,30 +151,36 @@ public class PvpToggleCommand {
public static void disable(CommandSender sender, String[] args) { public static void disable(CommandSender sender, String[] args) {
if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
if (args.length == 1) { if (args.length == 1) {
if (sender instanceof Player) { if (sender instanceof Player player) {
Player player = (Player) sender; if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
if (CombatTimer.isInCombat(player.getUniqueId())) { PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), false); playerManager.setPlayerPvpState(player.getUniqueId(), false);
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_disabled()); PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, false, true);
Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task) -> {
if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
Bukkit.getPluginManager().callEvent(toggleEvent);
}
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().pvp_disabled);
}
});
} else { } else {
PluginMessages.sendMessage(sender, "Try /pvp disable <player>"); PluginMessages.sendMessage(sender, "Try /pvp disable <player>");
} }
} else if (args.length == 2) { } else if (args.length == 2) {
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
if (sender instanceof Player) { if (sender instanceof Player player) {
Player player = (Player) sender; if (playerManager.getPlayer(player.getUniqueId()).isInCombat()) {
if (CombatTimer.isInCombat(player.getUniqueId())) { PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().cant_do_that_during_combat);
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
} }
@@ -150,9 +189,18 @@ public class PvpToggleCommand {
PluginMessages.sendMessage(sender, "<red>Player offline."); PluginMessages.sendMessage(sender, "<red>Player offline.");
return; return;
} }
String message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other(); String message = PreventStabby.getPlugin().getConfigCache().pvp_disabled_other;
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message)); PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true); playerManager.setPlayerPvpState(player.getUniqueId(), false);
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, false, false);
Bukkit.getGlobalRegionScheduler().run(PreventStabby.getPlugin(), (task) -> {
if (PlayerTogglePvpEvent.getHandlerList().getRegisteredListeners().length > 0) {
Bukkit.getPluginManager().callEvent(toggleEvent);
}
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().pvp_disabled);
}
});
} else { } else {
if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) { if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
@@ -9,9 +9,9 @@ import org.bukkit.command.CommandSender;
public class ReloadCommand { public class ReloadCommand {
public static void reload(CommandSender sender) { public static void reload(CommandSender sender) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getAsyncScheduler().runNow(PreventStabby.getPlugin(), (task) -> {
if (!PreventStabbyPermission.COMMAND_RELOAD.doesCommandSenderHave(sender)) { if (!PreventStabbyPermission.COMMAND_RELOAD.doesCommandSenderHave(sender)) {
PluginMessages.parseMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.parseMessage(sender, PreventStabby.getPlugin().getConfigCache().no_permission);
return; return;
} }
PreventStabby.getPlugin().reloadPluginConfig(sender); PreventStabby.getPlugin().reloadPluginConfig(sender);
@@ -1,157 +1,220 @@
package me.youhavetrouble.preventstabby.config; package me.youhavetrouble.preventstabby.config;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import io.github.thatsmusic99.configurationmaster.CMFile;
import lombok.Getter;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
public class ConfigCache { public class ConfigCache {
private final PreventStabby plugin = PreventStabby.getPlugin(); public final boolean pvp_enabled_by_default,
bucket_stopper_enabled,
@Getter private final boolean pvp_enabled_by_default, lava_and_fire_stopper_enabled, channeling_enchant_disabled, fire_stopper_enabled,
punish_for_combat_logout, punish_for_combat_logout_announce, only_owner_can_interact_with_pet, block_stopper_enabled,
snowballs_knockback, egg_knockback, block_commands_in_combat, block_teleports_in_combat, allow_fishing_rod_pull; punish_for_combat_logout,
@Getter private final String pvp_enabled, pvp_disabled, cannot_attack_victim, cannot_attack_attacker, punish_for_combat_logout_announce,
block_teleports_in_combat,
allow_fishing_rod_pull;
public final String pvp_enabled, pvp_disabled, cannot_attack_victim, cannot_attack_attacker,
cannot_attack_pets_victim, cannot_attack_pets_attacker, no_permission, no_such_command, pvp_enabled_other, cannot_attack_pets_victim, cannot_attack_pets_attacker, no_permission, no_such_command, pvp_enabled_other,
pvp_disabled_other, punish_for_combat_logout_message, entering_combat, leaving_combat, pvp_disabled_other, punish_for_combat_logout_message, entering_combat, leaving_combat,
cant_do_that_during_combat, cannot_attack_mounts_attacker, cannot_attack_mounts_victim, force_pvp_on, cant_do_that_during_combat, cannot_attack_mounts_attacker, cannot_attack_mounts_victim, force_pvp_on,
force_pvp_off, force_pvp_none, placeholder_combat_time, placeholder_not_in_combat, cannot_attack_pvp_force_off; force_pvp_off, force_pvp_none, placeholder_combat_time, placeholder_not_in_combat, cannot_attack_pvp_force_off,
@Getter private final double lava_and_fire_stopper_radius; placeholder_pvp_forced_true, placeholder_pvp_forced_false, placeholder_pvp_forced_none;
@Getter private final long cache_time, combat_time, login_protection_time, teleport_protection_time;
@Getter private final Set<String> combatBlockedCommands = new HashSet<>();
public ConfigCache() { public final String cannot_attack_forced_pvp_off, cannot_attack_teleport_or_spawn_protection_attacker,
cannot_attack_pets_teleport_or_spawn_protection_attacker, cannot_attack_mounts_teleport_or_spawn_protection_attacker,
cannot_attack_teleport_or_spawn_protection_victim;
CMFile configFile = new CMFile(plugin, "config") { public final double combat_time, login_protection_time, teleport_protection_time, bucket_stopper_radius,
@Override fire_stopper_radius, block_stopper_radius;
public void loadDefaults() { private final Set<String> combatBlockedCommands = new HashSet<>();
addDefault("settings.pvp_enabled_by_default", false, "Decides if pvp should be enabled or disabled by default"); private final FileConfiguration config;
addComment("settings.lava_and_fire_stopper", "Prevents dumping lava and pufferfish bucket, placing wither roses and lighting blocks on fire near players with pvp off"); public ConfigCache(PreventStabby plugin) {
addDefault("settings.lava_and_fire_stopper.enabled", true); plugin.reloadConfig();
addDefault("settings.lava_and_fire_stopper.radius", 2.5); config = plugin.getConfig();
addDefault("settings.channeling_enchant_disabled", false, "Disables channeling (trident enchant) lightning strike.\nYou may want to keep it disabled because players with pvp off can use it to attack players with pvp on");
addDefault("settings.only_owner_can_interact_with_pet", false, "Makes it so only pet owner can interact with it. Useful if you don't want people renaming other people's pets.");
addDefault("settings.combat_time", 25, "Time (in seconds) to keep player in combat");
addDefault("settings.login_protection_time", 0, "Time (in seconds) that player can't be harmed by other player after logging in");
addDefault("settings.teleport_protection_time", 0, "Time (in seconds) that player can't be harmed by other player after teleporting");
addComment("settings.punish_for_combat_logout", "Kill the player if they log out during combat");
addDefault("settings.punish_for_combat_logout.enabled", true);
addDefault("settings.punish_for_combat_logout.announce", true);
addDefault("settings.punish_for_combat_logout.message", "%player%<reset> <white>logged out while in combat. What a loser.");
addDefault("settings.snowballs_do_knockback", false, "Set to true if snowballs should cause knockback to players");
addDefault("settings.eggs_do_knockback", false, "Set to true if eggs should cause knockback to players");
addDefault("settings.allow_fishing_rod_pull", false, "Allows players with pvp off to be pulled by fishing rods");
addComment("settings.block_in_combat", "Set what actions should be blocked while in combat");
addDefault("settings.block_in_combat.block_commands.enabled", true);
List<String> defaultCommandsBlocked = new ArrayList<>();
defaultCommandsBlocked.add("spawn");
defaultCommandsBlocked.add("tpa");
defaultCommandsBlocked.add("home");
addDefault("settings.block_in_combat.block_commands.commands", defaultCommandsBlocked);
addDefault("settings.block_in_combat.block_teleports", true, "Set if players should be denied teleportation attempts while in combat");
addDefault("settings.cache_time", 30, "Time (in seconds) to keep player data in memory when players goes offline.\nThis is used for checking if offline players pvp state.\nAdjust only if you know what you're doing. NEVER set to less than 6.");
addDefault("messages.pvp_enabled", "<red>You enabled PvP!");
addDefault("messages.pvp_disabled", "<red>You disabled PvP!");
addDefault("messages.cannot_attack_victim", "<red>You can't attack players that have PvP turned off!");
addDefault("messages.cannot_attack_attacker", "<red>You can't attack players while you have PvP turned off!");
addDefault("messages.cannot_attack_pets_victim", "<red>You can't attack pets of players that have PvP turned off");
addDefault("messages.cannot_attack_pets_attacker", "<red>You can't attack pets while you have PvP turned off");
addDefault("messages.cannot_attack_mounts_victim", "<red>You can't attack mounts of players that have PvP turned off");
addDefault("messages.cannot_attack_mounts_attacker", "<red>You can't attack mounts while you have PvP turned off");
addDefault("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled");
addDefault("messages.no_permission", "<red>You don't have permission to use that.");
addDefault("messages.no_such_command", "<red>No such command.");
addDefault("messages.pvp_enabled_others", "<red>You've enabled %player%'s PvP.");
addDefault("messages.pvp_disabled_others", "<red>You've disabled %player%'s PvP.");
addDefault("messages.entering_combat", "<red>Entering combat");
addDefault("messages.leaving_combat", "<red>Leaving combat");
addDefault("messages.cant_do_that_during_combat", "<red>You can't do that while in combat!");
addDefault("messages.force_pvp_on", "PvP is now force enabled");
addDefault("messages.force_pvp_off", "PvP is now force disabled");
addDefault("messages.force_pvp_none", "PvP state is not forced now");
addDefault("placeholder.placeholder_combat_time", "Combat time: %time%");
addDefault("placeholder.not_in_combat", "Not in combat");
}
};
configFile.setDescription("Prevent people from getting stabbed!");
configFile.addLink("Spigot", "https://www.spigotmc.org/resources/89376/");
configFile.addLink("Source", "https://github.com/YouHaveTrouble/PreventStabby");
configFile.load();
FileConfiguration config = configFile.getConfig();
// Settings // Settings
this.pvp_enabled_by_default = config.getBoolean("settings.pvp_enabled_by_default", false); this.pvp_enabled_by_default = getBoolean(
"settings.pvp_enabled_by_default",
false,
List.of("Should pvp be enabled by default when the player first joins?")
);
this.lava_and_fire_stopper_enabled = config.getBoolean("settings.lava_and_fire_stopper.enabled", true); this.combat_time = getDouble(
this.lava_and_fire_stopper_radius = config.getDouble("settings.lava_and_fire_stopper.radius", 2.5); "settings.combat_time",
25,
List.of("How long in seconds should combat last since the last hit")
);
this.punish_for_combat_logout = getBoolean(
"settings.punish_for_combat_logout.enabled",
true,
List.of("Should players be killed if they log out during combat?")
);
this.punish_for_combat_logout_announce = getBoolean(
"settings.punish_for_combat_logout.announce",
true,
List.of("Should killing of a player that logged out of combat be announced?")
);
this.channeling_enchant_disabled = config.getBoolean("settings.channeling_enchant_disabled", true); this.combatBlockedCommands.addAll(getList(
"settings.block_in_combat.commands",
List.of("spawn", "tpa", "home"),
List.of("Commands to block when player is in combat")
)
);
this.combat_time = config.getLong("settings.combat_time", 25L); this.block_teleports_in_combat = getBoolean(
this.punish_for_combat_logout = config.getBoolean("settings.punish_for_combat_logout.enabled", true); "settings.block_in_combat.teleports",
this.punish_for_combat_logout_announce = config.getBoolean("settings.punish_for_combat_logout.announce", true); false,
this.punish_for_combat_logout_message = config.getString("settings.punish_for_combat_logout.message", "%player%<reset><white> logged out while in combat. What a loser."); List.of("Block teleportation triggered by plugins while in combat")
this.only_owner_can_interact_with_pet = config.getBoolean("settings.only_owner_can_interact_with_pet", false); );
this.allow_fishing_rod_pull = config.getBoolean("settings.allow_fishing_rod_pull", false); this.login_protection_time = getDouble(
this.snowballs_knockback = config.getBoolean("settings.snowballs_do_knockback", false); "settings.login_protection_time",
this.egg_knockback = config.getBoolean("settings.eggs_do_knockback", false); 0,
this.block_commands_in_combat = config.getBoolean("settings.block_in_combat.block_commands", true); List.of("Protection time after player logs in in seconds")
if (block_commands_in_combat) { );
this.combatBlockedCommands.addAll(config.getStringList("settings.block_in_combat.block_commands.commands")); this.teleport_protection_time = getDouble(
} "settings.teleport_protection_time",
this.block_teleports_in_combat = config.getBoolean("settings.block_in_combat.block_teleports", false); 0,
List.of("Protection time after player is teleported in seconds")
);
this.cache_time = config.getLong("settings.cache_time", 30L); this.allow_fishing_rod_pull = getBoolean(
"settings.allow_fishing_rod_pull",
this.login_protection_time = config.getLong("settings.login_protection_time", 0); false,
this.teleport_protection_time = config.getLong("settings.teleport_protection_time", 0); List.of("Should fishing rod pulling be allowed regardless of players pvp state?")
);
this.bucket_stopper_enabled = getBoolean(
"settings.environmental.bucket_stopper.enabled",
true,
List.of("Should plugin block dumping buckets with dangers near players with pvp off?")
);
this.bucket_stopper_radius = getDouble(
"settings.environmental.bucket_stopper.radius",
2.5,
List.of("Distance from the player where dumping buckets will be disallowed")
);
this.fire_stopper_enabled = getBoolean(
"settings.environmental.fire_stopper.enabled",
true,
List.of("Should plugin block igniting blocks near players with pvp off?")
);
this.fire_stopper_radius = getDouble(
"settings.environmental.fire_stopper.radius",
2.5,
List.of("Distance from the player where igniting blocks will be disallowed")
);
this.block_stopper_enabled = getBoolean(
"settings.environmental.block_stopper.enabled",
true,
List.of("Should plugin block placing dangerous blocks near players with pvp off?")
);
this.block_stopper_radius = getDouble(
"settings.environmental.block_stopper.radius",
2.5,
List.of("Distance from the player where placing dangerous blocks will be disallowed")
);
// Messages // Messages
this.pvp_enabled = config.getString("messages.pvp_enabled", "<red>You enabled PvP!"); this.pvp_enabled = getString("messages.pvp_enabled", "<red>You enabled PvP!");
this.pvp_disabled = config.getString("messages.pvp_disabled", "<red>You disabled PvP!"); this.pvp_disabled = getString("messages.pvp_disabled", "<red>You disabled PvP!");
this.cannot_attack_victim = config.getString("messages.cannot_attack_victim", "<red>You can't attack players that have PvP turned off!"); this.cannot_attack_victim = getString("messages.cannot_attack_victim", "<red>You can't attack players that have PvP turned off!");
this.cannot_attack_attacker = config.getString("messages.cannot_attack_attacker", "<red>You can't attack players while you have PvP turned off!"); this.cannot_attack_attacker = getString("messages.cannot_attack_attacker", "<red>You can't attack players while you have PvP turned off!");
this.cannot_attack_pets_victim = config.getString("messages.cannot_attack_pets_victim", "<red>You can't attack pets while you have PvP turned off"); this.cannot_attack_pets_victim = getString("messages.cannot_attack_pets_victim", "<red>You can't attack pets while you have PvP turned off");
this.cannot_attack_pets_attacker = config.getString("messages.cannot_attack_pets_attacker", "<red>You can't attack pets of players that have PvP turned off"); this.cannot_attack_pets_attacker = getString("messages.cannot_attack_pets_attacker", "<red>You can't attack pets of players that have PvP turned off");
this.cannot_attack_mounts_victim = config.getString("messages.cannot_attack_mounts_victim", "<red>You can't attack mounts of players that have PvP turned off"); this.cannot_attack_mounts_victim = getString("messages.cannot_attack_mounts_victim", "<red>You can't attack mounts of players that have PvP turned off");
this.cannot_attack_mounts_attacker = config.getString("messages.cannot_attack_mounts_attacker", "<red>You can't attack mounts while you have PvP turned off"); this.cannot_attack_mounts_attacker = getString("messages.cannot_attack_mounts_attacker", "<red>You can't attack mounts while you have PvP turned off");
this.cannot_attack_pvp_force_off = config.getString("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled"); this.cannot_attack_pvp_force_off = getString("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled");
this.no_permission = config.getString("messages.no_permission", "<red>You don't have permission to use that.");
this.no_such_command = config.getString("messages.no_such_command", "<red>No such command.");
this.pvp_enabled_other = config.getString("messages.pvp_enabled_others", "<red>You've enabled %player%'s PvP.");
this.pvp_disabled_other = config.getString("messages.pvp_disabled_others", "<red>You've disabled %player%'s PvP.");
this.entering_combat = config.getString("messages.entering_combat", "<red>Entering combat");
this.leaving_combat = config.getString("messages.leaving_combat", "<red>Leaving combat");
this.cant_do_that_during_combat = config.getString("messages.cant_do_that_during_combat", "<red>You can't do that while in combat!");
this.force_pvp_on = config.getString("messages.force_pvp_on", "PvP is now force enabled");
this.force_pvp_off = config.getString("messages.force_pvp_off", "PvP is now force disabled");
this.force_pvp_none = config.getString("messages.force_pvp_none", "PvP state is not forced now");
this.placeholder_combat_time = config.getString("placeholder.placeholder_combat_time", "Combat time: %time%"); this.no_permission = getString("messages.no_permission", "<red>You don't have permission to use that.");
this.placeholder_not_in_combat = config.getString("placeholder.not_in_combat", "Not in combat"); this.no_such_command = getString("messages.no_such_command", "<red>No such command.");
this.pvp_enabled_other = getString("messages.pvp_enabled_others", "<red>You've enabled %player%'s PvP.");
this.pvp_disabled_other = getString("messages.pvp_disabled_others", "<red>You've disabled %player%'s PvP.");
this.entering_combat = getString("messages.entering_combat", "<red>Entering combat");
this.leaving_combat = getString("messages.leaving_combat", "<red>Leaving combat");
this.cant_do_that_during_combat = getString("messages.cant_do_that_during_combat", "<red>You can't do that while in combat!");
this.force_pvp_on = getString("messages.force_pvp_on", "PvP is now force enabled");
this.force_pvp_off = getString("messages.force_pvp_off", "PvP is now force disabled");
this.force_pvp_none = getString("messages.force_pvp_none", "PvP state is not forced now");
this.punish_for_combat_logout_message = getString("messages.punish_for_combat_logout.message", "%player%<reset><white> logged out while in combat. What a loser.");
this.placeholder_combat_time = getString("placeholder.placeholder_combat_time", "Combat time: %time%");
this.placeholder_not_in_combat = getString("placeholder.not_in_combat", "Not in combat");
this.placeholder_pvp_forced_true = getString("placeholder.pvp_forced_true", "PvP is forced on");
this.placeholder_pvp_forced_false = getString("placeholder.pvp_forced_false", "PvP is forced off");
this.placeholder_pvp_forced_none = getString("placeholder.pvp_forced_none", "PvP is not forced");
this.cannot_attack_forced_pvp_off = getString("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled");
this.cannot_attack_teleport_or_spawn_protection_attacker = getString("messages.cannot_attack_teleport_or_spawn_protection_attacker", "<red>You can't attack players while they have teleport or spawn protection");
this.cannot_attack_pets_teleport_or_spawn_protection_attacker = getString("messages.cannot_attack_pets_teleport_or_spawn_protection_attacker", "<red>You can't attack pets while you have teleport or spawn protection");
this.cannot_attack_mounts_teleport_or_spawn_protection_attacker = getString("messages.cannot_attack_mounts_teleport_or_spawn_protection_attacker", "<red>You can't attack mounts while you have teleport or spawn protection");
this.cannot_attack_teleport_or_spawn_protection_victim = getString("messages.cannot_attack_teleport_or_spawn_protection_victim", "<red>You can't attack players while you have teleport or spawn protection");
try {
config.save(new File(plugin.getDataFolder(), "config.yml"));
} catch (IOException e) {
plugin.getLogger().severe("Failed to save configuration file! - " + e.getLocalizedMessage());
}
}
public Set<String> getCombatBlockedCommands() {
return Collections.unmodifiableSet(combatBlockedCommands);
}
private String getString(String path, @NotNull String def) {
return getString(path, def, null);
}
private String getString(String path, @NotNull String def, @Nullable List<String> comments) {
if (config.isSet(path)) return config.getString(path, def);
config.set(path, def);
if (comments != null) config.setComments(path, comments);
return def;
}
private boolean getBoolean(String path, boolean def, @Nullable List<String> comments) {
if (config.isSet(path)) return config.getBoolean(path, def);
config.set(path, def);
if (comments != null) config.setComments(path, comments);
return def;
}
private double getDouble(String path, double def, @Nullable List<String> comments) {
if (config.isSet(path)) return config.getDouble(path, def);
config.set(path, def);
if (comments != null) config.setComments(path, comments);
return def;
}
private long getLong(String path, long def, @Nullable List<String> comments) {
if (config.isSet(path)) return config.getLong(path, def);
config.set(path, def);
if (comments != null) config.setComments(path, comments);
return def;
}
private List<String> getList(String path, List<String> def, @Nullable List<String> comments) {
if (config.isSet(path)) return config.getStringList(path);
config.set(path, def);
if (comments != null) config.setComments(path, comments);
return def;
}
private List<String> getList(String path, List<String> def) {
return getList(path, def, null);
} }
@@ -8,7 +8,8 @@ public enum PreventStabbyPermission {
COMMAND_TOGGLE("command.toggle"), COMMAND_TOGGLE("command.toggle"),
COMMAND_TOGGLE_OTHERS("command.toggle.others"), COMMAND_TOGGLE_OTHERS("command.toggle.others"),
COMMAND_RELOAD("command.reload"), COMMAND_RELOAD("command.reload"),
COMMAND_GLOBAL_TOGGLE("command.toggle.global"); COMMAND_GLOBAL_TOGGLE("command.toggle.global"),
COMMAND_HELP("command.help");
private final String permission; private final String permission;
PreventStabbyPermission(String permission) { PreventStabbyPermission(String permission) {
@@ -0,0 +1,40 @@
package me.youhavetrouble.preventstabby.data;
import javax.annotation.Nullable;
import java.util.UUID;
/**
* @param ableToDamage Result of the damage check
* @param feedbackForAttacker Feedback to send to the attacker
* @param attackerId UUID of attacker player
* @param victimId UUID of victim player
*/
public record DamageCheckResult(
boolean ableToDamage,
@Nullable UUID attackerId,
@Nullable UUID victimId,
@Nullable String feedbackForAttacker,
boolean shouldVictimBePutInCombat
) {
public static DamageCheckResult positive() {
return new DamageCheckResult(
true,
null,
null,
null,
true
);
}
public static DamageCheckResult positive(UUID attackerId, UUID victimId, boolean shouldVictimBePutInCombat) {
return new DamageCheckResult(
true,
attackerId,
victimId,
null,
shouldVictimBePutInCombat
);
}
}
@@ -0,0 +1,165 @@
package me.youhavetrouble.preventstabby.data;
import me.youhavetrouble.preventstabby.PreventStabby;
import java.util.UUID;
/**
* PreventStabby player data keeper.
*/
public class PlayerData {
private final UUID playerUuid;
private long lastAccessTimestamp;
private Long combatStartTimestamp, teleportTimestamp, loginTimestamp;
private boolean pvpEnabled, lastCombatCheck;
public PlayerData(UUID playerUuid, boolean pvpEnabled) {
this.playerUuid = playerUuid;
this.pvpEnabled = pvpEnabled;
this.lastCombatCheck = false;
this.combatStartTimestamp = null;
this.loginTimestamp = null;
this.teleportTimestamp = null;
refreshCacheTime();
}
public UUID getPlayerUuid() {
return playerUuid;
}
/**
* Returns true if player has personal pvp enabled, false otherwise.
* @return True if player has personal pvp enabled, false otherwise.
*/
public boolean isPvpEnabled() {
return pvpEnabled;
}
/**
* Sets player's personal pvp state.
* @param pvpEnabled Pvp state to set.
*/
protected void setPvpEnabled(boolean pvpEnabled) {
this.pvpEnabled = pvpEnabled;
}
/**
* Returns player's last access timestamp.
* @return Player's last access timestamp.
*/
protected long getLastAccessTimestamp() {
return lastAccessTimestamp;
}
protected boolean isCacheExpired() {
return System.currentTimeMillis() - lastAccessTimestamp > 60000;
}
/**
* Refreshes the last access to any of the fields
*/
protected void refreshCacheTime() {
this.lastAccessTimestamp = System.currentTimeMillis();
}
/**
* Retrieves the timestamp when combat started.
* @return The timestamp when combat started.
*/
protected long getCombatStartTimestamp() {
refreshCacheTime();
return combatStartTimestamp;
}
protected boolean getLastCombatCheckState() {
return lastCombatCheck;
}
protected void setLastCombatCheckState(boolean state) {
this.lastCombatCheck = state;
}
/**
* Marks the player as in combat.
*/
public void markInCombat() {
refreshCacheTime();
if (PreventStabby.getPlugin().getConfigCache().combat_time <= 0) return;
this.combatStartTimestamp = System.currentTimeMillis();
}
protected void markNotInCombat() {
refreshCacheTime();
this.combatStartTimestamp = null;
}
/**
* Sets the login timestamp for the player.
* @param loginTimestamp The login timestamp to set.
*/
protected void setLoginTimestamp(long loginTimestamp) {
this.loginTimestamp = loginTimestamp;
}
/**
* Retrieves the login timestamp for the player.
* @return The login timestamp for the player.
*/
public Long getLoginTimestamp() {
return loginTimestamp;
}
/**
* Sets the timestamp of the player's teleport.
* @param teleportTimestamp The timestamp of the player's teleport.
*/
public void setTeleportTimestamp(long teleportTimestamp) {
this.teleportTimestamp = teleportTimestamp;
}
/**
* Checks if the player is currently in combat.
*
* @return true if the player is in combat, false otherwise.
*/
public boolean isInCombat() {
if (combatStartTimestamp == null) return false;
return System.currentTimeMillis() - (combatStartTimestamp + (PreventStabby.getPlugin().getConfigCache().combat_time * 1000)) < 0;
}
/**
* Retrieves the number of seconds left until combat ends for the player.
* @return The number of seconds left until combat ends. -1 if not in combat
*/
public long getSecondsLeftUntilCombatEnd() {
if (combatStartTimestamp == null) return -1;
long timeSinceCombatStart = System.currentTimeMillis() - combatStartTimestamp;
long combatTimeConfigured = (long) (PreventStabby.getPlugin().getConfigCache().combat_time * 1000);
return (timeSinceCombatStart < combatTimeConfigured) ? (combatTimeConfigured - timeSinceCombatStart) / 1000 : -1;
}
/**
* Checks if the player has login protection.
*
* @return true if the player has login protection, false otherwise.
*/
public boolean hasLoginProtection() {
if (loginTimestamp == null) return false;
return System.currentTimeMillis() - (loginTimestamp + (PreventStabby.getPlugin().getConfigCache().login_protection_time * 1000)) < 0;
}
public boolean hasTeleportProtection() {
if (teleportTimestamp == null) return false;
return System.currentTimeMillis() - (teleportTimestamp + (PreventStabby.getPlugin().getConfigCache().teleport_protection_time * 1000)) < 0;
}
/**
* Returns true if the player has any form of protection enabled, including login and teleport protection.
*
* @return true if the player has protection enabled, false otherwise.
*/
public boolean isProtected() {
return hasLoginProtection() || hasTeleportProtection();
}
}
@@ -0,0 +1,82 @@
package me.youhavetrouble.preventstabby.data;
import com.destroystokyo.paper.event.entity.EntityAddToWorldEvent;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.*;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
public class PlayerListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(AsyncPlayerPreLoginEvent event) {
if (!event.getLoginResult().equals(AsyncPlayerPreLoginEvent.Result.ALLOWED)) return;
UUID uuid = event.getUniqueId();
try {
PreventStabby.getPlugin().getPlayerManager().getPlayerData(uuid).get();
} catch (ExecutionException | InterruptedException e) {
PreventStabby.getPlugin().getLogger().severe(e.getMessage());
PreventStabby.getPlugin().getLogger().severe("Failed to load data for player %s".formatted(event.getPlayerProfile().getName()));
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, new PlayerData(uuid, false));
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event) {
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(event.getPlayer().getUniqueId());
playerData.setLoginTimestamp(System.currentTimeMillis());
}
/**
* This event is here to save player's data to database
* Also punishes players who log out during combat
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerLeave(PlayerQuitEvent event) {
Player player = event.getPlayer();
if (!PreventStabby.getPlugin().getConfigCache().punish_for_combat_logout) return;
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
if (!playerData.isInCombat()) return;
player.setHealth(0);
if (!PreventStabby.getPlugin().getConfigCache().punish_for_combat_logout_announce) return;
PluginMessages.broadcastMessage(player, PreventStabby.getPlugin().getConfigCache().punish_for_combat_logout_message);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
Player player = event.getPlayer();
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
playerData.setTeleportTimestamp(Instant.now().getEpochSecond());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDeath(EntityDeathEvent event) {
if (!(event.getEntity() instanceof Player player)) return;
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
if (playerData == null) return;
playerData.markNotInCombat();
}
/**
* Load data for owners of loaded tameables
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityLoad(EntityAddToWorldEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Tameable tameable)) return;
UUID ownerId = tameable.getOwnerUniqueId();
if (ownerId == null) return;
PreventStabby.getPlugin().getPlayerManager().getPlayerData(ownerId);
}
}
@@ -0,0 +1,257 @@
package me.youhavetrouble.preventstabby.data;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.api.event.PlayerEnterCombatEvent;
import me.youhavetrouble.preventstabby.api.event.PlayerLeaveCombatEvent;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class PlayerManager {
private final PreventStabby plugin;
private final ConcurrentHashMap<UUID, PlayerData> playerList = new ConcurrentHashMap<>();
private PvpState pvpForcedState = PvpState.NONE;
public PlayerManager(PreventStabby plugin) {
this.plugin = plugin;
Bukkit.getAsyncScheduler().runAtFixedRate(plugin, (task) -> {
// Check for entries that should be invalidated
playerList.values().removeIf(PlayerData::isCacheExpired);
}, 250, 250, TimeUnit.MILLISECONDS);
Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, (task) -> Bukkit.getWorlds().forEach((world -> {
for (Chunk chunk : world.getLoadedChunks()) {
if (!chunk.isEntitiesLoaded()) continue;
Bukkit.getRegionScheduler().run(plugin, chunk.getWorld(), chunk.getX(), chunk.getZ(), (task1) -> {
for (Entity entity : chunk.getEntities()) {
if (!(entity instanceof Tameable tameable)) continue;
UUID ownerId = tameable.getOwnerUniqueId();
if (ownerId == null) continue;
getPlayerData(ownerId);
}
});
}
})), 5, 20 * 15);
Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, (task) -> {
for (PlayerData playerData : playerList.values()) {
if (playerData == null) continue;
Player player = Bukkit.getPlayer(playerData.getPlayerUuid());
if (player == null || !player.isOnline()) continue;
playerData.refreshCacheTime(); // Refresh cache timer if player is online
// leaving combat logic
if (playerData.getLastCombatCheckState() && !playerData.isInCombat()) {
PlayerLeaveCombatEvent leaveCombatEvent = null;
if (PlayerLeaveCombatEvent.getHandlerList().getRegisteredListeners().length > 0) {
leaveCombatEvent = new PlayerLeaveCombatEvent(player);
Bukkit.getPluginManager().callEvent(leaveCombatEvent);
}
if (leaveCombatEvent != null && leaveCombatEvent.isCancelled()) {
playerData.markInCombat();
playerData.setLastCombatCheckState(playerData.isInCombat());
continue;
}
PluginMessages.sendActionBar(player, plugin.getConfigCache().leaving_combat);
playerData.setLastCombatCheckState(playerData.isInCombat());
continue;
}
// entering combat logic
if (plugin.getConfigCache().combat_time <= 0) return; // disable combat entering when combat time is <0
if (!playerData.getLastCombatCheckState() && playerData.isInCombat()) {
PlayerEnterCombatEvent enterCombatEvent = null;
if (PlayerEnterCombatEvent.getHandlerList().getRegisteredListeners().length > 0) {
enterCombatEvent = new PlayerEnterCombatEvent(player);
Bukkit.getPluginManager().callEvent(enterCombatEvent);
}
if (enterCombatEvent != null && enterCombatEvent.isCancelled()) {
playerData.markNotInCombat();
playerData.setLastCombatCheckState(playerData.isInCombat());
continue;
}
PluginMessages.sendActionBar(player, plugin.getConfigCache().entering_combat);
playerData.setLastCombatCheckState(playerData.isInCombat());
continue;
}
}
}, 1, 1);
}
/**
* Gets player's PlayerData object. Returns null when player with provided UUID doesn't exist.
*
* @param uuid Player's UUID.
* @return Player's PlayerData object or null if player doesn't exist.
*/
public PlayerData getPlayer(UUID uuid) {
return playerList.get(uuid);
}
protected void addPlayer(UUID uuid, PlayerData data) {
playerList.put(uuid, data);
}
public void handleDamageCheck(@NotNull DamageCheckResult damageCheckResult) {
if (damageCheckResult.attackerId() == null) return;
if (damageCheckResult.victimId() == null) return;
PluginMessages.sendOutMessages(damageCheckResult);
PlayerData attacker = getPlayer(damageCheckResult.attackerId());
PlayerData victim = getPlayer(damageCheckResult.victimId());
if (attacker == null || victim == null) return;
if (!damageCheckResult.ableToDamage()) return;
attacker.markInCombat();
if (!damageCheckResult.shouldVictimBePutInCombat()) return;
victim.markInCombat();
}
/**
* Determines whether the given attacker can damage the victim.
*
* @param attacker The attacking entity.
* @param victim The victim entity.
* @return A {@link DamageCheckResult} object containing the result of the damage check.
*/
public DamageCheckResult canDamage(@NotNull Entity attacker, @NotNull Entity victim) {
Target attackerData = Target.getTarget(attacker);
Target victimData = Target.getTarget(victim);
if (attackerData == null || victimData == null) return DamageCheckResult.positive();
return canDamage(attackerData.playerUuid, victimData.playerUuid, victimData.classifier);
}
public DamageCheckResult canDamage(UUID attackerId, UUID victimId, Target.EntityClassifier victimClassifier) {
if (attackerId == null || victimId == null) return DamageCheckResult.positive();
PlayerData attackerPlayerData = getPlayer(attackerId);
PlayerData victimPlayerData = getPlayer(victimId);
if (attackerPlayerData == null || victimPlayerData == null) {
return DamageCheckResult.positive();
}
if (attackerPlayerData.getPlayerUuid().equals(victimPlayerData.getPlayerUuid())) {
return DamageCheckResult.positive(attackerId, victimId, false);
}
if (attackerPlayerData.isProtected()) {
String message = switch (victimClassifier) {
case PLAYER -> plugin.getConfigCache().cannot_attack_teleport_or_spawn_protection_attacker;
case PET -> plugin.getConfigCache().cannot_attack_pets_teleport_or_spawn_protection_attacker;
case MOUNT -> plugin.getConfigCache().cannot_attack_mounts_teleport_or_spawn_protection_attacker;
default -> null;
};
return new DamageCheckResult(false, attackerId, victimId, message, false);
}
if (victimPlayerData.isProtected()) {
String message = null;
if (victimClassifier == Target.EntityClassifier.PLAYER) {
message = plugin.getConfigCache().cannot_attack_teleport_or_spawn_protection_victim;
}
return new DamageCheckResult(false, attackerId, victimId, message, false);
}
switch (getForcedPvpState()) {
case DISABLED -> {
return new DamageCheckResult(false, attackerId, victimId, plugin.getConfigCache().cannot_attack_forced_pvp_off, false);
}
case ENABLED -> {
return DamageCheckResult.positive(attackerId, victimId, victimClassifier.equals(Target.EntityClassifier.PLAYER));
}
}
if (!attackerPlayerData.isPvpEnabled()) {
String message = switch (victimClassifier) {
case PLAYER -> plugin.getConfigCache().cannot_attack_attacker;
case PET -> plugin.getConfigCache().cannot_attack_pets_victim;
case MOUNT -> plugin.getConfigCache().cannot_attack_mounts_attacker;
default -> null;
};
return new DamageCheckResult(false, attackerId, victimId, message, victimClassifier.equals(Target.EntityClassifier.PLAYER));
}
if (!victimPlayerData.isPvpEnabled()) {
String message = switch (victimClassifier) {
case PLAYER -> plugin.getConfigCache().cannot_attack_victim;
case PET -> plugin.getConfigCache().cannot_attack_pets_attacker;
case MOUNT -> plugin.getConfigCache().cannot_attack_mounts_victim;
default -> null;
};
return new DamageCheckResult(false, attackerId, victimId, message, victimClassifier.equals(Target.EntityClassifier.PLAYER));
}
return new DamageCheckResult(
true,
attackerId,
victimId,
null,
victimClassifier.equals(Target.EntityClassifier.PLAYER)
);
}
/**
* Returns current forced pvp state.
* @return Current forced pvp state.
*/
public PvpState getForcedPvpState() {
return pvpForcedState;
}
/**
* Sets current forced pvp state.
* @param forcedPvpState New forced pvp state.
*/
public void setForcedPvpState(PvpState forcedPvpState) {
this.pvpForcedState = forcedPvpState;
}
/**
* Retrieves the PlayerData object for the player with the provided UUID. Returns new default if there isn't data.
*
* @param uuid The UUID of the player.
* @return The PlayerData object associated with the player.
*/
public CompletableFuture<PlayerData> getPlayerData(UUID uuid) {
// Try to get data from cache and refresh it
PlayerData data = getPlayer(uuid);
if (data != null) {
data.refreshCacheTime();
return CompletableFuture.completedFuture(data);
}
// Get data from database or provide default
return CompletableFuture.supplyAsync(() -> {
PlayerData playerData = plugin.getSqLite().getPlayerInfo(uuid);
if (playerData == null) {
playerData = new PlayerData(uuid, false);
}
plugin.getPlayerManager().addPlayer(uuid, playerData);
return playerData;
});
}
public void setPlayerPvpState(UUID uuid, boolean state) {
// If player is in cache update that
if (getPlayer(uuid) != null) {
getPlayer(uuid).setPvpEnabled(state);
}
// Update the database aswell
plugin.getSqLite().updatePlayerInfo(uuid, new PlayerData(uuid, state));
}
public CompletableFuture<Boolean> togglePlayerPvpState(UUID uuid) {
return getPlayerData(uuid).thenApply(playerData -> {
playerData.setPvpEnabled(!playerData.isPvpEnabled());
plugin.getSqLite().updatePlayerInfo(uuid, new PlayerData(uuid, playerData.isPvpEnabled()));
return playerData.isPvpEnabled();
});
}
}
@@ -0,0 +1,97 @@
package me.youhavetrouble.preventstabby.data;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataHolder;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.UUID;
public class Target {
public static final NamespacedKey playerSourceIdKey = new NamespacedKey("preventstabby", "playersource");
/**
* The unique identifier for a player.
*/
public final UUID playerUuid;
/**
* Represents the entity classifier of a target.
* This indicates what type of entity player's id was assumed from
*/
public final EntityClassifier classifier;
private Target(UUID uuid, EntityClassifier classifier) {
this.playerUuid = uuid;
this.classifier = classifier;
}
/**
* Get the UUID of the actual player, being owner of a pet, shooter of a projectile, etc.
*
* @param entity Base entity to get the player UUID from
* @return UUID of the actual player, null if not found
*/
@Nullable
public static Target getTarget(@NotNull Entity entity) {
if (entity instanceof Player) return new Target(entity.getUniqueId(), EntityClassifier.PLAYER);
// Get shooter of projectile
if (entity instanceof Projectile projectile) {
if (projectile.getShooter() instanceof Player shooter) {
return new Target(shooter.getUniqueId(), EntityClassifier.PLAYER);
}
}
// Get player riding mount
if (!entity.getPassengers().isEmpty()) {
Entity passenger = entity.getPassengers().get(0);
if (passenger instanceof Player) {
return new Target(passenger.getUniqueId(), EntityClassifier.MOUNT);
}
}
// Get owner of tamed entity
if (entity instanceof Tameable tameable) {
if (tameable.getOwner() != null) {
return new Target(tameable.getOwner().getUniqueId(), EntityClassifier.PET);
}
}
// Try to get player's id from other various entities
PersistentDataContainer pdc = entity.getPersistentDataContainer();
if (!pdc.has(playerSourceIdKey)) return null;
String id = pdc.get(playerSourceIdKey, PersistentDataType.STRING);
if (id == null) return null;
try {
UUID uuid = UUID.fromString(id);
return new Target(uuid, EntityClassifier.OTHER);
} catch (Exception e) {
return null;
}
}
/**
* Assigns the player source ID to the given data holder.
* @param dataHolder The persistent data holder to assign the player source ID to.
* @param id The UUID of the player source ID to assign.
*/
public static void assignPlayerSourceId(@NotNull PersistentDataHolder dataHolder, @NotNull UUID id) {
dataHolder.getPersistentDataContainer().set(playerSourceIdKey, PersistentDataType.STRING, id.toString());
}
public enum EntityClassifier {
PLAYER,
PET,
MOUNT,
OTHER
}
}
@@ -0,0 +1,74 @@
package me.youhavetrouble.preventstabby.hooks;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class PlaceholderApiHook extends PlaceholderExpansion {
private final PreventStabby plugin;
private final LegacyComponentSerializer legacyComponentSerializer;
public PlaceholderApiHook(PreventStabby preventStabby) {
plugin = preventStabby;
this.legacyComponentSerializer = LegacyComponentSerializer.legacyAmpersand();
}
@Override
public @NotNull String getIdentifier() {
return "preventstabby";
}
@Override
public @NotNull String getAuthor() {
return plugin.getDescription().getAuthors().get(0);
}
@Override
public @NotNull String getVersion() {
return plugin.getDescription().getVersion();
}
@Override
public String onRequest(OfflinePlayer player, String params) {
return switch (params) {
case "pvp" -> {
if (!player.isOnline()) yield String.valueOf(false);
yield String.valueOf(plugin.getPlayerManager().getPlayer(player.getUniqueId()).isPvpEnabled());
}
case "combat_time" -> getCombatTimePlaceholder(player.getUniqueId(), player);
case "in_combat" -> {
if (!player.isOnline()) yield String.valueOf(false);
yield String.valueOf(plugin.getPlayerManager().getPlayer(player.getUniqueId()).isInCombat());
}
case "pvp_forced" -> switch (PreventStabby.getPlugin().getPlayerManager().getForcedPvpState()) {
case NONE ->
legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().placeholder_pvp_forced_none));
case ENABLED ->
legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().placeholder_pvp_forced_true));
case DISABLED ->
legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().placeholder_pvp_forced_false));
};
default -> null;
};
}
private String getCombatTimePlaceholder(UUID uuid, OfflinePlayer player) {
if (!player.isOnline()) {
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().placeholder_not_in_combat));
}
long seconds = plugin.getPlayerManager().getPlayer(uuid).getSecondsLeftUntilCombatEnd();
if (seconds > 0) {
String msg = plugin.getConfigCache().placeholder_combat_time;
msg = msg.replaceAll("%time%", String.valueOf(seconds));
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(msg));
}
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().placeholder_not_in_combat));
}
}
@@ -1,59 +0,0 @@
package me.youhavetrouble.preventstabby.hooks;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.UUID;
public class PlacoholderApiHook extends PlaceholderExpansion {
private final PreventStabby plugin;
private final LegacyComponentSerializer legacyComponentSerializer;
public PlacoholderApiHook(PreventStabby preventStabby) {
plugin = preventStabby;
this.legacyComponentSerializer = LegacyComponentSerializer.legacyAmpersand();
}
@Override
public @NotNull String getIdentifier() {
return "preventstabby";
}
@Override
public @NotNull String getAuthor() {
return plugin.getDescription().getAuthors().get(0);
}
@Override
public @NotNull String getVersion() {
return plugin.getDescription().getVersion();
}
@Override
public String onRequest(OfflinePlayer player, String params) {
if (params.equalsIgnoreCase("combat_time")) {
return getCombatTimePlaceholder(player.getUniqueId());
}
if (params.equalsIgnoreCase("in_combat")) {
return String.valueOf(plugin.getPlayerManager().getPlayer(player.getUniqueId()).isInCombat());
}
return null;
}
private String getCombatTimePlaceholder(UUID uuid) {
long seconds = plugin.getPlayerManager().getPlayer(uuid).getCombattime() - Instant.now().getEpochSecond();
if (seconds > 0) {
String msg = plugin.getConfigCache().getPlaceholder_combat_time();
msg = msg.replaceAll("%time%", String.valueOf(seconds));
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(msg));
}
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().getPlaceholder_not_in_combat()));
}
}
@@ -14,7 +14,6 @@ import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery; import com.sk89q.worldguard.protection.regions.RegionQuery;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class WorldGuardHook { public class WorldGuardHook {
@@ -22,19 +21,18 @@ public class WorldGuardHook {
public static StateFlag FORCE_PVP_FLAG; public static StateFlag FORCE_PVP_FLAG;
public static void init() { public static void init() {
PreventStabby plugin = PreventStabby.getPlugin();
try { try {
Class.forName("com.sk89q.worldguard.protection.flags.registry.FlagRegistry"); Class.forName("com.sk89q.worldguard.protection.flags.registry.FlagRegistry");
WorldGuardPlugin worldGuardPlugin = WorldGuardPlugin.inst(); WorldGuardPlugin worldGuardPlugin = WorldGuardPlugin.inst();
if (WorldGuard.getInstance() == null || worldGuardPlugin == null) return; if (WorldGuard.getInstance() == null || worldGuardPlugin == null) return;
plugin.getLogger().info("Hooking into WorldGuard"); PreventStabby.getPlugin().getLogger().info("[PreventStabby] Hooking into WorldGuard");
flagRegistry = WorldGuard.getInstance().getFlagRegistry(); flagRegistry = WorldGuard.getInstance().getFlagRegistry();
createForcePvpFlag(plugin); createForcePvpFlag();
} catch (NoClassDefFoundError | ClassNotFoundException ignored) { } catch (NoClassDefFoundError | ClassNotFoundException ignored) {
} }
} }
private static void createForcePvpFlag(Plugin plugin) { private static void createForcePvpFlag() {
if (flagRegistry == null) return; if (flagRegistry == null) return;
String flagName = "preventstabby-force-pvp"; String flagName = "preventstabby-force-pvp";
try { try {
@@ -46,7 +44,7 @@ public class WorldGuardHook {
if (existing instanceof StateFlag) { if (existing instanceof StateFlag) {
FORCE_PVP_FLAG = (StateFlag) existing; FORCE_PVP_FLAG = (StateFlag) existing;
} else { } else {
plugin.getLogger().severe("There is a conflict between flag names!"); PreventStabby.getPlugin().getLogger().severe("[PreventStabby] There is a conflict between flag names!");
} }
} }
} }
@@ -0,0 +1,103 @@
package me.youhavetrouble.preventstabby.listeners;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.data.DamageCheckResult;
import me.youhavetrouble.preventstabby.data.Target;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.util.BoundingBox;
import java.util.HashSet;
import java.util.Set;
public class EnvironmentalListener implements Listener {
private final PreventStabby plugin;
private final Set<Material> dangerousBuckets = new HashSet<>();
public EnvironmentalListener(PreventStabby plugin) {
this.plugin = plugin;
dangerousBuckets.add(Material.LAVA_BUCKET);
dangerousBuckets.add(Material.PUFFERFISH_BUCKET);
dangerousBuckets.add(Material.POWDER_SNOW_BUCKET);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onDangerousBucketDump(PlayerBucketEmptyEvent event) {
ConfigCache config = plugin.getConfigCache();
if (!config.bucket_stopper_enabled) return;
if (!dangerousBuckets.contains(event.getBucket())) return;
Location location = event.getBlockClicked().getLocation();
Player placer = event.getPlayer();
double radius = config.bucket_stopper_radius;
BoundingBox boundingBox = BoundingBox.of(location.toVector(), radius, radius, radius);
for (Entity victim : location.getWorld().getNearbyEntities(boundingBox)) {
if (victim.getUniqueId() == placer.getUniqueId()) continue;
Target victimTarget = Target.getTarget(victim);
if (victimTarget == null) continue;
DamageCheckResult result = plugin.getPlayerManager().canDamage(placer.getUniqueId(), victim.getUniqueId(), victimTarget.classifier);
if (!result.ableToDamage()) {
event.setCancelled(true);
break;
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
ConfigCache config = plugin.getConfigCache();
if (!config.fire_stopper_enabled) return;
Entity igniter = event.getIgnitingEntity();
if (igniter == null) return;
Target igniterTarget = Target.getTarget(igniter);
if (igniterTarget == null) return;
Location location = event.getBlock().getLocation();
double radius = config.fire_stopper_radius;
BoundingBox boundingBox = BoundingBox.of(location.toVector(), radius, radius, radius);
for (Entity victim : location.getWorld().getNearbyEntities(boundingBox)) {
if (victim.getUniqueId() == igniterTarget.playerUuid) continue;
Target victimTarget = Target.getTarget(victim);
if (victimTarget == null) continue;
DamageCheckResult result = plugin.getPlayerManager().canDamage(igniterTarget.playerUuid, victim.getUniqueId(), victimTarget.classifier);
if (!result.ableToDamage()) {
event.setCancelled(true);
break;
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockIgnite(BlockPlaceEvent event) {
ConfigCache config = plugin.getConfigCache();
if (!config.block_stopper_enabled) return;
Player player = event.getPlayer();
Location location = event.getBlock().getLocation().toCenterLocation();
Target target = Target.getTarget(player);
if (target == null) return;
double radius = config.block_stopper_radius;
BoundingBox boundingBox = BoundingBox.of(location.toVector(), radius, radius, radius);
for (Entity victim : location.getWorld().getNearbyEntities(boundingBox)) {
if (victim.getUniqueId() == target.playerUuid) continue;
Target victimTarget = Target.getTarget(victim);
if (victimTarget == null) continue;
DamageCheckResult result = plugin.getPlayerManager().canDamage(target.playerUuid, victim.getUniqueId(), victimTarget.classifier);
if (!result.ableToDamage()) {
event.setCancelled(true);
break;
}
}
}
}
@@ -0,0 +1,96 @@
package me.youhavetrouble.preventstabby.listeners;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.data.DamageCheckResult;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.AreaEffectCloudApplyEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class PvpListener implements Listener {
private final PreventStabby plugin;
public PvpListener(PreventStabby plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity victim = event.getEntity();
DamageCheckResult result = plugin.getPlayerManager().canDamage(attacker, victim);
if (!result.ableToDamage()) {
event.setCancelled(true);
}
plugin.getPlayerManager().handleDamageCheck(result);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
if (!(event.getEntity().getShooter() instanceof Player thrower)) return;
boolean harmful = false;
for (PotionEffect effect : event.getPotion().getEffects()) {
if (!PotionEffectType.Category.HARMFUL.equals(effect.getType().getEffectCategory())) continue;
harmful = true;
break;
}
if (!harmful) return;
for (LivingEntity victim : event.getAffectedEntities()) {
if (thrower == victim) continue;
DamageCheckResult result = plugin.getPlayerManager().canDamage(thrower, victim);
if (!result.ableToDamage()) {
event.setIntensity(victim, 0);
}
plugin.getPlayerManager().handleDamageCheck(result);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPotionCloudEffectApply(AreaEffectCloudApplyEvent event) {
if (!(event.getEntity().getSource() instanceof Player thrower)) return;
boolean harmful = false;
for (PotionEffect effect : event.getEntity().getBasePotionType().getPotionEffects()) {
if (!PotionEffectType.Category.HARMFUL.equals(effect.getType().getEffectCategory())) continue;
harmful = true;
break;
}
if (!harmful) return;
event.getAffectedEntities().removeIf(victim -> {
if (thrower == victim) return false;
boolean shouldRemoveFromAffected = false;
DamageCheckResult result = plugin.getPlayerManager().canDamage(thrower, victim);
if (!result.ableToDamage()) {
shouldRemoveFromAffected = true;
}
plugin.getPlayerManager().handleDamageCheck(result);
return shouldRemoveFromAffected;
});
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFish(PlayerFishEvent event) {
if (event.getCaught() instanceof Item) return;
if (plugin.getConfigCache().allow_fishing_rod_pull) return;
Player attacker = event.getPlayer();
Entity victim = event.getCaught();
if (victim == null) return;
if (attacker == victim) return;
DamageCheckResult result = plugin.getPlayerManager().canDamage(attacker, victim);
if (!result.ableToDamage()) {
event.setCancelled(true);
}
plugin.getPlayerManager().handleDamageCheck(result);
}
}
@@ -0,0 +1,76 @@
package me.youhavetrouble.preventstabby.listeners;
import me.youhavetrouble.preventstabby.data.Target;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityPlaceEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
/**
* This class is a listener that performs various operations related to tagging entities with player UUIDs.
*/
public class UtilListener implements Listener {
/**
* Tag TNT minecart with uuid of player who placed it
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerPlacedTntMinecart(EntityPlaceEvent event) {
if (!(event.getEntity() instanceof ExplosiveMinecart minecart)) return;
if (event.getPlayer() == null) return;
Target.assignPlayerSourceId(minecart, event.getPlayer().getUniqueId());
}
/**
* Tag TNT minecart with uuid of player who last nudged it
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerNudgedTntMinecart(VehicleEntityCollisionEvent event) {
if (!(event.getVehicle() instanceof ExplosiveMinecart minecart)) return;
if (!(event.getEntity() instanceof Player player)) return;
Target.assignPlayerSourceId(minecart, player.getUniqueId());
}
/**
* Tag primed TNT with players uuid
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerPrimedTnt(ExplosionPrimeEvent event) {
if (!(event.getEntity() instanceof TNTPrimed tntPrimed)) return;
if (tntPrimed.getSource() instanceof TNTPrimed primingTnt) {
Target primingTntTarget = Target.getTarget(primingTnt);
if (primingTntTarget == null) return;
Target.assignPlayerSourceId(tntPrimed, primingTntTarget.playerUuid);
return;
}
if (tntPrimed.getSource() instanceof Player primingPlayer) {
Target.assignPlayerSourceId(tntPrimed, primingPlayer.getUniqueId());
return;
}
}
/**
* Tags ender crystal with exploding players uuid
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitEnderCrystal(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof EnderCrystal enderCrystal)) return;
if (event.getDamager() instanceof Player player) {
Target.assignPlayerSourceId(enderCrystal, player.getUniqueId());
return;
}
if (event.getDamager() instanceof Projectile projectile && projectile.getShooter() instanceof Player player) {
Target.assignPlayerSourceId(enderCrystal, player.getUniqueId());
return;
}
}
}
@@ -1,27 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.mount;
import me.youhavetrouble.preventstabby.util.Util;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import java.util.UUID;
@PreventStabbyListener
public class MountHitByExplosionListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onMountHitByExplosion(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return;
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
UUID damager = event.getDamager().getUniqueId();
Entity mount = event.getEntity();
if (Util.processMountAttack(damager, mount))
event.setCancelled(true);
}
}
@@ -1,30 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.mount;
import me.youhavetrouble.preventstabby.util.Util;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import java.util.UUID;
@PreventStabbyListener
public class MountHitByFireworkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onMountHitByFireWork(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Firework) || event.getEntity().getPassengers().isEmpty()) return;
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
Firework firework = (Firework) event.getDamager();
if (!(firework.getShooter() instanceof Player)) return;
UUID damager = ((Player) firework.getShooter()).getUniqueId();
Entity mount = event.getEntity();
if (Util.processMountAttack(damager, mount))
event.setCancelled(true);
}
}
@@ -1,40 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.mount;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.Util;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.potion.PotionEffect;
import java.util.UUID;
@PreventStabbyListener
public class MountHitBySplashPotionListener implements Listener {
/**
* If thrown potion applies negative effects and it's thrown by a player
* it will have no effect on a pet of a player with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onMountHitBySplashPotion(org.bukkit.event.entity.PotionSplashEvent event) {
if (!(event.getEntity().getShooter() instanceof Player)) return;
boolean harmful = false;
for (PotionEffect effect : event.getPotion().getEffects()) {
if (Util.isPotionEffectHarmful(effect.getType())) {
harmful = true;
break;
}
}
if (!harmful) return;
UUID damager = ((Player) event.getEntity().getShooter()).getUniqueId();
for (LivingEntity entity : event.getAffectedEntities()) {
if (entity.getPassengers().isEmpty()) continue;
if (Util.processMountAttack(damager, entity))
event.setIntensity(entity, 0);
}
}
}
@@ -1,25 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.mount;
import me.youhavetrouble.preventstabby.util.Util;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerAttackMountListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return;
Entity entity = event.getEntity();
UUID damager = event.getDamager().getUniqueId();
if (Util.processMountAttack(damager, entity))
event.setCancelled(true);
}
}
@@ -1,28 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.mount;
import me.youhavetrouble.preventstabby.util.Util;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitMountWithProjectileListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitMountWithProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Projectile)) return;
Projectile projectile = (Projectile) event.getDamager();
if (!(projectile.getShooter() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return;
Entity entity = event.getEntity();
UUID damager = event.getDamager().getUniqueId();
if (Util.processMountAttack(damager, entity))
event.setCancelled(true);
}
}
@@ -1,40 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import java.util.UUID;
@PreventStabbyListener
public class PetHitByExplosionListener implements Listener {
/**
* Cancels explosion damage for pets with pvp off that is caused by players
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetHitByExplosion(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Tameable)) return;
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return;
UUID victim = tameable.getOwner().getUniqueId();
try {
UUID damager = UUID.fromString(event.getDamager().getMetadata("PLAYEREXPLODED").get(0).asString());
if (victim.equals(damager))
return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
} catch (NullPointerException | IndexOutOfBoundsException ignored) {}
}
}
@@ -1,35 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PetHitByFireworkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetFireworkDamage(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Firework && event.getEntity() instanceof Tameable) {
Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return;
Firework firework = (Firework) event.getDamager();
if (!(firework.getShooter() instanceof Player)) return;
UUID damager = ((Player) firework.getShooter()).getUniqueId();
UUID victim = tameable.getOwner().getUniqueId();
if (victim.equals(damager)) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
@@ -1,53 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.Util;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.UUID;
@PreventStabbyListener
public class PetHitBySplashPotionListener implements Listener {
/**
* If thrown potion applies negative effects and it's thrown by a player
* it will have no effect on a pet of a player with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetHitBySplashPotion(org.bukkit.event.entity.PotionSplashEvent event) {
if (!(event.getEntity().getShooter() instanceof Player)) return;
boolean harmful = false;
for (PotionEffect effect : event.getPotion().getEffects()) {
if (Util.isPotionEffectHarmful(effect.getType())) {
harmful = true;
break;
}
}
if (!harmful) return;
UUID damager = ((Player) event.getEntity().getShooter()).getUniqueId();
for (Entity entity : event.getAffectedEntities()) {
if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
if (tameable.getOwner() == null) continue;
UUID victim = tameable.getOwner().getUniqueId();
if (victim == damager) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
@@ -1,32 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PetLeashListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetLeash(org.bukkit.event.entity.PlayerLeashEntityEvent event) {
if (event.getEntity() instanceof Tameable) {
Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return;
UUID damager = event.getPlayer().getUniqueId();
UUID victim = tameable.getOwner().getUniqueId();
if (victim == damager) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
@@ -1,38 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.Util;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class PetTargettingMountListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWolfAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Tameable) || event.getEntity().getPassengers().isEmpty()) return;
Tameable damager = (Tameable) event.getDamager();
Entity victim = event.getEntity();
if (damager.getOwner() == null) return;
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
boolean damagerPvpEnabled = smartCache.getPlayerData(damager.getOwner().getUniqueId()).isPvpEnabled();
boolean victimPvpEnabled = !Util.processMountAttack(damager.getOwner().getUniqueId(), victim);
if (!victimPvpEnabled || !damagerPvpEnabled) {
if (damager instanceof Wolf) {
Wolf wolf = (Wolf) damager;
wolf.setAngry(false);
}
event.setCancelled(true);
}
}
}
@@ -1,36 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class PetTargettingPetListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWolfAttackWolf(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Tameable && event.getEntity() instanceof Tameable) {
Tameable damager = (Tameable) event.getDamager();
Tameable victim = (Tameable) event.getEntity();
if (damager.getOwner() == null || victim.getOwner() == null) return;
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
boolean damagerPvpEnabled = smartCache.getPlayerData(damager.getOwner().getUniqueId()).isPvpEnabled();
boolean victimPvpEnabled = smartCache.getPlayerData(victim.getOwner().getUniqueId()).isPvpEnabled();
if (!victimPvpEnabled || !damagerPvpEnabled) {
if (damager instanceof Wolf) {
Wolf wolf = (Wolf) damager;
wolf.setAngry(false);
}
event.setCancelled(true);
}
}
}
}
@@ -1,35 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PetTargettingPlayerListener implements Listener {
/**
* Stops pets with owners targetting players with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetTargetPlayer(org.bukkit.event.entity.EntityTargetEvent event) {
if (!(event.getEntity() instanceof Tameable)) return;
Tameable entity = (Tameable) event.getEntity();
if (!(entity.getOwner() instanceof Player)) return;
if (!(event.getTarget() instanceof Player)) return;
UUID damager = entity.getOwner().getUniqueId();
UUID victim = event.getTarget().getUniqueId();
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
@@ -1,49 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerAttackPetListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackPet(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player && event.getEntity() instanceof Tameable) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return;
UUID damager = event.getDamager().getUniqueId();
UUID victim = tameable.getOwner().getUniqueId();
if (damager.equals(victim)) return;
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
boolean damagerPvpState = PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(damager);
if (!damagerPvpState) {
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_attacker());
event.setCancelled(true);
return;
}
if (!smartCache.getPlayerData(victim).isPvpEnabled()) {
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_victim());
event.setCancelled(true);
return;
}
CombatTimer.refreshPlayersCombatTime(damager);
}
}
}
@@ -1,54 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitPetWithProjectileListener implements Listener {
/**
* Cancels damage done by projectiles to pets of players with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitPetWithProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Tameable && event.getDamager() instanceof Projectile) {
Projectile projectile = (Projectile) event.getDamager();
if (!(projectile.getShooter() instanceof Player)) return;
Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return;
UUID damager = ((Player) projectile.getShooter()).getUniqueId();
UUID victim = tameable.getOwner().getUniqueId();
if (damager.equals(victim)) return;
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (!smartCache.getPlayerData(damager).isPvpEnabled()) {
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_attacker());
event.setCancelled(true);
return;
}
if (!smartCache.getPlayerData(victim).isPvpEnabled()) {
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_victim());
event.setCancelled(true);
return;
}
CombatTimer.refreshPlayersCombatTime(damager);
}
}
}
@@ -1,26 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class PlayerInteractWithPetListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteractWithPet(org.bukkit.event.player.PlayerInteractEntityEvent event) {
if (!PreventStabby.getPlugin().getConfigCache().isOnly_owner_can_interact_with_pet()) return;
if (!(event.getRightClicked() instanceof Tameable)) return;
Tameable tameable = (Tameable) event.getRightClicked();
if (tameable.getOwner() == null) return;
if (tameable.getOwner().getUniqueId().equals(event.getPlayer().getUniqueId())) return;
event.setCancelled(true);
}
}
@@ -1,47 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerManager;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PetAttackPlayerListener implements Listener {
/**
* Pets stop following player with pvp off after trying to hit them
* This is to fix any inconsistancy with pet behavior
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetAttack(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Tameable)) return;
Tameable entity = (Tameable) event.getDamager();
if (entity.getOwner() != null && event.getEntity() instanceof Player) {
UUID victim = event.getEntity().getUniqueId();
UUID damager = entity.getOwner().getUniqueId();
PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
if (!playerManager.canDamage(damager, victim, false)) {
if (entity instanceof Wolf) {
Wolf wolf = (Wolf) entity;
wolf.setAngry(false);
}
event.setCancelled(true);
return;
}
CombatTimer.refreshPlayersCombatTime(damager, victim);
}
}
}
@@ -1,35 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerAttackListener implements Listener {
/**
* Cancels basic attacks done to player with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttack(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
Entity damagerEntity = event.getDamager();
Entity victimEntity = event.getEntity();
if (damagerEntity instanceof Player && victimEntity instanceof Player) {
UUID damager = damagerEntity.getUniqueId();
UUID victim = victimEntity.getUniqueId();
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
@@ -1,27 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class PlayerDeathListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDeath(org.bukkit.event.entity.EntityDeathEvent event) {
if (!(event.getEntity() instanceof Player)) return;
Player player = (Player) event.getEntity();
PlayerData playerData = PreventStabby.getPlugin().getSmartCache().getPlayerData(player.getUniqueId());
playerData.setCombattime(0);
playerData.setLastCombatCheck(false);
playerData.setInCombat(false);
}
}
@@ -1,109 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitByExplosionListener implements Listener {
/**
* Cancels explosion damage for players with pvp off that is caused by players
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitByExplosion(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player) {
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
UUID victim = event.getEntity().getUniqueId();
try {
UUID damager = UUID.fromString(event.getDamager().getMetadata("PLAYEREXPLODED").get(0).asString());
if (victim.equals(damager)) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
} catch (NullPointerException | IndexOutOfBoundsException ignored) { }
}
}
/**
* Tags ender crystal with exploder uuid
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitEnderCrystal(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof EnderCrystal) {
EnderCrystal enderCrystal = (EnderCrystal) event.getEntity();
if (event.getDamager() instanceof Player) {
enderCrystal.setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), event.getDamager().getUniqueId().toString()));
} else if (event.getDamager() instanceof Projectile) {
Projectile projectile = (Projectile) event.getDamager();
if (projectile.getShooter() instanceof Player) {
Player damager = (Player) projectile.getShooter();
enderCrystal.setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), damager.getUniqueId().toString()));
}
}
}
}
/**
* Tag ender crystal with destroying players uuid
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerPrimedTnt(org.bukkit.event.entity.ExplosionPrimeEvent event) {
if (event.getEntity() instanceof TNTPrimed) {
TNTPrimed tntPrimed = (TNTPrimed) event.getEntity();
if (tntPrimed.getSource() instanceof Player) {
Player damager = (Player) tntPrimed.getSource();
tntPrimed.setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), damager.getUniqueId().toString()));
} else if (tntPrimed.getSource() instanceof TNTPrimed) {
try {
TNTPrimed sourceTnt = (TNTPrimed) tntPrimed.getSource();
String damagerUuid = sourceTnt.getMetadata("PLAYEREXPLODED").get(0).asString();
tntPrimed.setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), damagerUuid));
} catch (NullPointerException ignored) {
}
}
}
}
/**
* Tag TNT minecart with placing player uuid
*/
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerPlacedTntMinecart(org.bukkit.event.entity.EntityPlaceEvent event) {
if (event.getEntityType().equals(EntityType.MINECART_TNT)) {
if (event.getPlayer() != null) {
event.getEntity().setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), event.getPlayer().getUniqueId().toString()));
}
}
}
/**
* Tag TNT minecart with uuid of player who last nudged it
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerNudgedTntMinecart(org.bukkit.event.vehicle.VehicleEntityCollisionEvent event) {
if (event.getVehicle() instanceof ExplosiveMinecart && event.getEntity() instanceof Player) {
Player damager = (Player) event.getEntity();
event.getVehicle().setMetadata("PLAYEREXPLODED", new FixedMetadataValue(PreventStabby.getPlugin(), damager.getUniqueId().toString()));
}
}
}
@@ -1,34 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitByFireworkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFireworkDamage(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Firework && event.getEntity() instanceof Player) {
UUID victim = event.getEntity().getUniqueId();
Firework firework = (Firework) event.getDamager();
if (firework.getShooter() instanceof Player) {
UUID damager = ((Player) firework.getShooter()).getUniqueId();
if (damager == victim) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
@@ -1,59 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitByProjectileListener implements Listener {
/**
* Cancels damage done by projectiles to player with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player && event.getDamager() instanceof Projectile) {
Projectile projectile = (Projectile) event.getDamager();
if (projectile.getShooter() instanceof Player) {
UUID damager = ((Player) projectile.getShooter()).getUniqueId();
UUID victim = event.getEntity().getUniqueId();
if (PreventStabby.getPlugin().getConfigCache().isSnowballs_knockback() && event.getDamager() instanceof Snowball) {
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true)) {
((Player) event.getEntity()).damage(0.01, (Entity) projectile.getShooter());
CombatTimer.refreshPlayersCombatTime(damager, victim);
} else {
event.setCancelled(true);
return;
}
} else if (PreventStabby.getPlugin().getConfigCache().isEgg_knockback() && event.getDamager() instanceof Egg) {
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true)) {
((Player) event.getEntity()).damage(0.01, (Entity) projectile.getShooter());
CombatTimer.refreshPlayersCombatTime(damager, victim);
} else {
event.setCancelled(true);
return;
}
}
// Ender pearls and other self-damage
if (damager.equals(victim)) return;
if (event.getDamage() == 0) return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
@@ -1,48 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.Util;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.potion.PotionEffect;
import java.util.UUID;
@PreventStabbyListener
public class PlayerHitBySplashPotionListener implements Listener {
/**
* If thrown potion is applies negative effects and it's thrown by a player it will have no effect on player with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitBySplashPotion(org.bukkit.event.entity.PotionSplashEvent event) {
if (!(event.getEntity().getShooter() instanceof Player)) return;
boolean harmful = false;
for (PotionEffect effect : event.getPotion().getEffects()) {
if (Util.isPotionEffectHarmful(effect.getType())) {
harmful = true;
break;
}
}
if (!harmful) return;
UUID damager = ((Player) event.getEntity().getShooter()).getUniqueId();
for (LivingEntity entity : event.getAffectedEntities()) {
if (!(entity instanceof Player)) continue;
UUID victim = entity.getUniqueId();
if (damager == victim) continue;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true)) {
CombatTimer.refreshPlayersCombatTime(damager, victim);
} else {
event.setIntensity(entity, 0);
}
}
}
}
@@ -1,63 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.time.Instant;
import java.util.UUID;
@PreventStabbyListener
public class PlayerJoinAndLeaveListener implements Listener {
/**
* This event is here to get players saved options on join
*/
@EventHandler(ignoreCancelled = true)
public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
long time = Instant.now().getEpochSecond();
if (playerData == null) {
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, new PlayerData(uuid,false));
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
PlayerData data = PreventStabby.getPlugin().getSqLite().getPlayerInfo(uuid);
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, data);
data.setLoginTimestamp(time);
});
return;
}
playerData.refreshCachetime();
playerData.setLoginTimestamp(time);
}
/**
* This event is here to save player's data to database
* Also punishes players who log out during combat
*/
@EventHandler
public void onPlayerLeave(org.bukkit.event.player.PlayerQuitEvent event) {
Player player = event.getPlayer();
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> PreventStabby.getPlugin().getSqLite().updatePlayerInfo(player.getUniqueId(), PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId())));
if (!PreventStabby.getPlugin().getConfigCache().isPunish_for_combat_logout()) return;
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
PlayerData playerData = smartCache.getPlayerData(player.getUniqueId());
if (!playerData.isInCombat()) return;
player.setHealth(0);
if (PreventStabby.getPlugin().getConfigCache().isPunish_for_combat_logout_announce())
PluginMessages.broadcastMessage(player, PreventStabby.getPlugin().getConfigCache().getPunish_for_combat_logout_message());
}
}
@@ -1,24 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.player;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.time.Instant;
@PreventStabbyListener
public class PlayerTeleportListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerTeleport(org.bukkit.event.player.PlayerTeleportEvent event) {
Player player = event.getPlayer();
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
PlayerData playerData = smartCache.getPlayerData(player.getUniqueId());
playerData.setTeleportTimestamp(Instant.now().getEpochSecond());
}
}
@@ -1,38 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.toggles;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerManager;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class CombatCommandListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommandInCombat(org.bukkit.event.player.PlayerCommandPreprocessEvent event) {
if (!PreventStabby.getPlugin().getConfigCache().isBlock_commands_in_combat())
return;
if (event.getPlayer().hasPermission("toglepvp.combatcommandblock.bypass"))
return;
PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
if (!playerManager.getPlayer(event.getPlayer().getUniqueId()).isInCombat())
return;
String command = event.getMessage().replaceFirst("/", "");
if (!PreventStabby.getPlugin().getConfigCache().getCombatBlockedCommands().contains(command))
return;
event.setCancelled(true);
PluginMessages.sendMessage(event.getPlayer(), PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
}
}
@@ -1,33 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.toggles;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerManager;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class PlayerTeleportInCombatListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerTeleportInCombat(org.bukkit.event.player.PlayerTeleportEvent event) {
if (!PreventStabby.getPlugin().getConfigCache().isBlock_teleports_in_combat())
return;
PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
if (!playerManager.getPlayer(event.getPlayer().getUniqueId()).isInCombat())
return;
if (event.getPlayer().hasPermission("toglepvp.combatteleportblock.bypass"))
return;
event.setCancelled(true);
PluginMessages.sendMessage(event.getPlayer(), PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
}
}
@@ -1,75 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerManager;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.AreaEffectCloudApplyEvent;
import org.bukkit.potion.PotionEffectType;
import java.util.Iterator;
import java.util.UUID;
@PreventStabbyListener
public class AreaEffectCloudApplyListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onCloudEffects(AreaEffectCloudApplyEvent event) {
PotionEffectType potionEffectType = event.getEntity().getBasePotionData().getType().getEffectType();
if (potionEffectType == null)
return;
if(event.getEntity().getSource() instanceof Player) {
if (potionEffectType.equals(PotionEffectType.BLINDNESS) ||
potionEffectType.equals(PotionEffectType.CONFUSION) ||
potionEffectType.equals(PotionEffectType.HARM) ||
potionEffectType.equals(PotionEffectType.HUNGER) ||
potionEffectType.equals(PotionEffectType.POISON) ||
potionEffectType.equals(PotionEffectType.SLOW_DIGGING) ||
potionEffectType.equals(PotionEffectType.WEAKNESS) ||
potionEffectType.equals(PotionEffectType.SLOW) ||
potionEffectType.equals(PotionEffectType.WITHER)) {
PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
Iterator<LivingEntity> it = event.getAffectedEntities().iterator();
UUID damager = ((Player) event.getEntity().getSource()).getUniqueId();
while(it.hasNext()) {
LivingEntity entity = it.next();
if(entity instanceof Player) {
UUID victim = entity.getUniqueId();
if (damager == victim)
continue;
if (playerManager.canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
it.remove();
} else if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
if (tameable.getOwner() == null)
continue;
UUID victim = tameable.getOwner().getUniqueId();
if (victim == damager)
continue;
if (playerManager.canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
it.remove();
}
}
}
}
}
}
@@ -1,61 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.UUID;
/**
* Listen for lightning strikes and tag the trident spawned ones.
* Idea from aasmus' PvPToggle plugin
*/
@PreventStabbyListener
public class EntityHitByLightningListener implements Listener {
/**
* Cancels damage from lightning strike caused by channeling for players with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerLightningDamage(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof LightningStrike && event.getDamager().getMetadata("TRIDENT").size() >= 1) {
if (event.getEntity() instanceof Player) {
UUID victim = event.getEntity().getUniqueId();
if (PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(victim)) {
event.setCancelled(true);
return;
}
if (!PreventStabby.getPlugin().getSmartCache().getPlayerData(victim).isPvpEnabled()) {
event.setCancelled(true);
}
} else if (event.getEntity() instanceof Tameable) {
Tameable victim = (Tameable) event.getEntity();
if (victim.getOwner() != null && !PreventStabby.getPlugin().getSmartCache().getPlayerData(victim.getOwner().getUniqueId()).isPvpEnabled()) {
event.setCancelled(true);
}
}
}
}
/**
* Tags the lightning strike
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event){
if(event.getCause() == LightningStrikeEvent.Cause.TRIDENT){
if (PreventStabby.getPlugin().getConfigCache().isChanneling_enchant_disabled()) {
event.setCancelled(true);
return;
}
event.getLightning().setMetadata("TRIDENT", new FixedMetadataValue(PreventStabby.getPlugin(), event.getLightning().getLocation()));
}
}
}
@@ -1,49 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.UUID;
@PreventStabbyListener
public class FishingListener implements Listener {
/**
* Prevents hooking players with disabled pvp with fishing rod
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFish(org.bukkit.event.player.PlayerFishEvent event) {
if (event.getCaught() instanceof Player) {
if (!PreventStabby.getPlugin().getConfigCache().isAllow_fishing_rod_pull()) return;
UUID damager = event.getPlayer().getUniqueId();
UUID victim = event.getCaught().getUniqueId();
if (damager == victim)
return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
} else if (event.getCaught() instanceof Tameable) {
Tameable tameable = (Tameable) event.getCaught();
UUID damager = event.getPlayer().getUniqueId();
if (tameable.getOwner() == null)
return;
UUID victim = tameable.getOwner().getUniqueId();
if (damager == victim)
return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
@@ -1,125 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.util.BoundingBoxUtil;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.util.BoundingBox;
import java.util.UUID;
@PreventStabbyListener
public class LavaDumpAndIgniteListener implements Listener {
/**
* Prevents dumping lava and pufferfish bucket near players with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLavaDump(org.bukkit.event.player.PlayerBucketEmptyEvent event) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
if (!config.isLava_and_fire_stopper_enabled())
return;
if (event.getBucket().equals(Material.LAVA_BUCKET) || event.getBucket().equals(Material.PUFFERFISH_BUCKET)) {
Location location = event.getBlockClicked().getLocation();
UUID damager = event.getPlayer().getUniqueId();
double radius = config.getLava_and_fire_stopper_radius();
BoundingBox boundingBox = BoundingBoxUtil.getBoundingBox(location, radius);
for (Entity entity : location.getWorld().getNearbyEntities(boundingBox)) {
if (entity instanceof Player) {
UUID victim = entity.getUniqueId();
if (victim != damager) {
if (PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(victim, damager)) {
event.setCancelled(true);
return;
}
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
} else if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
if (tameable.getOwner() == null) {
return;
}
UUID victim = tameable.getOwner().getUniqueId();
if (PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(victim, damager)) {
event.setCancelled(true);
return;
}
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
/**
* Prevents setting blocks on fire near players with pvp off
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onIgnite(org.bukkit.event.block.BlockIgniteEvent event) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
if (!config.isLava_and_fire_stopper_enabled())
return;
if (event.getPlayer() == null)
return;
Location location = event.getBlock().getLocation();
UUID damager = event.getPlayer().getUniqueId();
double radius = config.getLava_and_fire_stopper_radius();
BoundingBox boundingBox = BoundingBoxUtil.getBoundingBox(location, radius);
for (Entity entity : location.getWorld().getNearbyEntities(boundingBox)) {
if (entity instanceof Player) {
UUID victim = entity.getUniqueId();
if (victim == damager)
continue;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
} else if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
if (tameable.getOwner() == null) {
continue;
}
UUID victim = tameable.getOwner().getUniqueId();
if (victim == damager)
continue;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
@@ -1,50 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@PreventStabbyListener
public class LightningBlockIgniteListener implements Listener {
/**
* Lightning strikes from channeling enchant won't ignite blocks if player with pvp off is in radius
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockIgnite(org.bukkit.event.block.BlockIgniteEvent event) {
if (event.getIgnitingEntity() instanceof LightningStrike && event.getIgnitingEntity().getMetadata("TRIDENT").size() >= 1) {
LightningStrike lightningStrike = (LightningStrike) event.getIgnitingEntity();
for (Entity entity : lightningStrike.getNearbyEntities(2,2,2)) {
if (entity instanceof Player) {
Player victim = (Player) entity;
if (PreventStabby.getPlugin().getPlayerManager().hasLoginProtection(victim.getUniqueId())) {
event.setCancelled(true);
return;
}
if (!PreventStabby.getPlugin().getSmartCache().getPlayerData(victim.getUniqueId()).isPvpEnabled()) {
event.setCancelled(true);
return;
}
} else if (entity instanceof Tameable) {
Tameable victim = (Tameable) entity;
if (victim.getOwner() == null) {
return;
}
if (!PreventStabby.getPlugin().getSmartCache().getPlayerData(victim.getOwner().getUniqueId()).isPvpEnabled()) {
event.setCancelled(true);
return;
}
}
}
}
}
}
@@ -1,64 +0,0 @@
package me.youhavetrouble.preventstabby.listeners.unspecific;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.util.BoundingBoxUtil;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.util.BoundingBox;
import java.util.UUID;
@PreventStabbyListener
public class PlaceWitherRoseListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerWitherRosePlace(org.bukkit.event.block.BlockPlaceEvent event) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
if (!config.isLava_and_fire_stopper_enabled())
return;
if (event.getBlock().getType().equals(Material.WITHER_ROSE)) {
Location location = event.getBlockPlaced().getLocation();
double radius = config.getLava_and_fire_stopper_radius();
BoundingBox boundingBox = BoundingBoxUtil.getBoundingBox(location, radius);
for (Entity entity : location.getWorld().getNearbyEntities(boundingBox)) {
if (entity instanceof Player) {
UUID damager = event.getPlayer().getUniqueId();
UUID victim = entity.getUniqueId();
if (victim == damager)
return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
} else if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
UUID damager = event.getPlayer().getUniqueId();
if (tameable.getOwner() == null)
return;
UUID victim = tameable.getOwner().getUniqueId();
if (victim == damager)
return;
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false))
CombatTimer.refreshPlayersCombatTime(damager, victim);
else
event.setCancelled(true);
}
}
}
}
}
@@ -1,87 +0,0 @@
package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby;
import java.time.Instant;
import java.util.UUID;
public class PlayerData {
private final UUID playerUuid;
private long cachetime, combattime, loginTimestamp, teleportTimestamp;
private boolean pvpEnabled, lastCombatCheck, inCombat;
public PlayerData(UUID playerUuid, boolean pvpEnabled) {
this.playerUuid = playerUuid;
this.pvpEnabled = pvpEnabled;
this.combattime = Instant.now().getEpochSecond()-1;
this.loginTimestamp = Instant.now().getEpochSecond()-1;
this.teleportTimestamp = Instant.now().getEpochSecond()-1;
this.inCombat = false;
refreshCachetime();
}
public UUID getPlayerUuid() {
return playerUuid;
}
public boolean isPvpEnabled() {
return pvpEnabled;
}
public void setPvpEnabled(boolean pvpEnabled) {
this.pvpEnabled = pvpEnabled;
}
public long getCachetime() {
return cachetime;
}
public void refreshCachetime() {
this.cachetime = Instant.now().getEpochSecond()+ PreventStabby.getPlugin().getConfigCache().getCache_time();
}
public long getCombattime() {
return combattime;
}
public void setCombattime(long combattime) {
this.combattime = combattime;
}
public void refreshCombatTime() {
this.combattime = Instant.now().getEpochSecond()+ PreventStabby.getPlugin().getConfigCache().getCombat_time();
}
public boolean getLastCombatCheck() {
return lastCombatCheck;
}
public void setLastCombatCheck(boolean bool) {
lastCombatCheck = bool;
}
public void setLoginTimestamp(long loginTimestamp) {
this.loginTimestamp = loginTimestamp + PreventStabby.getPlugin().getConfigCache().getLogin_protection_time()-1;
}
public long getLoginTimestamp() {
return loginTimestamp;
}
public void setTeleportTimestamp(long teleportTimestamp) {
this.teleportTimestamp = teleportTimestamp + PreventStabby.getPlugin().getConfigCache().getTeleport_protection_time()-1;
}
public long getTeleportTimestamp() {
return teleportTimestamp;
}
public boolean isInCombat() {
return inCombat;
}
public void setInCombat(boolean inCombat) {
this.inCombat = inCombat;
}
}
@@ -1,176 +0,0 @@
package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.api.event.PlayerLeaveCombatEvent;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.hooks.WorldGuardHook;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import lombok.Getter;
import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerManager {
@Getter
ConcurrentHashMap<UUID, PlayerData> playerList = new ConcurrentHashMap<>();
private PvpState pvpForcedState = PvpState.NONE;
public final BukkitTask combatTrackerTask;
public PlayerManager() {
for (Player p : Bukkit.getOnlinePlayers()) {
PlayerData playerData = PreventStabby.getPlugin().getSqLite().getPlayerInfo(p.getUniqueId());
playerList.put(p.getUniqueId(), playerData);
}
combatTrackerTask = Bukkit.getScheduler().runTaskTimerAsynchronously(PreventStabby.getPlugin(), () -> {
for (PlayerData playerData : playerList.values()) {
UUID uuid = playerData.getPlayerUuid();
if (!CombatTimer.isInCombat(uuid)) {
if (playerData.getLastCombatCheck()) {
Player player = Bukkit.getPlayer(uuid);
if (player == null) continue;
PlayerLeaveCombatEvent playerLeaveCombatEvent = new PlayerLeaveCombatEvent(player);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(playerLeaveCombatEvent);
if (playerLeaveCombatEvent.isCancelled()) {
playerData.refreshCombatTime();
return;
}
playerData.setLastCombatCheck(false);
playerData.setInCombat(false);
PluginMessages.sendActionBar(uuid, PreventStabby.getPlugin().getConfigCache().getLeaving_combat());
});
}
} else {
playerData.setLastCombatCheck(true);
}
}
}, 20, 20);
}
public void refreshPlayersCacheTime(UUID uuid) {
playerList.get(uuid).refreshCachetime();
}
public void refreshPlayersCombatTime(UUID uuid) {
PlayerData data = playerList.get(uuid);
if (data == null) return;
Player player = Bukkit.getPlayer(uuid);
if (player == null || player.isDead()) return;
data.refreshCombatTime();
data.setInCombat(true);
}
public PlayerData getPlayer(UUID uuid) {
return playerList.get(uuid);
}
public void addPlayer(UUID uuid, PlayerData data) {
playerList.put(uuid, data);
}
public boolean getPlayerPvPState(UUID uuid) {
return PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).isPvpEnabled();
}
public void setPlayerPvpState(UUID uuid, boolean state) {
PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).setPvpEnabled(state);
}
public boolean togglePlayerPvpState(UUID uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (smartCache.getPlayerData(uuid).isPvpEnabled()) {
smartCache.getPlayerData(uuid).setPvpEnabled(false);
return false;
} else {
smartCache.getPlayerData(uuid).setPvpEnabled(true);
return true;
}
}
public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage) {
return canDamage(attacker, victim, sendDenyMessage, true);
}
public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage, boolean checkVictimSpawnProtection) {
if (hasLoginProtection(attacker) || hasTeleportProtection(attacker)) return false;
if (checkVictimSpawnProtection && hasLoginProtection(victim)) return false;
if (checkVictimSpawnProtection && hasTeleportProtection(victim)) return false;
switch (pvpForcedState) {
case ENABLED:
return true;
case DISABLED:
PluginMessages.sendActionBar(attacker, PreventStabby.getPlugin().getConfigCache().getCannot_attack_pvp_force_off());
return false;
case NONE:
default:
break;
}
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (!smartCache.getPlayerData(attacker).isPvpEnabled()) {
Player attackerPlayer = Bukkit.getPlayer(attacker);
if (PreventStabby.worldGuardHookEnabled() && attackerPlayer != null && WorldGuardHook.isPlayerForcedToPvp(attackerPlayer))
return true;
if (sendDenyMessage) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
PluginMessages.sendActionBar(attacker, config.getCannot_attack_attacker());
}
return false;
}
if (!smartCache.getPlayerData(victim).isPvpEnabled()) {
Player victimPlayer = Bukkit.getPlayer(victim);
if (PreventStabby.worldGuardHookEnabled() && victimPlayer != null && WorldGuardHook.isPlayerForcedToPvp(victimPlayer))
return true;
if (sendDenyMessage) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
PluginMessages.sendActionBar(attacker, config.getCannot_attack_victim());
}
return false;
}
return true;
}
/**
* @param uuid Player UUIDs
* @return true if any of the provided UUIDs has spawn protection
*/
public boolean hasLoginProtection(UUID... uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
for (UUID checkedUuid : uuid) {
if (Instant.now().getEpochSecond() < smartCache.getPlayerData(checkedUuid).getLoginTimestamp())
return true;
}
return false;
}
public boolean hasTeleportProtection(UUID uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
return Instant.now().getEpochSecond() < smartCache.getPlayerData(uuid).getTeleportTimestamp();
}
public PvpState getForcedPvpState() {
return pvpForcedState;
}
public void setForcedPvpState(PvpState forcedPvpState) {
this.pvpForcedState = forcedPvpState;
}
}
@@ -1,60 +0,0 @@
package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
public class SmartCache {
public void runSmartCache() {
Bukkit.getScheduler().runTaskTimerAsynchronously(PreventStabby.getPlugin(), () -> {
// Refresh cache timer if player is online
for (Map.Entry<UUID, PlayerData> e : PreventStabby.getPlugin().getPlayerManager().getPlayerList().entrySet()) {
try {
Player player = Bukkit.getPlayer(e.getKey());
if (player != null && player.isOnline()) {
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCacheTime(e.getKey());
}
} catch (NullPointerException ignored) {}
}
// Check for entries that should be invalidated
try {
long now = Instant.now().getEpochSecond();
PreventStabby.getPlugin().getPlayerManager().getPlayerList().entrySet()
.removeIf(cacheEntry -> cacheEntry.getValue().getCachetime() < now);
} catch (Exception ignored) {}
}, 100, 100);
}
public PlayerData getPlayerData(UUID uuid) {
// Try to get data from cache and refresh it
try {
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCacheTime(uuid);
return PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid);
} catch (NullPointerException e) {
// If player data is not in cache get it from database and put into cache
try {
PlayerData playerData = PreventStabby.getPlugin().getSqLite().getPlayerInfo(uuid);
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, playerData);
return playerData;
} catch (NullPointerException ex) {
// Return false if database call fails
return new PlayerData(uuid,false);
}
}
}
public void setPlayerPvpState(UUID uuid, boolean state) {
// If player is in cache update that
if (PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid) != null) {
PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).setPvpEnabled(state);
}
// Update the database aswell
PreventStabby.getPlugin().getSqLite().updatePlayerInfo(uuid, new PlayerData(uuid, state));
}
}
@@ -1,22 +0,0 @@
package me.youhavetrouble.preventstabby.util;
import org.bukkit.Location;
import org.bukkit.util.BoundingBox;
public class BoundingBoxUtil {
public static BoundingBox getBoundingBox(Location location, double radius) {
double x1 = location.getX()+radius;
double y1 = location.getY()+radius;
double z1 = location.getZ()+radius;
double x2 = location.getX()-radius;
double y2 = location.getY()-radius;
double z2 = location.getZ()-radius;
return new BoundingBox(x1, y1, z1, x2, y2, z2);
}
}
@@ -1,47 +0,0 @@
package me.youhavetrouble.preventstabby.util;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.api.event.PlayerEnterCombatEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.time.Instant;
import java.util.UUID;
public class CombatTimer {
public static void refreshPlayersCombatTime(UUID uuid) {
try {
long now = Instant.now().getEpochSecond();
long combattime = PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).getCombattime();
Player player = Bukkit.getPlayer(uuid);
if (player == null || !player.isOnline()) return;
PlayerEnterCombatEvent playerEnterCombatEvent = new PlayerEnterCombatEvent(player);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(playerEnterCombatEvent);
if (playerEnterCombatEvent.isCancelled()) return;
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCombatTime(uuid);
if (combattime <= now) {
PluginMessages.sendActionBar(uuid, PreventStabby.getPlugin().getConfigCache().getEntering_combat());
}
});
} catch (Exception ignored) {
}
}
public static void refreshPlayersCombatTime(UUID... uuid) {
for (UUID id : uuid) {
refreshPlayersCombatTime(id);
}
}
public static boolean isInCombat(UUID uuid) {
try {
return PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).getCombattime() >= Instant.now().getEpochSecond();
} catch (Exception e) {
return false;
}
}
}
@@ -1,94 +1,73 @@
package me.youhavetrouble.preventstabby.util; package me.youhavetrouble.preventstabby.util;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData; import me.youhavetrouble.preventstabby.data.PlayerData;
import java.io.File; import java.io.File;
import java.sql.*; import java.sql.*;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger;
public class DatabaseSQLite { public class DatabaseSQLite {
private final String url; private final String url;
private final File folder; private final File folder;
private final Logger logger;
public DatabaseSQLite(String url, File folder) { public DatabaseSQLite(String url, File folder, Logger logger) {
this.url = url; this.url = url;
this.folder = folder; this.folder = folder;
this.logger = logger;
createDatabaseFile();
} }
public boolean createDatabaseFile() { private void createDatabaseFile() {
this.folder.mkdir(); this.folder.mkdir();
try (Connection conn = DriverManager.getConnection(url)) { try (Connection conn = DriverManager.getConnection(url)) {
if (conn != null) { if (conn == null) return;
DatabaseMetaData meta = conn.getMetaData(); DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName()); logger.info("The driver name is " + meta.getDriverName());
Statement statement = conn.createStatement(); Statement statement = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS `players` (`player_uuid` varchar(36) UNIQUE PRIMARY KEY, `pvpenabled` boolean);"; String sql = "CREATE TABLE IF NOT EXISTS `players` (`player_uuid` varchar(36) UNIQUE PRIMARY KEY, `pvpenabled` boolean);";
statement.execute(sql); statement.execute(sql);
conn.close(); } catch (SQLException exception) {
} logger.warning(exception.getMessage());
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
} }
return true;
}
public boolean testConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
if (conn != null) {
conn.close();
return true;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return false;
} }
public PlayerData getPlayerInfo(UUID uuid) { public PlayerData getPlayerInfo(UUID uuid) {
try { try (Connection conn = DriverManager.getConnection(url)) {
Connection conn = DriverManager.getConnection(url); PreparedStatement statement = conn.prepareStatement(
Statement insertnewuser = conn.createStatement(); "INSERT OR IGNORE INTO `players` (player_uuid, pvpenabled) VALUES (?, ?);"
try { );
String newuserdata = "INSERT OR IGNORE INTO `players` (player_uuid, pvpenabled) VALUES ('" + uuid.toString() + "', " + PreventStabby.getPlugin().getConfigCache().isPvp_enabled_by_default() + ")"; statement.setString(1, uuid.toString());
insertnewuser.execute(newuserdata); statement.setBoolean(2, PreventStabby.getPlugin().getConfigCache().pvp_enabled_by_default);
} catch (SQLException e) { statement.executeUpdate();
if (e.getErrorCode() != 19) { statement = conn.prepareStatement("SELECT * FROM `players` WHERE `player_uuid` = ?;");
e.printStackTrace(); statement.setString(1, uuid.toString());
} statement.executeQuery();
} ResultSet result = statement.executeQuery();
Statement statement = conn.createStatement();
String sql = "SELECT * FROM `players` WHERE `player_uuid` = '" + uuid + "';";
statement.execute(sql);
ResultSet result = statement.getResultSet();
boolean state = result.getBoolean("pvpenabled"); boolean state = result.getBoolean("pvpenabled");
conn.close();
return new PlayerData(uuid, state); return new PlayerData(uuid, state);
} catch (SQLException throwables) { } catch (SQLException exception) {
throwables.printStackTrace(); logger.warning(exception.getMessage());
} }
return null; return null;
} }
public void updatePlayerInfo(UUID uuid, PlayerData data) { public void updatePlayerInfo(UUID uuid, PlayerData data) {
try { try (Connection conn = DriverManager.getConnection(url)) {
Connection conn = DriverManager.getConnection(url);
Statement insertnewuser = conn.createStatement();
try { try {
String newuserdata = "UPDATE `players` SET pvpenabled = "+data.isPvpEnabled()+" WHERE `player_uuid` = '"+uuid.toString()+"';"; PreparedStatement statement = conn.prepareStatement("UPDATE `players` SET pvpenabled = ? WHERE `player_uuid` = ?;");
insertnewuser.execute(newuserdata); statement.setBoolean(1, data.isPvpEnabled());
} catch (SQLException e) { statement.setString(2, uuid.toString());
PreventStabby.getPlugin().getLogger().severe("Error while saving player data!"); statement.executeUpdate();
e.printStackTrace(); } catch (SQLException exception) {
logger.severe("Error while saving player data!");
logger.warning(exception.getMessage());
} }
} catch (SQLException throwables) { } catch (SQLException exception) {
throwables.printStackTrace(); logger.warning(exception.getMessage());
} }
} }
@@ -2,7 +2,7 @@ package me.youhavetrouble.preventstabby.util;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import net.kyori.adventure.platform.bukkit.BukkitAudiences; import me.youhavetrouble.preventstabby.data.DamageCheckResult;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
@@ -15,7 +15,6 @@ import java.util.UUID;
public class PluginMessages { public class PluginMessages {
public static final MiniMessage MINIMESSAGE = MiniMessage.miniMessage(); public static final MiniMessage MINIMESSAGE = MiniMessage.miniMessage();
private static final BukkitAudiences audiences = PreventStabby.getAudiences();
public static Component parseMessage(String message) { public static Component parseMessage(String message) {
message = makeColorsWork('&', message); message = makeColorsWork('&', message);
@@ -24,9 +23,7 @@ public class PluginMessages {
} }
public static Component parseMessage(CommandSender sender,String message) { public static Component parseMessage(CommandSender sender,String message) {
if (sender instanceof Player player && isPlaceholderApiEnabled()) {
if (sender instanceof Player && isPlaceholderApiEnabled()) {
Player player = (Player) sender;
message = PlaceholderAPI.setPlaceholders(player, message); message = PlaceholderAPI.setPlaceholders(player, message);
} }
return parseMessage(message); return parseMessage(message);
@@ -37,15 +34,18 @@ public class PluginMessages {
} }
public static void sendMessage(CommandSender sender, String message) { public static void sendMessage(CommandSender sender, String message) {
audiences.sender(sender).sendMessage(parseMessage(sender, message)); if ("".equals(message)) return;
sender.sendMessage(parseMessage(sender, message));
} }
public static void sendActionBar(Player player, String message) { public static void sendActionBar(Player player, String message) {
if ("".equals(message)) return;
Component parsedMessage = parseMessage(player, message); Component parsedMessage = parseMessage(player, message);
audiences.player(player).sendActionBar(parsedMessage); player.sendActionBar(parsedMessage);
} }
public static void sendActionBar(UUID uuid, String message) { public static void sendActionBar(UUID uuid, String message) {
if ("".equals(message)) return;
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null) return; if (player == null) return;
sendActionBar(player, message); sendActionBar(player, message);
@@ -57,15 +57,23 @@ public class PluginMessages {
} }
public static void broadcastMessage(Player player, String message) { public static void broadcastMessage(Player player, String message) {
if ("".equals(message)) return;
message = parsePlayerName(player, message); message = parsePlayerName(player, message);
if (PreventStabby.getPlugin().getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { if (PreventStabby.getPlugin().getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
message = PlaceholderAPI.setPlaceholders(player, message); message = PlaceholderAPI.setPlaceholders(player, message);
} }
audiences.all().sendMessage(parseMessage(message)); Bukkit.broadcast(parseMessage(message));
} }
public static void broadcastMessage(String message) { public static void broadcastMessage(String message) {
audiences.all().sendMessage(parseMessage(message)); if ("".equals(message)) return;
Bukkit.broadcast(parseMessage(message));
}
public static void sendOutMessages(DamageCheckResult damageCheckResult) {
if (damageCheckResult.attackerId() != null && damageCheckResult.feedbackForAttacker() != null) {
sendActionBar(damageCheckResult.attackerId(), damageCheckResult.feedbackForAttacker());
}
} }
/** /**
@@ -1,11 +0,0 @@
package me.youhavetrouble.preventstabby.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface PreventStabbyListener {}
@@ -1,73 +0,0 @@
package me.youhavetrouble.preventstabby.util;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class Util {
private static final HashSet<PotionEffectType> harmfulPotions = new HashSet<>();
public static void initData() {
harmfulPotions.add(PotionEffectType.BLINDNESS);
harmfulPotions.add(PotionEffectType.CONFUSION);
harmfulPotions.add(PotionEffectType.HARM);
harmfulPotions.add(PotionEffectType.HUNGER);
harmfulPotions.add(PotionEffectType.POISON);
harmfulPotions.add(PotionEffectType.SLOW_DIGGING);
harmfulPotions.add(PotionEffectType.WEAKNESS);
harmfulPotions.add(PotionEffectType.SLOW);
harmfulPotions.add(PotionEffectType.WITHER);
}
/**
* @param attacker Player attacking the mount
* @param mount Entity being ridden
* @return true if event should be cancelled
*/
public static boolean processMountAttack(UUID attacker, Entity mount) {
// Don't cancel attacks on players that have passengers
if (mount instanceof Player) return false;
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
Set<UUID> playerPassengersWithPvpEnabled = new HashSet<>();
boolean hasPlayerPassengers = false;
for (Entity passenger : mount.getPassengers()) {
if (!(passenger instanceof Player)) continue;
Player player = (Player) passenger;
hasPlayerPassengers = true;
if (PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(player.getUniqueId()))
playerPassengersWithPvpEnabled.add(player.getUniqueId());
}
if (!hasPlayerPassengers) return false;
if (!PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(attacker)) {
PluginMessages.sendActionBar(attacker, config.getCannot_attack_mounts_attacker());
return true;
}
if (playerPassengersWithPvpEnabled.isEmpty()) {
PluginMessages.sendActionBar(attacker, config.getCannot_attack_mounts_victim());
return true;
}
playerPassengersWithPvpEnabled.forEach(CombatTimer::refreshPlayersCombatTime);
CombatTimer.refreshPlayersCombatTime(attacker);
return false;
}
public static boolean isPotionEffectHarmful(PotionEffectType effect) {
return harmfulPotions.contains(effect);
}
}
+15 -1
View File
@@ -2,7 +2,8 @@ name: PreventStabby
version: ${project.version} version: ${project.version}
main: me.youhavetrouble.preventstabby.PreventStabby main: me.youhavetrouble.preventstabby.PreventStabby
authors: [YouHaveTrouble] authors: [YouHaveTrouble]
api-version: 1.13 api-version: 1.20
folia-supported: true
description: Stop people from getting stabbed! description: Stop people from getting stabbed!
soft-depend: soft-depend:
- WorldGuard - WorldGuard
@@ -22,15 +23,28 @@ permissions:
preventstabby.command: preventstabby.command:
default: true default: true
description: Allows usage of /pvp command description: Allows usage of /pvp command
preventstabby.command.help:
default: true
description: Allows usage of /pvp help command
children:
preventstabby.command: true
preventstabby.command.toggle: preventstabby.command.toggle:
default: true default: true
description: Allows usage of /pvp <toggle/enable/disable> command description: Allows usage of /pvp <toggle/enable/disable> command
children:
preventstabby.command: true
preventstabby.command.toggle.others: preventstabby.command.toggle.others:
default: op default: op
description: Allows usage of /pvp <toggle/enable/disable> <player> command description: Allows usage of /pvp <toggle/enable/disable> <player> command
children:
preventstabby.command: true
preventstabby.command.toggle.global: preventstabby.command.toggle.global:
default: op default: op
description: Allows usage of /pvp override <enabled/disabled/none> command description: Allows usage of /pvp override <enabled/disabled/none> command
children:
preventstabby.command: true
preventstabby.command.reload: preventstabby.command.reload:
default: op default: op
description: Allows usage of /pvp reload command description: Allows usage of /pvp reload command
children:
preventstabby.command: true