Compare commits

..

100 Commits

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