Compare commits

...

53 Commits

Author SHA1 Message Date
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
YouHaveTrouble 44a5c6d800 bump version 2022-07-19 17:36:14 +02:00
YouHaveTrouble 2ee577a08c setting to allow players being pulled with fishing rods while having pvp off 2022-07-19 17:35:04 +02:00
YouHaveTrouble f5d38eefc3 update readme 2022-06-17 23:35:43 +02:00
YouHaveTrouble e5b566db67 fix javadoc 2022-06-17 22:56:31 +02:00
YouHaveTrouble 9b18c435f6 implement pvp state override command and api 2022-06-17 21:12:55 +02:00
YouHaveTrouble b99c14b631 going on an adventure 2022-06-16 23:52:30 +02:00
YouHaveTrouble 6fd3e4b671 use enum for permissions 2022-05-14 12:28:50 +02:00
YouHaveTrouble 0ff0177f0b Merge remote-tracking branch 'origin/master' 2022-05-14 11:53:40 +02:00
YouHaveTrouble 5a36ba7748 use internal method for message sending, replace some try/catch with null checks 2022-05-14 11:53:31 +02:00
YouHaveTrouble 388e3c74a5 Create LICENSE 2022-05-03 19:22:37 +02:00
YouHaveTrouble 4088a6dd5b fix npe when new pet target is null 2022-05-02 22:57:20 +02:00
YouHaveTrouble a8e606dab5 fix a few bugs 2022-04-15 17:31:26 +02:00
YouHaveTrouble 35f0e6c9d8 add basic true/false placeholder for combat 2022-04-04 17:41:00 +02:00
YouHaveTrouble 51f0f6c93b add placeholderapi hook 2022-03-22 23:02:58 +01:00
YouHaveTrouble 52fb010270 return earlier if player has bypass permission 2022-03-17 21:00:41 +01:00
YouHaveTrouble cd26d621e5 allow damaging mounts with non-player riders 2022-03-17 20:58:39 +01:00
YouHaveTrouble 4c08041ee6 better names for methods 2022-03-17 20:58:12 +01:00
YouHaveTrouble 643511df31 make sure damager is projectile in projectile event 2022-03-17 20:58:03 +01:00
YouHaveTrouble 94f97568d5 update depends 2022-03-17 20:57:01 +01:00
YouHaveTrouble 9a9a44939a prepare for finishing rebranding 2022-01-26 14:41:12 +01:00
YouHaveTrouble 1e7adf398a fix worldguard hook errors 2021-09-18 01:40:11 +02:00
YouHaveTrouble c0ca85c44d add isHooked() back 2021-09-18 00:23:41 +02:00
YouHaveTrouble a86485a089 fix issues with servers not having worldguard 2021-09-18 00:21:19 +02:00
YouHaveTrouble bea0d9c7df make sure mount has player rider before checking for attack cancel 2021-09-17 15:28:34 +02:00
YouHaveTrouble 0eccf1b1af fix unable to attack mounts with no player on them 2021-09-17 15:26:40 +02:00
YouHaveTrouble 2669c538cd remove debug 2 electric boogaloo 2021-08-03 17:45:30 +02:00
YouHaveTrouble 36861084cc remove debug 2021-08-03 17:31:35 +02:00
YouHaveTrouble f182c2c859 add worldguard flag for force pvp 2021-08-03 17:24:17 +02:00
YouHaveTrouble 60b360f170 bump version 2021-07-29 13:37:32 +02:00
YouHaveTrouble 6de41b68bd yeat it kinda fixes the whole thing 2021-07-29 13:34:55 +02:00
37 changed files with 1382 additions and 429 deletions
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+56 -11
View File
@@ -6,7 +6,7 @@
<groupId>me.youhavetrouble</groupId> <groupId>me.youhavetrouble</groupId>
<artifactId>PreventStabby</artifactId> <artifactId>PreventStabby</artifactId>
<version>1.3-pre1</version> <version>1.11.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>PreventStabby</name> <name>PreventStabby</name>
@@ -22,7 +22,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.8.1</version>
<configuration> <configuration>
<source>${java.version}</source> <source>${java.version}</source>
<target>${java.version}</target> <target>${java.version}</target>
@@ -47,9 +47,12 @@
</relocation> </relocation>
<relocation> <relocation>
<pattern>org.bstats</pattern> <pattern>org.bstats</pattern>
<!-- Replace this with your package! -->
<shadedPattern>bstats</shadedPattern> <shadedPattern>bstats</shadedPattern>
</relocation> </relocation>
<relocation>
<pattern>net.kyori</pattern>
<shadedPattern>kyori</shadedPattern>
</relocation>
</relocations> </relocations>
</configuration> </configuration>
</execution> </execution>
@@ -74,8 +77,16 @@
<url>https://oss.sonatype.org/content/groups/public/</url> <url>https://oss.sonatype.org/content/groups/public/</url>
</repository> </repository>
<repository> <repository>
<id>jitpack.io</id> <id>bs-repo</id>
<url>https://jitpack.io</url> <url>https://ci.pluginwiki.us/plugin/repository/everything/</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository> </repository>
</repositories> </repositories>
@@ -89,25 +100,59 @@
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.12</version> <version>1.18.26</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.reflections</groupId> <groupId>org.reflections</groupId>
<artifactId>reflections</artifactId> <artifactId>reflections</artifactId>
<version>0.9.12</version> <version>0.10.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.Thatsmusic99</groupId> <groupId>com.github.thatsmusic99</groupId>
<artifactId>ConfigurationMaster</artifactId> <artifactId>ConfigurationMaster</artifactId>
<version>v1.0-RC-2</version> <version>v1.0.3</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bstats</groupId> <groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId> <artifactId>bstats-bukkit</artifactId>
<version>2.2.1</version> <version>3.0.0</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.4-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.12.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-platform-bukkit</artifactId>
<version>4.2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-minimessage</artifactId>
<version>4.12.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-serializer-legacy</artifactId>
<version>4.12.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
+28 -37
View File
@@ -1,43 +1,34 @@
<h2>PreventStabby ⚔</h2> <h1>PreventStabby ⚔</h1>
Use Issues section to report bugs or submit suggestions. Use Issues section to report bugs or submit suggestions.
<h3>Commands</h3> <h3>Commands</h3>
Permission: <code>preventstabby.command</code> (given by default to everyone) : You can find available commands <a href="https://github.com/YouHaveTrouble/PreventStabby/wiki/Commands">HERE</a>.
<h3>Configuration</h3>
Explanation of all available config options is <a href="https://github.com/YouHaveTrouble/PreventStabby/wiki/Config">HERE</a>.
<h3>Placeholders</h3>
List of all PlaceholderAPI placeholders can be found <a href="https://github.com/YouHaveTrouble/PreventStabby/wiki/Placeholders">HERE</a>.
<h3>Developer API</h3>
Developer API documetation is <a href="https://github.com/YouHaveTrouble/PreventStabby/wiki/Developer-API">HERE</a>!
<h2>Features</h2>
<ul> <ul>
<li>/pvp help- displays help message</li> <li>Per-player PvP Toggle</li>
<li>Global PvP override, allowing to ignore personal toggles temporarily</li>
<li>Block all forms of player-induced damage when PvP off</li>
<li>Block damage done to pets and mounts when PvP off</li>
<li>Block the ability to pour lava and set fire under player's feet</li>
<li>Block channeling tridents spawning fire under players with PvP off</li>
<li>Block fishing pole pulling for players with PvP off</li>
<li>Pets do not attack players with PvP off</li>
<li>Configurable PvP protection after login</li>
<li>Configurable PvP protection after teleport</li>
<li>Kill players that logged out during combat</li>
<li>Block specific commands while in combat</li>
<li>Block teleports in combat (might cause issues with some plugins)</li>
<li>Toggles for eggs and snowballs applying knockback</li>
<li>Extensive developer API</li>
</ul> </ul>
Permission: <code>preventstabby.command.toggle</code> (given by default to everyone) :
<ul>
<li>/pvp toggle - toggles PvP</li>
<li>/pvp on - enables PvP (aliases: enable)</li>
<li>/pvp off - disables PvP (aliases: disable)</li>
</ul>
Permission: <code>preventstabby.command.toggle.others</code> (given by default to ops) :
<ul>
<li>/pvp toggle [player] - toggles other player's PvP</li>
<li>/pvp on [player] - enables other player's PvP (aliases: enable)</li>
<li>/pvp off [player] - disables other player's PvP (aliases: disable)</li>
</ul>
<h3>Features</h3>
Player who disables PvP cannot get hurt by any player induced damage.
They also can't deal any damage to other players.
This includes basic attacks, projectiles, splash potions,
lingering potions and lightning strikes from channeling trident enchant.
Additionally lightning strikes from channeling cannot spawn fire under
players, who have pvp disabled and it's impossible to use
fishing rod on players who have pvp disabled.
There is also a feature that disallows pouring lava or using
flint and steel nearby players with disabled pvp. You can
either disable it in config or set its radius.
All the protections are extended to tameable entities (pets) that set player's uuid as their owner on tame.
Pets will not attack players with pvp off or if their owner has pvp off.
@@ -2,12 +2,16 @@ 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.WorldGuardHook;
import me.youhavetrouble.preventstabby.players.PlayerManager; import me.youhavetrouble.preventstabby.players.PlayerManager;
import me.youhavetrouble.preventstabby.players.SmartCache; import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.DatabaseSQLite; import me.youhavetrouble.preventstabby.util.DatabaseSQLite;
import lombok.Getter; import lombok.Getter;
import me.youhavetrouble.preventstabby.util.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;
@@ -21,9 +25,12 @@ public final class PreventStabby extends JavaPlugin {
@Getter private static PreventStabby plugin; @Getter private static PreventStabby plugin;
private ConfigCache configCache; private ConfigCache configCache;
protected PlayerManager playerManager; private PlayerManager playerManager;
protected DatabaseSQLite sqLite; private DatabaseSQLite sqLite;
protected SmartCache smartCache; private SmartCache smartCache;
private static boolean worldGuardHook;
private static BukkitAudiences adventure;
@Override @Override
public void onEnable() { public void onEnable() {
@@ -31,7 +38,7 @@ public final class PreventStabby extends JavaPlugin {
Util.initData(); Util.initData();
reloadPluginConfig(); reloadPluginConfig();
File dbFile = new File("plugins/PreventStabby"); File dbFile = new File("plugins/PreventStabby");
sqLite = new DatabaseSQLite("jdbc:sqlite:plugins/PreventStabby/TogglePvP.db", dbFile); sqLite = new DatabaseSQLite("jdbc:sqlite:plugins/PreventStabby/database.db", dbFile);
sqLite.createDatabaseFile(); sqLite.createDatabaseFile();
if (!sqLite.testConnection()) { if (!sqLite.testConnection()) {
getLogger().severe("Error with accessing database. Check if server has write rights."); getLogger().severe("Error with accessing database. Check if server has write rights.");
@@ -39,12 +46,13 @@ public final class PreventStabby extends JavaPlugin {
getServer().getPluginManager().disablePlugin(this); getServer().getPluginManager().disablePlugin(this);
return; return;
} }
adventure = BukkitAudiences.create(this);
playerManager = new PlayerManager(); playerManager = new PlayerManager();
smartCache = new SmartCache(); smartCache = new SmartCache();
smartCache.runSmartCache(); smartCache.runSmartCache();
// Register listeners // Register listeners
Reflections reflections = new Reflections(new String[]{"eu.endermite.preventstabby"}); Reflections reflections = new Reflections((Object[]) new String[]{"me.youhavetrouble.preventstabby"});
Set<Class<?>> listenerClasses = reflections.getTypesAnnotatedWith(PreventStabbyListener.class); Set<Class<?>> listenerClasses = reflections.getTypesAnnotatedWith(PreventStabbyListener.class);
listenerClasses.forEach((listener)-> { listenerClasses.forEach((listener)-> {
try { try {
@@ -68,7 +76,27 @@ public final class PreventStabby extends JavaPlugin {
pvpCommand.setExecutor(mainCommand); pvpCommand.setExecutor(mainCommand);
pvpCommand.setTabCompleter(mainCommand); pvpCommand.setTabCompleter(mainCommand);
Metrics metrics = new Metrics(this, 10597); if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PlacoholderApiHook(this).register();
}
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() {
return worldGuardHook;
} }
public void reloadPluginConfig() { public void reloadPluginConfig() {
@@ -78,7 +106,7 @@ public final class PreventStabby extends JavaPlugin {
public void reloadPluginConfig(CommandSender commandSender) { public void reloadPluginConfig(CommandSender commandSender) {
getServer().getScheduler().runTaskAsynchronously(this, () -> { getServer().getScheduler().runTaskAsynchronously(this, () -> {
reloadPluginConfig(); reloadPluginConfig();
commandSender.sendMessage("TogglePvP configuration reloaded."); PluginMessages.sendMessage(commandSender, "PreventStabby configuration reloaded.");
}); });
} }
@@ -95,4 +123,8 @@ public final class PreventStabby extends JavaPlugin {
public SmartCache getSmartCache() { public SmartCache getSmartCache() {
return smartCache; return smartCache;
} }
public static BukkitAudiences getAudiences() {
return adventure;
}
} }
@@ -2,7 +2,10 @@ 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.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.util.UUID; import java.util.UUID;
public class PreventStabbyAPI { public class PreventStabbyAPI {
@@ -65,6 +68,26 @@ public class PreventStabbyAPI {
return PreventStabby.getPlugin().getPlayerManager().canDamage(attacker.getUniqueId(), victim.getUniqueId(), 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. * Checks if player has login protection.
* @param uuid UUID of player to check * @param uuid UUID of player to check
@@ -119,5 +142,19 @@ public class PreventStabbyAPI {
return CombatTimer.isInCombat(player.getUniqueId()); return CombatTimer.isInCombat(player.getUniqueId());
} }
/**
* @return Current state of forced PvP
*/
public static PvpState getForcedPvpState() {
return PreventStabby.getPlugin().getPlayerManager().getForcedPvpState();
}
/**
* Sets forced PvP state until server restart or changed with override command or this method.
*/
public static void setForcedPvpState(PvpState newForcedPvpState) {
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(newForcedPvpState);
}
} }
@@ -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.players.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;
} }
@@ -0,0 +1,48 @@
package me.youhavetrouble.preventstabby.commands;
import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.PreventStabbyPermission;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.Locale;
public class GlobalToggleCommand {
public static void globalToggle(CommandSender sender, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
if (!PreventStabbyPermission.COMMAND_GLOBAL_TOGGLE.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
return;
}
if (args.length != 2) {
PluginMessages.sendMessage(sender, "Try /pvp override <enabled/disabled/none>");
return;
}
PvpState pvpState = PvpState.valueOf(args[1].toUpperCase(Locale.ROOT));
switch (pvpState) {
case ENABLED:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.ENABLED);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_on());
break;
case DISABLED:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.DISABLED);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_off());
break;
case NONE:
PreventStabby.getPlugin().getPlayerManager().setForcedPvpState(PvpState.NONE);
PluginMessages.broadcastMessage(PreventStabby.getPlugin().getConfigCache().getForce_pvp_none());
break;
default:
PluginMessages.sendMessage(sender, "Try /pvp override <enabled/disabled/none>");
}
});
}
}
@@ -1,28 +1,34 @@
package me.youhavetrouble.preventstabby.commands; 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.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
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.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
List<String> helpPage = new ArrayList<>(); if (!PreventStabbyPermission.COMMAND_HELP.doesCommandSenderHave(sender)) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
helpPage.add(PluginMessages.parseMessage("&b&m &bTogglePvP Help&b&m ")); return;
helpPage.add(PluginMessages.parseMessage("&9/pvp &b&lhelp &f- shows this message"));
if (sender.hasPermission("preventstabby.command.toggle")) {
helpPage.add(PluginMessages.parseMessage("&9/pvp &b&l[on/off] &f- enables or disables PvP"));
helpPage.add(PluginMessages.parseMessage("&9/pvp &b&ltoggle &f- toggles PvP status"));
} }
String[] helpReady = helpPage.toArray(new String[0]);
sender.sendMessage(helpReady);
Component helpComponent = PluginMessages.MINIMESSAGE
.deserialize("<aqua><strikethrough> </strikethrough> PreventStabby Help <strikethrough> </strikethrough>")
.append(Component.newline())
.append(PluginMessages.MINIMESSAGE.deserialize("<blue>/pvp <aqua><bold>help</bold> <white>- shows this message"));
if (PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
helpComponent = helpComponent.append(Component.newline());
helpComponent = helpComponent
.append(PluginMessages.MINIMESSAGE.deserialize("<blue>/pvp <aqua><bold>[on/off]</bold> <white>- enables or disables PvP"))
.append(Component.newline())
.append(PluginMessages.MINIMESSAGE.deserialize("<blue>/pvp <aqua><bold>toggle</bold> <white>- toggles PvP status"));
}
PreventStabby.getAudiences().sender(sender).sendMessage(helpComponent);
}); });
} }
@@ -1,12 +1,15 @@
package me.youhavetrouble.preventstabby.commands; 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.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -14,22 +17,30 @@ import java.util.Map;
public class MainCommand implements TabExecutor { public class MainCommand implements TabExecutor {
private final HashMap<String, String> subCommands = new HashMap<>(); private final HashMap<String, PreventStabbyPermission> subCommands = new HashMap<>();
public MainCommand() { public MainCommand() {
subCommands.put("help", "preventstabby.command"); subCommands.put("help", PreventStabbyPermission.COMMAND_HELP);
subCommands.put("toggle", "preventstabby.command.toggle"); subCommands.put("toggle", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("on", "preventstabby.command.toggle"); subCommands.put("on", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("enable", "preventstabby.command.toggle"); subCommands.put("enable", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("off", "preventstabby.command.toggle"); subCommands.put("off", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("disable", "preventstabby.command.toggle"); subCommands.put("disable", PreventStabbyPermission.COMMAND_TOGGLE);
subCommands.put("reload", "preventstabby.command.reload"); subCommands.put("reload", PreventStabbyPermission.COMMAND_RELOAD);
subCommands.put("override", PreventStabbyPermission.COMMAND_GLOBAL_TOGGLE);
} }
@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")) {
if (args.length >= 1) { PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
return true;
}
if (args.length == 0) {
PvpToggleCommand.toggle(sender, args);
return true;
}
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "help": case "help":
HelpCommand.help(sender, args); HelpCommand.help(sender, args);
@@ -48,15 +59,12 @@ public class MainCommand implements TabExecutor {
case "reload": case "reload":
ReloadCommand.reload(sender); ReloadCommand.reload(sender);
break; break;
default: case "override":
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getNo_such_command())); GlobalToggleCommand.globalToggle(sender, args);
break;
default:
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_such_command());
break; break;
}
} else {
HelpCommand.help(sender, args);
}
} else {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getNo_permission()));
} }
return true; return true;
} }
@@ -66,12 +74,13 @@ public class MainCommand implements TabExecutor {
List<String> commands = new ArrayList<>(); List<String> commands = new ArrayList<>();
if (args.length == 1) { if (args.length == 1) {
String arg1 = args[0].toLowerCase(); String arg1 = args[0].toLowerCase();
for (Map.Entry<String, String> entry : subCommands.entrySet()) { for (Map.Entry<String, PreventStabbyPermission> entry : subCommands.entrySet()) {
if (entry.getKey().toLowerCase().startsWith(arg1) && sender.hasPermission(entry.getValue())) if (entry.getKey().toLowerCase().startsWith(arg1)
&& entry.getValue().doesCommandSenderHave(sender))
commands.add(entry.getKey()); commands.add(entry.getKey());
} }
return commands; return commands;
} else if (args.length == 2 && sender.hasPermission("preventstabby.command.toggle")) { } else if (args.length == 2) {
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
default: default:
break; break;
@@ -80,12 +89,19 @@ public class MainCommand implements TabExecutor {
case "enable": case "enable":
case "off": case "off":
case "disable": case "disable":
if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) break;
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
commands.add(player.getName()); commands.add(player.getName());
} }
break; break;
case "override":
if (!PreventStabbyPermission.COMMAND_GLOBAL_TOGGLE.doesCommandSenderHave(sender)) break;
commands.add("enabled");
commands.add("disabled");
commands.add("none");
break;
} }
return commands; return StringUtil.copyPartialMatches(args[1], commands, new ArrayList<>());
} }
return null; return null;
} }
@@ -1,178 +1,202 @@
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.util.CombatTimer; import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class PvpToggleCommand { public class PvpToggleCommand {
public static void toggle(CommandSender sender, String[] args) { public static void toggle(CommandSender sender, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
if (!sender.hasPermission("preventstabby.command.toggle")) { PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (args.length == 1) { if (args.length <= 1) {
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId()); boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId());
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, currentState, true);
String message = ""; Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
if (currentState) { if (currentState) {
message = PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getPvp_enabled()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
} else { } else {
message = PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getPvp_disabled()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_disabled());
} }
player.sendMessage(message); }
});
} else { } else {
sender.sendMessage("Try /pvp toggle <player>"); PluginMessages.sendMessage(sender, "Try /pvp toggle <player>");
} }
} else if (args.length == 2) { } else if (args.length == 2) {
if (!sender.hasPermission("preventstabby.command.toggle.others")) { if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
} }
try {
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
if (player == null) {
PluginMessages.sendMessage(sender, "<red>Player offline.");
return;
}
boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId()); boolean currentState = PreventStabby.getPlugin().getPlayerManager().togglePlayerPvpState(player.getUniqueId());
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, currentState, false);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
if (currentState) {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
} else {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().getPvp_disabled());
}
}
});
String message; String message;
if (currentState) { if (currentState) {
message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other(); message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other();
} else { } else {
message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other(); message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other();
} }
sender.sendMessage(PluginMessages.parsePlayerName(player, message)); PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
} catch (NullPointerException e) {
sender.sendMessage(PluginMessages.parseMessage("&cPlayer offline."));
}
} else {
if (sender.hasPermission("preventstabby.command.toggle.others")) {
sender.sendMessage("Try /pvp toggle <player>");
} else {
sender.sendMessage("Try /pvp toggle");
}
} }
}); });
} }
public static void enable(CommandSender sender, String[] args) { public static void enable(CommandSender sender, String[] args) {
if (!sender.hasPermission("preventstabby.command.toggle")) { if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (args.length == 1) { if (args.length == 1) {
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true); PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true);
String message = PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getPvp_enabled()); PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, true, true);
player.sendMessage(message); Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
}
});
} else { } else {
sender.sendMessage("Try /pvp enable <player>"); PluginMessages.sendMessage(sender, "Try /pvp enable <player>");
} }
} else if (args.length == 2) { } else if (args.length == 2) {
if (!sender.hasPermission("preventstabby.command.toggle.others")) { if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
} }
try {
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
String message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other(); if (player == null) {
sender.sendMessage(PluginMessages.parsePlayerName(player, message)); PluginMessages.sendMessage(sender, "<red>Player offline.");
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true); return;
} catch (NullPointerException e) {
sender.sendMessage(PluginMessages.parseMessage("&cPlayer offline."));
} }
String message = PreventStabby.getPlugin().getConfigCache().getPvp_enabled_other();
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true);
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, true, false);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().getPvp_enabled());
}
});
} else { } else {
if (sender.hasPermission("preventstabby.command.toggle.others")) { if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
sender.sendMessage("Try /pvp enable <player>"); PluginMessages.sendMessage(sender, "Try /pvp enable <player>");
} else { } else {
sender.sendMessage("Try /pvp enable"); PluginMessages.sendMessage(sender, "Try /pvp enable");
} }
} }
} }
public static void disable(CommandSender sender, String[] args) { public static void disable(CommandSender sender, String[] args) {
if (!sender.hasPermission("preventstabby.command.toggle")) { if (!PreventStabbyPermission.COMMAND_TOGGLE.doesCommandSenderHave(sender)) {
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (args.length == 1) { if (args.length == 1) {
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), false); PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), false);
String message = PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getPvp_disabled()); PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, false, true);
player.sendMessage(message); Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getPvp_disabled());
}
});
} else { } else {
sender.sendMessage("Try /pvp disable <player>"); PluginMessages.sendMessage(sender, "Try /pvp disable <player>");
} }
} else if (args.length == 2) { } else if (args.length == 2) {
if (!sender.hasPermission("preventstabby.command.toggle.others")) { if (!PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
String message = PreventStabby.getPlugin().getConfigCache().getNo_permission(); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (CombatTimer.isInCombat(player.getUniqueId())) { if (CombatTimer.isInCombat(player.getUniqueId())) {
sender.sendMessage(PluginMessages.parseMessage(PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat())); PluginMessages.sendMessage(sender, PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
return; return;
} }
} }
try {
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
String message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other(); if (player == null) {
sender.sendMessage(PluginMessages.parsePlayerName(player, message)); PluginMessages.sendMessage(sender, "<red>Player offline.");
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), true); return;
} catch (NullPointerException e) {
sender.sendMessage(PluginMessages.parseMessage("&cPlayer offline."));
} }
String message = PreventStabby.getPlugin().getConfigCache().getPvp_disabled_other();
PluginMessages.sendMessage(sender, PluginMessages.parsePlayerName(player, message));
PreventStabby.getPlugin().getPlayerManager().setPlayerPvpState(player.getUniqueId(), false);
PlayerTogglePvpEvent toggleEvent = new PlayerTogglePvpEvent(player, false, false);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(toggleEvent);
if (toggleEvent.isSendMessage()) {
PluginMessages.sendMessage(player, PreventStabby.getPlugin().getConfigCache().getPvp_disabled());
}
});
} else { } else {
if (sender.hasPermission("preventstabby.command.toggle.others")) { if (PreventStabbyPermission.COMMAND_TOGGLE_OTHERS.doesCommandSenderHave(sender)) {
sender.sendMessage("Try /pvp disable <player>"); PluginMessages.sendMessage(sender, "Try /pvp disable <player>");
} else { } else {
sender.sendMessage("Try /pvp disable"); PluginMessages.sendMessage(sender, "Try /pvp disable");
} }
} }
} }
@@ -1,23 +1,21 @@
package me.youhavetrouble.preventstabby.commands; 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.util.PluginMessages;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; 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.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
if (!sender.hasPermission("preventstabby.command.reload")) { if (!PreventStabbyPermission.COMMAND_RELOAD.doesCommandSenderHave(sender)) {
String message = ChatColor.translateAlternateColorCodes('&', PreventStabby.getPlugin().getConfigCache().getNo_permission()); PluginMessages.parseMessage(sender, PreventStabby.getPlugin().getConfigCache().getNo_permission());
sender.sendMessage(message);
return; return;
} }
PreventStabby.getPlugin().reloadPluginConfig(sender); PreventStabby.getPlugin().reloadPluginConfig(sender);
}); });
} }
} }
@@ -16,11 +16,13 @@ public class ConfigCache {
@Getter private final boolean pvp_enabled_by_default, lava_and_fire_stopper_enabled, channeling_enchant_disabled, @Getter private final boolean pvp_enabled_by_default, lava_and_fire_stopper_enabled, channeling_enchant_disabled,
punish_for_combat_logout, punish_for_combat_logout_announce, only_owner_can_interact_with_pet, punish_for_combat_logout, punish_for_combat_logout_announce, only_owner_can_interact_with_pet,
snowballs_knockback, egg_knockback, block_commands_in_combat, block_teleports_in_combat; snowballs_knockback, egg_knockback, block_commands_in_combat, block_teleports_in_combat, allow_fishing_rod_pull;
@Getter private final String pvp_enabled, pvp_disabled, cannot_attack_victim, cannot_attack_attacker, @Getter private 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; 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,
placeholder_pvp_forced_true, placeholder_pvp_forced_false, placeholder_pvp_forced_none;
@Getter private final double lava_and_fire_stopper_radius; @Getter private final double lava_and_fire_stopper_radius;
@Getter private final long cache_time, combat_time, login_protection_time, teleport_protection_time; @Getter private final long cache_time, combat_time, login_protection_time, teleport_protection_time;
@Getter private final Set<String> combatBlockedCommands = new HashSet<>(); @Getter private final Set<String> combatBlockedCommands = new HashSet<>();
@@ -50,12 +52,14 @@ public class ConfigCache {
addComment("settings.punish_for_combat_logout", "Kill the player if they log out during combat"); 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.enabled", true);
addDefault("settings.punish_for_combat_logout.announce", true); addDefault("settings.punish_for_combat_logout.announce", true);
addDefault("settings.punish_for_combat_logout.message", "&f%player% logged out while in combat. What a loser."); 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.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.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"); addComment("settings.block_in_combat", "Set what actions should be blocked while in combat");
addDefault("settings.block_in_combat.block_commands.enabled", true); addDefault("settings.block_in_combat.block_commands.enabled", true);
List<String> defaultCommandsBlocked = new ArrayList<>(); List<String> defaultCommandsBlocked = new ArrayList<>();
@@ -67,27 +71,36 @@ public class ConfigCache {
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("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", "&cYou enabled PvP!"); addDefault("messages.pvp_enabled", "<red>You enabled PvP!");
addDefault("messages.pvp_disabled", "&cYou disabled PvP!"); addDefault("messages.pvp_disabled", "<red>You disabled PvP!");
addDefault("messages.cannot_attack_victim", "&cYou can't attack players that have PvP turned off!"); addDefault("messages.cannot_attack_victim", "<red>You can't attack players that have PvP turned off!");
addDefault("messages.cannot_attack_attacker", "&cYou can't attack players while you 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", "&cYou can't attack pets of players that 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", "&cYou can't attack pets while you 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", "&cYou can't attack mounts of players that 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", "&cYou can't attack mounts while you have PvP turned off"); addDefault("messages.cannot_attack_mounts_attacker", "<red>You can't attack mounts while you have PvP turned off");
addDefault("messages.no_permission", "&cYou don't have permission to use that."); addDefault("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled");
addDefault("messages.no_such_command", "&cNo such command."); addDefault("messages.no_permission", "<red>You don't have permission to use that.");
addDefault("messages.pvp_enabled_others", "&cYou've enabled %player%'s PvP."); addDefault("messages.no_such_command", "<red>No such command.");
addDefault("messages.pvp_disabled_others", "&cYou've disabled %player%'s PvP."); addDefault("messages.pvp_enabled_others", "<red>You've enabled %player%'s PvP.");
addDefault("messages.entering_combat", "&cEntering combat"); addDefault("messages.pvp_disabled_others", "<red>You've disabled %player%'s PvP.");
addDefault("messages.leaving_combat", "&cLeaving combat"); addDefault("messages.entering_combat", "<red>Entering combat");
addDefault("messages.cant_do_that_during_combat", "&cYou can't do that while in 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");
addDefault("placeholder.pvp_forced_true", "PvP is forced on");
addDefault("placeholder.pvp_forced_false", "PvP is forced off");
addDefault("placeholder.pvp_forced_none", "PvP is not forced");
} }
}; };
configFile.setDescription("PvP toggle that CARES about your pets!"); configFile.setDescription("Prevent people from getting stabbed!");
configFile.addLink("Spigot", "https://www.spigotmc.org/resources/togglepvp.89376/"); configFile.addLink("Spigot", "https://www.spigotmc.org/resources/89376/");
configFile.addLink("Source", "https://github.com/YouHaveTrouble/TogglePvP"); configFile.addLink("Source", "https://github.com/YouHaveTrouble/PreventStabby");
configFile.load(); configFile.load();
FileConfiguration config = configFile.getConfig(); FileConfiguration config = configFile.getConfig();
@@ -103,16 +116,17 @@ public class ConfigCache {
this.combat_time = config.getLong("settings.combat_time", 25L); this.combat_time = config.getLong("settings.combat_time", 25L);
this.punish_for_combat_logout = config.getBoolean("settings.punish_for_combat_logout.enabled", true); this.punish_for_combat_logout = config.getBoolean("settings.punish_for_combat_logout.enabled", true);
this.punish_for_combat_logout_announce = config.getBoolean("settings.punish_for_combat_logout.announce", true); this.punish_for_combat_logout_announce = config.getBoolean("settings.punish_for_combat_logout.announce", true);
this.punish_for_combat_logout_message = config.getString("settings.punish_for_combat_logout.message", "&f%player% logged out while in combat. What a loser."); 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.");
this.only_owner_can_interact_with_pet = config.getBoolean("settings.only_owner_can_interact_with_pet", false); 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.snowballs_knockback = config.getBoolean("settings.snowballs_do_knockback", false); this.snowballs_knockback = config.getBoolean("settings.snowballs_do_knockback", false);
this.egg_knockback = config.getBoolean("settings.eggs_do_knockback", false); this.egg_knockback = config.getBoolean("settings.eggs_do_knockback", false);
this.block_commands_in_combat = config.getBoolean("settings.block_in_combat.block_commands", true); this.block_commands_in_combat = config.getBoolean("settings.block_in_combat.block_commands", true);
if (block_commands_in_combat) { if (block_commands_in_combat) {
this.combatBlockedCommands.addAll(config.getStringList("settings.block_in_combat.block_commands.commands")); this.combatBlockedCommands.addAll(config.getStringList("settings.block_in_combat.block_commands.commands"));
} }
this.block_teleports_in_combat = config.getBoolean("settings.block_in_combat.block_teleports", true); this.block_teleports_in_combat = config.getBoolean("settings.block_in_combat.block_teleports", false);
this.cache_time = config.getLong("settings.cache_time", 30L); this.cache_time = config.getLong("settings.cache_time", 30L);
@@ -120,23 +134,32 @@ public class ConfigCache {
this.teleport_protection_time = config.getLong("settings.teleport_protection_time", 0); this.teleport_protection_time = config.getLong("settings.teleport_protection_time", 0);
// Messages // Messages
this.pvp_enabled = config.getString("messages.pvp_enabled", "&cYou enabled PvP!"); this.pvp_enabled = config.getString("messages.pvp_enabled", "<red>You enabled PvP!");
this.pvp_disabled = config.getString("messages.pvp_disabled", "&cYou disabled PvP!"); this.pvp_disabled = config.getString("messages.pvp_disabled", "<red>You disabled PvP!");
this.cannot_attack_victim = config.getString("messages.cannot_attack_victim", "&cYou can't attack players that have PvP turned off!"); this.cannot_attack_victim = config.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", "&cYou can't attack players while you 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_pets_victim = config.getString("messages.cannot_attack_pets_victim", "&cYou can't attack pets 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_attacker = config.getString("messages.cannot_attack_pets_attacker", "&cYou can't attack pets of players that 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_mounts_victim = config.getString("messages.cannot_attack_mounts_victim", "&cYou can't attack mounts 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_attacker = config.getString("messages.cannot_attack_mounts_attacker", "&cYou can't attack mounts while you 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.no_permission = config.getString("messages.no_permission", "&cYou don't have permission to use that."); this.cannot_attack_pvp_force_off = config.getString("messages.cannot_attack_pvp_force_off", "<red>PvP is forcibly disabled");
this.no_such_command = config.getString("messages.no_such_command", "&cNo such command."); this.no_permission = config.getString("messages.no_permission", "<red>You don't have permission to use that.");
this.pvp_enabled_other = config.getString("messages.pvp_enabled_others", "&cYou've enabled %player%'s PvP."); this.no_such_command = config.getString("messages.no_such_command", "<red>No such command.");
this.pvp_disabled_other = config.getString("messages.pvp_disabled_others", "&cYou've disabled %player%'s PvP."); this.pvp_enabled_other = config.getString("messages.pvp_enabled_others", "<red>You've enabled %player%'s PvP.");
this.entering_combat = config.getString("messages.entering_combat", "&cEntering combat"); this.pvp_disabled_other = config.getString("messages.pvp_disabled_others", "<red>You've disabled %player%'s PvP.");
this.leaving_combat = config.getString("messages.leaving_combat", "&cLeaving combat"); this.entering_combat = config.getString("messages.entering_combat", "<red>Entering combat");
this.cant_do_that_during_combat = config.getString("messages.cant_do_that_during_combat", "&cYou can't do that while in 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.placeholder_not_in_combat = config.getString("placeholder.not_in_combat", "Not in combat");
this.placeholder_pvp_forced_true = config.getString("placeholder.pvp_forced_true", "PvP is forced on");
this.placeholder_pvp_forced_false = config.getString("placeholder.pvp_forced_false", "PvP is forced off");
this.placeholder_pvp_forced_none = config.getString("placeholder.pvp_forced_none", "PvP is not forced");
} }
@@ -0,0 +1,29 @@
package me.youhavetrouble.preventstabby.config;
import org.bukkit.command.CommandSender;
public enum PreventStabbyPermission {
COMMAND("command"),
COMMAND_TOGGLE("command.toggle"),
COMMAND_TOGGLE_OTHERS("command.toggle.others"),
COMMAND_RELOAD("command.reload"),
COMMAND_GLOBAL_TOGGLE("command.toggle.global"),
COMMAND_HELP("command.help");
private final String permission;
PreventStabbyPermission(String permission) {
this.permission = "preventstabby."+permission;
}
public boolean doesCommandSenderHave(CommandSender sender) {
return sender.hasPermission(permission);
}
@Override
public String toString() {
return permission;
}
}
@@ -0,0 +1,77 @@
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.minimessage.MiniMessage;
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) {
switch (params) {
case "pvp":
if (!player.isOnline()) return String.valueOf(false);
return String.valueOf(plugin.getPlayerManager().getPlayer(player.getUniqueId()).isPvpEnabled());
case "combat_time":
return getCombatTimePlaceholder(player.getUniqueId(), player);
case "in_combat":
if (!player.isOnline()) return String.valueOf(false);
return String.valueOf(plugin.getPlayerManager().getPlayer(player.getUniqueId()).isInCombat());
case "pvp_forced":
switch (PreventStabby.getPlugin().getPlayerManager().getForcedPvpState()) {
case NONE:
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().getPlaceholder_pvp_forced_none()));
case ENABLED:
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().getPlaceholder_pvp_forced_true()));
case DISABLED:
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().getPlaceholder_pvp_forced_false()));
}
default:
return null;
}
}
private String getCombatTimePlaceholder(UUID uuid, OfflinePlayer player) {
if (!player.isOnline()) {
return legacyComponentSerializer.serialize(PluginMessages.parseMessage(plugin.getConfigCache().getPlaceholder_not_in_combat()));
}
long seconds = plugin.getPlayerManager().getPlayer(uuid).getCombatTime();
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()));
}
}
@@ -0,0 +1,62 @@
package me.youhavetrouble.preventstabby.hooks;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class WorldGuardHook {
private static FlagRegistry flagRegistry;
public static StateFlag FORCE_PVP_FLAG;
public static void init() {
try {
Class.forName("com.sk89q.worldguard.protection.flags.registry.FlagRegistry");
WorldGuardPlugin worldGuardPlugin = WorldGuardPlugin.inst();
if (WorldGuard.getInstance() == null || worldGuardPlugin == null) return;
Bukkit.getLogger().info("[PreventStabby] Hooking into WorldGuard");
flagRegistry = WorldGuard.getInstance().getFlagRegistry();
createForcePvpFlag();
} catch (NoClassDefFoundError | ClassNotFoundException ignored) {
}
}
private static void createForcePvpFlag() {
if (flagRegistry == null) return;
String flagName = "preventstabby-force-pvp";
try {
StateFlag flag = new StateFlag(flagName, false);
flagRegistry.register(flag);
FORCE_PVP_FLAG = flag;
} catch (FlagConflictException e) {
Flag<?> existing = flagRegistry.get(flagName);
if (existing instanceof StateFlag) {
FORCE_PVP_FLAG = (StateFlag) existing;
} else {
Bukkit.getLogger().severe("[PreventStabby] There is a conflict between flag names!");
}
}
}
public static boolean isPlayerForcedToPvp(Player player) {
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
RegionQuery query = container.createQuery();
org.bukkit.Location loc = player.getLocation();
if (loc.getWorld() == null) return false;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
ApplicableRegionSet set = query.getApplicableRegions(new Location(BukkitAdapter.adapt(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()));
return set.testState(localPlayer, FORCE_PVP_FLAG);
}
}
@@ -15,7 +15,7 @@ import java.util.UUID;
public class MountHitByExplosionListener implements Listener { public class MountHitByExplosionListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onMountHitByExplosion(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return; if (!(event.getDamager() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return;
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return; if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
UUID damager = event.getDamager().getUniqueId(); UUID damager = event.getDamager().getUniqueId();
@@ -16,7 +16,7 @@ import java.util.UUID;
public class MountHitByFireworkListener implements Listener { public class MountHitByFireworkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onMountHitByFireWork(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Firework) || event.getEntity().getPassengers().isEmpty()) return; if (!(event.getDamager() instanceof Firework) || event.getEntity().getPassengers().isEmpty()) return;
if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return; if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return;
Firework firework = (Firework) event.getDamager(); Firework firework = (Firework) event.getDamager();
@@ -15,10 +15,10 @@ import java.util.UUID;
public class PlayerHitMountWithProjectileListener implements Listener { public class PlayerHitMountWithProjectileListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onPlayerHitMountWithProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return; if (!(event.getDamager() instanceof Projectile)) return;
Projectile projectile = (Projectile) event.getDamager(); Projectile projectile = (Projectile) event.getDamager();
if (!(projectile.getShooter() instanceof Player)) return; if (!(projectile.getShooter() instanceof Player) || event.getEntity().getPassengers().isEmpty()) return;
Entity entity = event.getEntity(); Entity entity = event.getEntity();
UUID damager = event.getDamager().getUniqueId(); UUID damager = event.getDamager().getUniqueId();
if (Util.processMountAttack(damager, entity)) if (Util.processMountAttack(damager, entity))
@@ -3,6 +3,7 @@ package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.SmartCache; import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import me.youhavetrouble.preventstabby.util.PvpState;
import me.youhavetrouble.preventstabby.util.Util; import me.youhavetrouble.preventstabby.util.Util;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Tameable; import org.bukkit.entity.Tameable;
@@ -14,8 +15,12 @@ import org.bukkit.event.Listener;
@PreventStabbyListener @PreventStabbyListener
public class PetTargettingMountListener implements Listener { public class PetTargettingMountListener implements Listener {
/**
* TODO - this needs to pass canDamage() in the future, for now it just checks forced pvp state directly
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWolfAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onWolfAttackMount(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (PreventStabby.getPlugin().getPlayerManager().getForcedPvpState() == PvpState.ENABLED) return;
if (!(event.getDamager() instanceof Tameable) || event.getEntity().getPassengers().isEmpty()) return; if (!(event.getDamager() instanceof Tameable) || event.getEntity().getPassengers().isEmpty()) return;
Tameable damager = (Tameable) event.getDamager(); Tameable damager = (Tameable) event.getDamager();
Entity victim = event.getEntity(); Entity victim = event.getEntity();
@@ -1,7 +1,9 @@
package me.youhavetrouble.preventstabby.listeners.pets; package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.players.SmartCache; import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Tameable; import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf; import org.bukkit.entity.Wolf;
@@ -14,23 +16,21 @@ public class PetTargettingPetListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWolfAttackWolf(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onWolfAttackWolf(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Tameable && event.getEntity() instanceof Tameable) { if (!(event.getDamager() instanceof Tameable) || !(event.getEntity() instanceof Tameable)) return;
Tameable damager = (Tameable) event.getDamager(); Tameable damager = (Tameable) event.getDamager();
Tameable victim = (Tameable) event.getEntity(); Tameable victim = (Tameable) event.getEntity();
if (damager.getOwner() == null || victim.getOwner() == null) return; if (damager.getOwner() == null || victim.getOwner() == null) return;
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache(); if (!PreventStabby.getPlugin().getPlayerManager()
boolean damagerPvpEnabled = smartCache.getPlayerData(damager.getOwner().getUniqueId()).isPvpEnabled(); .canDamage(
boolean victimPvpEnabled = smartCache.getPlayerData(victim.getOwner().getUniqueId()).isPvpEnabled(); damager.getUniqueId(),
victim.getUniqueId(),
if (!victimPvpEnabled || !damagerPvpEnabled) { false,
if (damager instanceof Wolf) { false
Wolf wolf = (Wolf) damager; ))
wolf.setAngry(false);
}
event.setCancelled(true); event.setCancelled(true);
}
}
} }
} }
@@ -8,6 +8,7 @@ import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityTargetEvent;
import java.util.UUID; import java.util.UUID;
@@ -17,19 +18,26 @@ public class PetTargettingPlayerListener implements Listener {
* Stops pets with owners targetting players with pvp off * Stops pets with owners targetting players with pvp off
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPetTargetPlayer(org.bukkit.event.entity.EntityTargetEvent event) { public void onPetTargetPlayer(EntityTargetEvent event) {
if (!(event.getEntity() instanceof Tameable)) return; if (!(event.getEntity() instanceof Tameable)) return;
Tameable entity = (Tameable) event.getEntity(); Tameable entity = (Tameable) event.getEntity();
if (entity.getOwner() == null) return; if (!(entity.getOwner() instanceof Player)) return;
if (!(event.getTarget() instanceof Player)) return;
if (event.getTarget() instanceof Player) {
UUID damager = entity.getOwner().getUniqueId(); UUID damager = entity.getOwner().getUniqueId();
UUID victim = event.getTarget().getUniqueId(); UUID victim = event.getTarget().getUniqueId();
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, true, false)) boolean tempting = event.getReason().equals(EntityTargetEvent.TargetReason.TEMPT);
if (PreventStabby.getPlugin().getPlayerManager().canDamage(damager, victim, !tempting, false)) {
if (tempting) {
event.setCancelled(true);
return;
}
CombatTimer.refreshPlayersCombatTime(damager, victim); CombatTimer.refreshPlayersCombatTime(damager, victim);
}
else else
event.setCancelled(true); event.setCancelled(true);
}
} }
} }
@@ -2,15 +2,14 @@ package me.youhavetrouble.preventstabby.listeners.pets;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.config.ConfigCache; import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.CombatTimer; import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable; import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import java.util.UUID; import java.util.UUID;
@@ -18,10 +17,10 @@ import java.util.UUID;
public class PlayerAttackPetListener implements Listener { public class PlayerAttackPetListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerAttackPet(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onPlayerAttackPet(EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || !(event.getEntity() instanceof Tameable)) return;
if (event.getDamager() instanceof Player && event.getEntity() instanceof Tameable) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
Tameable tameable = (Tameable) event.getEntity(); Tameable tameable = (Tameable) event.getEntity();
if (tameable.getOwner() == null) return; if (tameable.getOwner() == null) return;
@@ -31,19 +30,18 @@ public class PlayerAttackPetListener implements Listener {
if (damager.equals(victim)) return; if (damager.equals(victim)) return;
ConfigCache config = PreventStabby.getPlugin().getConfigCache(); ConfigCache config = PreventStabby.getPlugin().getConfigCache();
boolean damagerPvpState = PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(damager);
if (!damagerPvpState) { if (PreventStabby.getPlugin().getPlayerManager()
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_attacker()); .canDamage(
event.setCancelled(true); damager,
return; victim,
} config.getCannot_attack_pets_attacker(),
if (!smartCache.getPlayerData(victim).isPvpEnabled()) { config.getCannot_attack_pets_victim(),
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_victim()); false
event.setCancelled(true); ))
return;
}
CombatTimer.refreshPlayersCombatTime(damager); CombatTimer.refreshPlayersCombatTime(damager);
else
event.setCancelled(true);
} }
} }
}
@@ -23,7 +23,7 @@ public class PlayerHitPetWithProjectileListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerHitPetWithProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) { public void onPlayerHitPetWithProjectile(org.bukkit.event.entity.EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Tameable && event.getDamager() instanceof Projectile) { if (!(event.getEntity() instanceof Tameable) || !(event.getDamager() instanceof Projectile)) return;
Projectile projectile = (Projectile) event.getDamager(); Projectile projectile = (Projectile) event.getDamager();
if (!(projectile.getShooter() instanceof Player)) return; if (!(projectile.getShooter() instanceof Player)) return;
Tameable tameable = (Tameable) event.getEntity(); Tameable tameable = (Tameable) event.getEntity();
@@ -35,20 +35,19 @@ public class PlayerHitPetWithProjectileListener implements Listener {
if (damager.equals(victim)) return; if (damager.equals(victim)) return;
ConfigCache config = PreventStabby.getPlugin().getConfigCache(); ConfigCache config = PreventStabby.getPlugin().getConfigCache();
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (!smartCache.getPlayerData(damager).isPvpEnabled()) { if (PreventStabby.getPlugin().getPlayerManager()
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_attacker()); .canDamage(
event.setCancelled(true); damager,
return; victim,
} config.getCannot_attack_pets_attacker(),
if (!smartCache.getPlayerData(victim).isPvpEnabled()) { config.getCannot_attack_pets_victim(),
PluginMessages.sendActionBar(damager, config.getCannot_attack_pets_victim()); false
event.setCancelled(true); ))
return;
}
CombatTimer.refreshPlayersCombatTime(damager); CombatTimer.refreshPlayersCombatTime(damager);
else
event.setCancelled(true);
} }
} }
}
@@ -17,6 +17,9 @@ public class CombatCommandListener implements Listener {
if (!PreventStabby.getPlugin().getConfigCache().isBlock_commands_in_combat()) if (!PreventStabby.getPlugin().getConfigCache().isBlock_commands_in_combat())
return; return;
if (event.getPlayer().hasPermission("toglepvp.combatcommandblock.bypass"))
return;
PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager(); PlayerManager playerManager = PreventStabby.getPlugin().getPlayerManager();
if (!playerManager.getPlayer(event.getPlayer().getUniqueId()).isInCombat()) if (!playerManager.getPlayer(event.getPlayer().getUniqueId()).isInCombat())
@@ -27,9 +30,6 @@ public class CombatCommandListener implements Listener {
if (!PreventStabby.getPlugin().getConfigCache().getCombatBlockedCommands().contains(command)) if (!PreventStabby.getPlugin().getConfigCache().getCombatBlockedCommands().contains(command))
return; return;
if (event.getPlayer().hasPermission("toglepvp.combatcommandblock.bypass"))
return;
event.setCancelled(true); event.setCancelled(true);
PluginMessages.sendMessage(event.getPlayer(), PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat()); PluginMessages.sendMessage(event.getPlayer(), PreventStabby.getPlugin().getConfigCache().getCant_do_that_during_combat());
@@ -19,6 +19,7 @@ public class FishingListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFish(org.bukkit.event.player.PlayerFishEvent event) { public void onFish(org.bukkit.event.player.PlayerFishEvent event) {
if (event.getCaught() instanceof Player) { if (event.getCaught() instanceof Player) {
if (PreventStabby.getPlugin().getConfigCache().isAllow_fishing_rod_pull()) return;
UUID damager = event.getPlayer().getUniqueId(); UUID damager = event.getPlayer().getUniqueId();
UUID victim = event.getCaught().getUniqueId(); UUID victim = event.getCaught().getUniqueId();
if (damager == victim) if (damager == victim)
@@ -5,82 +5,108 @@ import me.youhavetrouble.preventstabby.PreventStabby;
import java.time.Instant; import java.time.Instant;
import java.util.UUID; import java.util.UUID;
/**
* PreventStabby player data keeper.<br>
*/
public class PlayerData { public class PlayerData {
private UUID playerUuid; private final UUID playerUuid;
private long cachetime, combattime, loginTimestamp, teleportTimestamp; private long cachetime, combattime, loginTimestamp, teleportTimestamp;
private boolean pvpEnabled, lastCombatCheck, inCombat; private boolean pvpEnabled, lastCombatCheck, inCombat;
public PlayerData(boolean pvpEnabled) { public PlayerData(UUID playerUuid, boolean pvpEnabled) {
this.playerUuid = playerUuid;
this.pvpEnabled = pvpEnabled; this.pvpEnabled = pvpEnabled;
this.combattime = Instant.now().getEpochSecond()-1; this.combattime = Instant.now().getEpochSecond()-1;
this.loginTimestamp = Instant.now().getEpochSecond()-1; this.loginTimestamp = Instant.now().getEpochSecond()-1;
this.teleportTimestamp = Instant.now().getEpochSecond()-1; this.teleportTimestamp = Instant.now().getEpochSecond()-1;
this.inCombat = false; this.inCombat = false;
refreshCachetime(); refreshCacheTime();
} }
public UUID getPlayerUuid() { public UUID getPlayerUuid() {
return playerUuid; return playerUuid;
} }
/**
* Returns true if player has personal pvp enabled, false otherwise.
* @return True if player has personal pvp enabled, false otherwise.
* @see PlayerManager#getPlayerPvPState(UUID)
*/
public boolean isPvpEnabled() { public boolean isPvpEnabled() {
return pvpEnabled; return pvpEnabled;
} }
/**
* Sets player's personal pvp state.
* @param pvpEnabled Pvp state to set.
*/
public void setPvpEnabled(boolean pvpEnabled) { public void setPvpEnabled(boolean pvpEnabled) {
this.pvpEnabled = pvpEnabled; this.pvpEnabled = pvpEnabled;
} }
public long getCachetime() { protected long getCachetime() {
return cachetime; return cachetime;
} }
public void refreshCachetime() { protected void refreshCacheTime() {
this.cachetime = Instant.now().getEpochSecond() + PreventStabby.getPlugin().getConfigCache().getCache_time(); this.cachetime = Instant.now().getEpochSecond() + PreventStabby.getPlugin().getConfigCache().getCache_time();
} }
public long getCombattime() { /**
return combattime; * Time left until the end of combat in seconds.
* @return Time left until the end of combat in seconds.<br>
* Return of 0 means out of combat or about to be out of combat.
*/
public long getCombatTime() {
return Math.max(combattime - Instant.now().getEpochSecond(), 0);
} }
public void setCombattime(long combattime) { protected void setCombattime(long combattime) {
this.combattime = combattime; this.combattime = combattime;
} }
/**
* Sets player in combat and sets combat time to the interval set in config.
* @see PlayerManager#refreshPlayersCombatTime(UUID)
*/
public void refreshCombatTime() { public void refreshCombatTime() {
this.combattime = Instant.now().getEpochSecond()+ PreventStabby.getPlugin().getConfigCache().getCombat_time(); this.combattime = Instant.now().getEpochSecond()+ PreventStabby.getPlugin().getConfigCache().getCombat_time();
} }
public boolean getLastCombatCheck() { protected boolean getLastCombatCheck() {
return lastCombatCheck; return lastCombatCheck;
} }
public void setLastCombatCheck(boolean bool) { protected void setLastCombatCheck(boolean bool) {
lastCombatCheck = bool; lastCombatCheck = bool;
} }
public void setLoginTimestamp(long loginTimestamp) { protected void setLoginTimestamp(long loginTimestamp) {
this.loginTimestamp = loginTimestamp + PreventStabby.getPlugin().getConfigCache().getLogin_protection_time()-1; this.loginTimestamp = loginTimestamp + PreventStabby.getPlugin().getConfigCache().getLogin_protection_time()-1;
} }
public long getLoginTimestamp() { protected long getLoginTimestamp() {
return loginTimestamp; return loginTimestamp;
} }
public void setTeleportTimestamp(long teleportTimestamp) { protected void setTeleportTimestamp(long teleportTimestamp) {
this.teleportTimestamp = teleportTimestamp + PreventStabby.getPlugin().getConfigCache().getTeleport_protection_time()-1; this.teleportTimestamp = teleportTimestamp + PreventStabby.getPlugin().getConfigCache().getTeleport_protection_time()-1;
} }
public long getTeleportTimestamp() { protected long getTeleportTimestamp() {
return teleportTimestamp; return teleportTimestamp;
} }
/**
* Returns player's current combat state.
* @return Player's current combat state.
*/
public boolean isInCombat() { public boolean isInCombat() {
return inCombat; return inCombat;
} }
public void setInCombat(boolean inCombat) { protected void setInCombat(boolean inCombat) {
this.inCombat = inCombat; this.inCombat = inCombat;
} }
} }
@@ -1,7 +1,6 @@
package me.youhavetrouble.preventstabby.listeners.player; package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -1,4 +1,4 @@
package me.youhavetrouble.preventstabby.listeners.player; package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData; import me.youhavetrouble.preventstabby.players.PlayerData;
@@ -26,7 +26,7 @@ public class PlayerJoinAndLeaveListener implements Listener {
PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId()); PlayerData playerData = PreventStabby.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
long time = Instant.now().getEpochSecond(); long time = Instant.now().getEpochSecond();
if (playerData == null) { if (playerData == null) {
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, new PlayerData(false)); PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, new PlayerData(uuid,false));
Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> { Bukkit.getScheduler().runTaskAsynchronously(PreventStabby.getPlugin(), () -> {
PlayerData data = PreventStabby.getPlugin().getSqLite().getPlayerInfo(uuid); PlayerData data = PreventStabby.getPlugin().getSqLite().getPlayerInfo(uuid);
PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, data); PreventStabby.getPlugin().getPlayerManager().addPlayer(uuid, data);
@@ -34,7 +34,7 @@ public class PlayerJoinAndLeaveListener implements Listener {
}); });
return; return;
} }
playerData.refreshCachetime(); playerData.refreshCacheTime();
playerData.setLoginTimestamp(time); playerData.setLoginTimestamp(time);
} }
@@ -3,22 +3,26 @@ package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.api.event.PlayerLeaveCombatEvent; import me.youhavetrouble.preventstabby.api.event.PlayerLeaveCombatEvent;
import me.youhavetrouble.preventstabby.config.ConfigCache; import me.youhavetrouble.preventstabby.config.ConfigCache;
import me.youhavetrouble.preventstabby.hooks.WorldGuardHook;
import me.youhavetrouble.preventstabby.util.CombatTimer; import me.youhavetrouble.preventstabby.util.CombatTimer;
import me.youhavetrouble.preventstabby.util.PluginMessages; import me.youhavetrouble.preventstabby.util.PluginMessages;
import lombok.Getter; import lombok.Getter;
import me.youhavetrouble.preventstabby.util.PvpState;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import javax.annotation.Nullable;
import java.time.Instant; import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerManager { public class PlayerManager {
@Getter @Getter
HashMap<UUID, PlayerData> playerList = new HashMap<>(); ConcurrentHashMap<UUID, PlayerData> playerList = new ConcurrentHashMap<>();
private PvpState pvpForcedState = PvpState.NONE;
public final BukkitTask combatTrackerTask; public final BukkitTask combatTrackerTask;
@@ -29,15 +33,12 @@ public class PlayerManager {
} }
combatTrackerTask = Bukkit.getScheduler().runTaskTimerAsynchronously(PreventStabby.getPlugin(), () -> { combatTrackerTask = Bukkit.getScheduler().runTaskTimerAsynchronously(PreventStabby.getPlugin(), () -> {
Iterator<PlayerData> iterator = playerList.values().iterator(); for (PlayerData playerData : playerList.values()) {
while (iterator.hasNext()) {
PlayerData playerData = iterator.next();
UUID uuid = playerData.getPlayerUuid(); UUID uuid = playerData.getPlayerUuid();
if (!CombatTimer.isInCombat(uuid)) { if (!CombatTimer.isInCombat(uuid)) {
if (playerData.getLastCombatCheck()) { if (playerData.getLastCombatCheck()) {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null) if (player == null) continue;
return;
PlayerLeaveCombatEvent playerLeaveCombatEvent = new PlayerLeaveCombatEvent(player); PlayerLeaveCombatEvent playerLeaveCombatEvent = new PlayerLeaveCombatEvent(player);
Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> { Bukkit.getScheduler().runTask(PreventStabby.getPlugin(), () -> {
Bukkit.getPluginManager().callEvent(playerLeaveCombatEvent); Bukkit.getPluginManager().callEvent(playerLeaveCombatEvent);
@@ -59,41 +60,57 @@ public class PlayerManager {
} }
public void refreshPlayersCacheTime(UUID uuid) { /**
playerList.get(uuid).refreshCachetime(); * Sets player in combat and sets combat time to the interval set in config.
} * @see PlayerData#refreshCombatTime()
*/
public void refreshPlayersCombatTime(UUID uuid) { public void refreshPlayersCombatTime(UUID uuid) {
try {
PlayerData data = playerList.get(uuid); PlayerData data = playerList.get(uuid);
if (data == null) if (data == null) return;
return;
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null || player.isDead()) if (player == null || player.isDead()) return;
return;
data.refreshCombatTime(); data.refreshCombatTime();
data.setInCombat(true); data.setInCombat(true);
} catch (Exception ignored) {
}
} }
/**
* 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) { public PlayerData getPlayer(UUID uuid) {
return playerList.get(uuid); return playerList.get(uuid);
} }
public void addPlayer(UUID uuid, PlayerData data) { protected void addPlayer(UUID uuid, PlayerData data) {
playerList.put(uuid, data); playerList.put(uuid, data);
} }
/**
* Returns true if player has personal pvp enabled, false otherwise.
* @param uuid Player's UUID.
* @return True if player has personal pvp enabled, false otherwise.
* @see PlayerData#isPvpEnabled()
*/
public boolean getPlayerPvPState(UUID uuid) { public boolean getPlayerPvPState(UUID uuid) {
return PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).isPvpEnabled(); return PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).isPvpEnabled();
} }
/**
* Sets player's personal pvp state.
* @param uuid Player's UUID.
* @param state Pvp state to set.
* @see PlayerData#setPvpEnabled(boolean)
*/
public void setPlayerPvpState(UUID uuid, boolean state) { public void setPlayerPvpState(UUID uuid, boolean state) {
PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).setPvpEnabled(state); PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).setPvpEnabled(state);
} }
/**
* Toggles player's personal pvp state.
* @param uuid Player's UUID.
* @return Player's personal pvp state after the change.
*/
public boolean togglePlayerPvpState(UUID uuid) { public boolean togglePlayerPvpState(UUID uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache(); SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (smartCache.getPlayerData(uuid).isPvpEnabled()) { if (smartCache.getPlayerData(uuid).isPvpEnabled()) {
@@ -105,32 +122,77 @@ public class PlayerManager {
} }
} }
/**
* Check if attacker can harm the victim. Both of them have to have personal pvp enabled and none of them can have
* any kind of spawn or teleport protection.
* @param attacker Atacker's UUID.
* @param victim Victim's UUID.
* @param sendDenyMessage Should plugin send a message that there was attempt at damaging to both players?
* @return Whenever attacker can harm the victim.
*/
public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage) { public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage) {
return canDamage(attacker, victim, sendDenyMessage, true); return canDamage(attacker, victim, sendDenyMessage, true);
} }
/**
* Check if attacker can harm the victim.
* @param attacker Atacker's UUID.
* @param victim Victim's UUID.
* @param sendDenyMessage Should plugin send a message that there was attempt at damaging to both players?
* @param checkVictimSpawnProtection Should teleport and spawn protections be taken into account?
* @return Whenever attacker can harm the victim.
*/
public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage, boolean checkVictimSpawnProtection) { public boolean canDamage(UUID attacker, UUID victim, boolean sendDenyMessage, boolean checkVictimSpawnProtection) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache();
String attackerMessage = sendDenyMessage ? config.getCannot_attack_attacker() : null;
String victimMessage = sendDenyMessage ? config.getCannot_attack_victim() : null;
return canDamage(attacker, victim, attackerMessage, victimMessage, checkVictimSpawnProtection);
}
if (hasLoginProtection(attacker) || hasTeleportProtection(attacker)) /**
return false; * Check if attacker can harm the victim.
* @param attacker Atacker's UUID.
* @param victim Victim's UUID.
* @param attackerDenyMessage Message that action was denied to the attacker.
* @param victimDenyMessage Message that action was denied to the victim.
* @param checkVictimSpawnProtection Should teleport and spawn protections be taken into account?
* @return Whenever attacker can harm the victim.
*/
public boolean canDamage(UUID attacker, UUID victim, @Nullable String attackerDenyMessage, @Nullable String victimDenyMessage, boolean checkVictimSpawnProtection) {
if (checkVictimSpawnProtection && hasLoginProtection(victim)) if (hasLoginProtection(attacker) || hasTeleportProtection(attacker)) return false;
return false; if (checkVictimSpawnProtection && hasLoginProtection(victim)) return false;
if (checkVictimSpawnProtection && hasTeleportProtection(victim)) return false;
if (checkVictimSpawnProtection && hasTeleportProtection(victim)) switch (pvpForcedState) {
case ENABLED:
return true;
case DISABLED:
PluginMessages.sendActionBar(attacker, PreventStabby.getPlugin().getConfigCache().getCannot_attack_pvp_force_off());
return false; return false;
case NONE:
default:
break;
}
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache(); SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
if (!smartCache.getPlayerData(attacker).isPvpEnabled()) { if (!smartCache.getPlayerData(attacker).isPvpEnabled()) {
if (sendDenyMessage) { Player attackerPlayer = Bukkit.getPlayer(attacker);
ConfigCache config = PreventStabby.getPlugin().getConfigCache(); if (PreventStabby.worldGuardHookEnabled() && attackerPlayer != null && WorldGuardHook.isPlayerForcedToPvp(attackerPlayer))
PluginMessages.sendActionBar(attacker, config.getCannot_attack_attacker()); return true;
if (attackerDenyMessage != null) {
PluginMessages.sendActionBar(attacker, attackerDenyMessage);
} }
return false; return false;
} }
if (!smartCache.getPlayerData(victim).isPvpEnabled()) { if (!smartCache.getPlayerData(victim).isPvpEnabled()) {
if (sendDenyMessage) { Player victimPlayer = Bukkit.getPlayer(victim);
if (PreventStabby.worldGuardHookEnabled() && victimPlayer != null && WorldGuardHook.isPlayerForcedToPvp(victimPlayer))
return true;
if (victimDenyMessage != null) {
ConfigCache config = PreventStabby.getPlugin().getConfigCache(); ConfigCache config = PreventStabby.getPlugin().getConfigCache();
PluginMessages.sendActionBar(attacker, config.getCannot_attack_victim()); PluginMessages.sendActionBar(attacker, config.getCannot_attack_victim());
} }
@@ -140,8 +202,8 @@ public class PlayerManager {
} }
/** /**
* @param uuid Player UUIDs * @param uuid Player UUIDs.
* @return true if any of the provided UUIDs has spawn protection * @return True if any of the provided UUIDs has spawn protection.
*/ */
public boolean hasLoginProtection(UUID... uuid) { public boolean hasLoginProtection(UUID... uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache(); SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
@@ -152,9 +214,28 @@ public class PlayerManager {
return false; return false;
} }
/**
* @param uuid Player UUID.
* @return True if player tied to the uuid currently has teleport protection.
*/
public boolean hasTeleportProtection(UUID uuid) { public boolean hasTeleportProtection(UUID uuid) {
SmartCache smartCache = PreventStabby.getPlugin().getSmartCache(); SmartCache smartCache = PreventStabby.getPlugin().getSmartCache();
return Instant.now().getEpochSecond() < smartCache.getPlayerData(uuid).getTeleportTimestamp(); return Instant.now().getEpochSecond() < smartCache.getPlayerData(uuid).getTeleportTimestamp();
} }
/**
* 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;
}
} }
@@ -1,8 +1,6 @@
package me.youhavetrouble.preventstabby.listeners.player; package me.youhavetrouble.preventstabby.players;
import me.youhavetrouble.preventstabby.PreventStabby; import me.youhavetrouble.preventstabby.PreventStabby;
import me.youhavetrouble.preventstabby.players.PlayerData;
import me.youhavetrouble.preventstabby.players.SmartCache;
import me.youhavetrouble.preventstabby.util.PreventStabbyListener; import me.youhavetrouble.preventstabby.util.PreventStabbyListener;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -16,7 +16,7 @@ public class SmartCache {
try { try {
Player player = Bukkit.getPlayer(e.getKey()); Player player = Bukkit.getPlayer(e.getKey());
if (player != null && player.isOnline()) { if (player != null && player.isOnline()) {
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCacheTime(e.getKey()); e.getValue().refreshCacheTime();
} }
} catch (NullPointerException ignored) {} } catch (NullPointerException ignored) {}
} }
@@ -32,8 +32,9 @@ public class SmartCache {
public PlayerData getPlayerData(UUID uuid) { public PlayerData getPlayerData(UUID uuid) {
// Try to get data from cache and refresh it // Try to get data from cache and refresh it
try { try {
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCacheTime(uuid); PlayerData data = PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid);
return PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid); data.refreshCacheTime();
return data;
} catch (NullPointerException e) { } catch (NullPointerException e) {
// If player data is not in cache get it from database and put into cache // If player data is not in cache get it from database and put into cache
try { try {
@@ -42,7 +43,7 @@ public class SmartCache {
return playerData; return playerData;
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
// Return false if database call fails // Return false if database call fails
return new PlayerData(false); return new PlayerData(uuid,false);
} }
} }
} }
@@ -53,7 +54,7 @@ public class SmartCache {
PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).setPvpEnabled(state); PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).setPvpEnabled(state);
} }
// Update the database aswell // Update the database aswell
PreventStabby.getPlugin().getSqLite().updatePlayerInfo(uuid, new PlayerData(state)); PreventStabby.getPlugin().getSqLite().updatePlayerInfo(uuid, new PlayerData(uuid, state));
} }
@@ -11,8 +11,7 @@ public class CombatTimer {
public static void refreshPlayersCombatTime(UUID uuid) { public static void refreshPlayersCombatTime(UUID uuid) {
try { try {
long now = Instant.now().getEpochSecond(); long combattime = PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).getCombatTime();
long combattime = PreventStabby.getPlugin().getSmartCache().getPlayerData(uuid).getCombattime();
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null || !player.isOnline()) return; if (player == null || !player.isOnline()) return;
@@ -22,7 +21,7 @@ public class CombatTimer {
if (playerEnterCombatEvent.isCancelled()) return; if (playerEnterCombatEvent.isCancelled()) return;
PreventStabby.getPlugin().getPlayerManager().refreshPlayersCombatTime(uuid); PreventStabby.getPlugin().getPlayerManager().refreshPlayersCombatTime(uuid);
if (combattime <= now) { if (combattime <= 0) {
PluginMessages.sendActionBar(uuid, PreventStabby.getPlugin().getConfigCache().getEntering_combat()); PluginMessages.sendActionBar(uuid, PreventStabby.getPlugin().getConfigCache().getEntering_combat());
} }
}); });
@@ -38,7 +37,7 @@ public class CombatTimer {
public static boolean isInCombat(UUID uuid) { public static boolean isInCombat(UUID uuid) {
try { try {
return PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).getCombattime() >= Instant.now().getEpochSecond(); return PreventStabby.getPlugin().getPlayerManager().getPlayer(uuid).getCombatTime() >= Instant.now().getEpochSecond();
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
@@ -64,12 +64,12 @@ public class DatabaseSQLite {
} }
} }
Statement statement = conn.createStatement(); Statement statement = conn.createStatement();
String sql = "SELECT * FROM `players` WHERE `player_uuid` = '" + uuid.toString() + "';"; String sql = "SELECT * FROM `players` WHERE `player_uuid` = '" + uuid + "';";
statement.execute(sql); statement.execute(sql);
ResultSet result = statement.getResultSet(); ResultSet result = statement.getResultSet();
boolean state = result.getBoolean("pvpenabled"); boolean state = result.getBoolean("pvpenabled");
conn.close(); conn.close();
return new PlayerData(state); return new PlayerData(uuid, state);
} catch (SQLException throwables) { } catch (SQLException throwables) {
throwables.printStackTrace(); throwables.printStackTrace();
} }
@@ -1,50 +1,108 @@
package me.youhavetrouble.preventstabby.util; package me.youhavetrouble.preventstabby.util;
import net.md_5.bungee.api.ChatMessageType; import me.clip.placeholderapi.PlaceholderAPI;
import net.md_5.bungee.api.chat.BaseComponent; import me.youhavetrouble.preventstabby.PreventStabby;
import net.md_5.bungee.api.chat.TextComponent; import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.UUID; import java.util.UUID;
public class PluginMessages { public class PluginMessages {
public static String parseMessage(String message) { public static final MiniMessage MINIMESSAGE = MiniMessage.miniMessage();
//TODO PAPI support private static final BukkitAudiences audiences = PreventStabby.getAudiences();
return ChatColor.translateAlternateColorCodes('&', message);
public static Component parseMessage(String message) {
message = makeColorsWork('&', message);
message = makeColorsWork(LegacyComponentSerializer.SECTION_CHAR, message);
return MINIMESSAGE.deserialize(message);
} }
public static void sendMessage(Player player, String message) { public static Component parseMessage(CommandSender sender,String message) {
String parsedMessage = ChatColor.translateAlternateColorCodes('&', message); if (sender instanceof Player && isPlaceholderApiEnabled()) {
player.sendMessage(parsedMessage); Player player = (Player) sender;
message = PlaceholderAPI.setPlaceholders(player, message);
}
return parseMessage(message);
}
private static boolean isPlaceholderApiEnabled() {
return PreventStabby.getPlugin().getServer().getPluginManager().getPlugin("PlaceholderAPI") != null;
}
public static void sendMessage(CommandSender sender, String message) {
if ("".equals(message)) return;
audiences.sender(sender).sendMessage(parseMessage(sender, message));
} }
public static void sendActionBar(Player player, String message) { public static void sendActionBar(Player player, String message) {
// TODO use adventure if ("".equals(message)) return;
BaseComponent[] component = TextComponent.fromLegacyText(parseMessage(message)); Component parsedMessage = parseMessage(player, message);
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, component); audiences.player(player).sendActionBar(parsedMessage);
} }
public static void sendActionBar(UUID uuid, String message) { public static void sendActionBar(UUID uuid, String message) {
try { if ("".equals(message)) return;
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null) return;
sendActionBar(player, message); sendActionBar(player, message);
} catch (NullPointerException ignored) {}
} }
public static String parsePlayerName(Player player, String message) { public static String parsePlayerName(Player player, String message) {
message = message.replaceAll("%player%", player.getDisplayName()); message = message.replaceAll("%player%", player.getDisplayName());
return parseMessage(message); return message;
} }
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);
message = parseMessage(message); if (PreventStabby.getPlugin().getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
BaseComponent[] component = TextComponent.fromLegacyText(parseMessage(message)); message = PlaceholderAPI.setPlaceholders(player, message);
Bukkit.spigot().broadcast(component); }
audiences.all().sendMessage(parseMessage(message));
}
public static void broadcastMessage(String message) {
if ("".equals(message)) return;
audiences.all().sendMessage(parseMessage(message));
}
/**
* Swaps most legacy color codes to adventure minimessage tags.
* @param symbol Usually '&'.
* @param string String to replace symbols in.
* @return String with legacy color codes replaced with minimessage tags.
*/
private static String makeColorsWork(Character symbol, String string) {
// Adventure and ChatColor do not like each other, so this is a thing.
string = string.replaceAll(symbol + "0", "<black>");
string = string.replaceAll(symbol + "1", "<dark_blue>");
string = string.replaceAll(symbol + "2", "<dark_green>");
string = string.replaceAll(symbol + "3", "<dark_aqua>");
string = string.replaceAll(symbol + "4", "<dark_red>");
string = string.replaceAll(symbol + "5", "<dark_purple>");
string = string.replaceAll(symbol + "6", "<gold>");
string = string.replaceAll(symbol + "7", "<gray>");
string = string.replaceAll(symbol + "8", "<dark_gray>");
string = string.replaceAll(symbol + "9", "<blue>");
string = string.replaceAll(symbol + "a", "<green>");
string = string.replaceAll(symbol + "b", "<aqua>");
string = string.replaceAll(symbol + "c", "<red>");
string = string.replaceAll(symbol + "d", "<light_purple>");
string = string.replaceAll(symbol + "e", "<yellow>");
string = string.replaceAll(symbol + "f", "<white>");
string = string.replaceAll(symbol + "k", "<obfuscated>");
string = string.replaceAll(symbol + "l", "<bold>");
string = string.replaceAll(symbol + "m", "<strikethrough>");
string = string.replaceAll(symbol + "n", "<underlined>");
string = string.replaceAll(symbol + "o", "<italic>");
string = string.replaceAll(symbol + "r", "<reset>");
return string;
} }
} }
@@ -0,0 +1,16 @@
package me.youhavetrouble.preventstabby.util;
public enum PvpState {
/**
* PvP Force enabled
*/
ENABLED,
/**
* PvP force disabled
*/
DISABLED,
/**
* PvP not forced
*/
NONE
}
@@ -38,20 +38,24 @@ public class Util {
ConfigCache config = PreventStabby.getPlugin().getConfigCache(); ConfigCache config = PreventStabby.getPlugin().getConfigCache();
if (!PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(attacker)) {
PluginMessages.sendActionBar(attacker, config.getCannot_attack_mounts_attacker());
return true;
}
Set<UUID> playerPassengersWithPvpEnabled = new HashSet<>(); Set<UUID> playerPassengersWithPvpEnabled = new HashSet<>();
boolean hasPlayerPassengers = false;
for (Entity passenger : mount.getPassengers()) { for (Entity passenger : mount.getPassengers()) {
if (!(passenger instanceof Player)) continue; if (!(passenger instanceof Player)) continue;
Player player = (Player) passenger; Player player = (Player) passenger;
hasPlayerPassengers = true;
if (PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(player.getUniqueId())) if (PreventStabby.getPlugin().getPlayerManager().getPlayerPvPState(player.getUniqueId()))
playerPassengersWithPvpEnabled.add(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()) { if (playerPassengersWithPvpEnabled.isEmpty()) {
PluginMessages.sendActionBar(attacker, config.getCannot_attack_mounts_victim()); PluginMessages.sendActionBar(attacker, config.getCannot_attack_mounts_victim());
return true; return true;
+28 -8
View File
@@ -1,29 +1,49 @@
name: TogglePvP name: PreventStabby
version: ${project.version} version: ${project.version}
main: eu.endermite.togglepvp.PreventStabby main: me.youhavetrouble.preventstabby.PreventStabby
authors: [YouHaveTrouble] authors: [YouHaveTrouble]
api-version: 1.13 api-version: 1.13
description: Stop people from getting stabbed! description: Stop people from getting stabbed!
soft-depend:
- WorldGuard
- PlaceholderAPI
commands: commands:
preventstabby: preventstabby:
permission: preventstabby.command
aliases: aliases:
- pvp - pvp
permissions: permissions:
toglepvp.combatcommandblock.bypass: preventstabby.combatcommandblock.bypass:
default: op default: op
description: Allows to bypass combat command blocker description: Allows to bypass combat command blocker
toglepvp.combatteleportblock.bypass: preventstabby.combatteleportblock.bypass:
default: op default: op
description: Allows to bypass combat teleport blocker description: Allows to bypass combat teleport blocker
togglepvp.command: preventstabby.command:
default: true default: true
description: Allows usage of /pvp command description: Allows usage of /pvp command
togglepvp.command.toggle: preventstabby.command.help:
default: true
description: Allows usage of /pvp help command
children:
preventstabby.command: true
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
togglepvp.command.toggle.others: children:
preventstabby.command: true
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
togglepvp.command.reload: children:
preventstabby.command: true
preventstabby.command.toggle.global:
default: op
description: Allows usage of /pvp override <enabled/disabled/none> command
children:
preventstabby.command: true
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