199 Commits

Author SHA1 Message Date
c9f14dd29d 0.10 doesn't display properly. Let's just go straight to 1.0 2022-04-08 21:42:08 -05:00
f9a504658c Plex 0.10 2022-04-08 21:29:39 -05:00
a58b6fbba8 Merge branch 'cmdblocker' of https://github.com/plexusorg/Plex 2022-04-08 21:23:38 -05:00
0f88f7c8fd Change package name 2022-04-08 21:23:22 -05:00
cf45863632 fix and improve 👍
fix !
2022-04-08 22:13:51 -04:00
187b177b01 add inline comments 2022-04-08 19:05:20 -05:00
79b687c80d add debug 2022-04-08 18:56:45 -05:00
271b8a1df4 idk fix it 2022-04-08 18:19:06 -05:00
b939219fc9 Merge branch 'master' of https://github.com/plexusorg/Plex into cmdblocker 2022-04-08 16:57:11 -05:00
9297eb6703 Try to improve things 2022-04-08 16:57:09 -05:00
11c014b822 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-08 16:37:20 -05:00
3039125b48 Improve it more 2022-04-08 16:37:13 -05:00
15b50ac8ae fix mistake 2022-04-08 14:02:56 -04:00
d756dcb2f4 final update before looking into...
...reusing preexisting plex code for different parts. dont merge until review has been done.
2022-04-08 12:26:46 -04:00
797372f4b6 AAAAA PANIC
CONSISTENCY...GONE...
2022-04-08 11:12:35 -04:00
fad5455f76 small changes
tweaks, if you will.
2022-04-08 11:07:11 -04:00
9f0b8fb56a fix ranks in commandblocker for inactive admins 2022-04-08 11:04:55 -04:00
245f7dd4d3 update command blocker usage 2022-04-08 10:41:28 -04:00
a784ffbc8a fixes and other things like that 2022-04-08 10:29:22 -04:00
13a458859c me when i dont finish my own code 2022-04-08 10:23:08 -04:00
5f7a89d7cd mOre FEATURES!! (+fixes) 2022-04-08 10:17:39 -04:00
1c4f43187d just in case... 2022-04-08 09:49:35 -04:00
e84e39b170 update usage for command blocker 2022-04-08 09:47:22 -04:00
af7ca9acef tele was right...this was wrong...
match mode now acts simply, as one may intially expect
2022-04-08 09:43:23 -04:00
2a23759d34 remove debug message LMAO 2022-04-08 09:39:56 -04:00
afe178b2c2 i forgor
to register the service. also removed useless arraylist
2022-04-08 09:36:52 -04:00
d33c8df675 add fleek to devs list 2022-04-08 00:40:42 -07:00
92eb900f22 patch 2022-04-08 03:07:47 -04:00
15d9eab91e final i think update yAY 2022-04-08 02:55:41 -04:00
78f3127dc9 part DONE 2022-04-08 02:49:59 -04:00
9bb316b80b part 4.... . .. .
incomplete
2022-04-08 02:36:56 -04:00
e402cd1fe5 Reorganize the config 2022-04-08 01:26:18 -05:00
4320e789d4 part 3...? 2022-04-08 02:15:25 -04:00
def099c3a3 Band aid fix 2022-04-08 01:06:34 -05:00
dd94613b99 part 2 2022-04-08 01:42:05 -04:00
583394d22e part 1 2022-04-08 01:16:05 -04:00
6071567eb3 Add some color 2022-04-08 00:03:59 -05:00
898dace3c1 Set different verbosity levels for the update messages 2022-04-08 00:01:02 -05:00
294f8db528 fix baby mobs, clean a few imports 2022-04-07 23:47:32 -04:00
a89cca1baa disallow tnt minecarts by default
in the future, tnt will be toggleable and this will be unnecessary
2022-04-07 19:52:36 -04:00
fb17c4c858 Add smite command and a few other fixes 2022-04-07 18:23:38 -05:00
6f7fcc5b51 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-07 19:09:25 -04:00
1652dd1ffa fix dispenser item decreasing when using spawn eggs 2022-04-07 19:09:23 -04:00
24310b00a5 Update Jenkinsfile 2022-04-07 16:28:00 -05:00
077cbff22b Update Jenkinsfile 2022-04-07 16:25:59 -05:00
aa0d9a0326 Update Jenkinsfile 2022-04-07 16:21:46 -05:00
974a5cbe2b Update Jenkinsfile 2022-04-07 16:19:45 -05:00
603309c79d Update Jenkinsfile 2022-04-07 16:16:21 -05:00
53c888aed1 Update Jenkinsfile 2022-04-07 16:09:22 -05:00
890f847c2f Allow specifying branch for update checking 2022-04-07 15:59:09 -05:00
1b7a06794b fix...???!?!???!! 2022-04-07 14:37:33 -04:00
6e149d07c6 remove argument-less updateJar 2022-04-07 14:22:53 -04:00
a43072cd1d i forgor to pass this variable lmao 2022-04-07 14:06:38 -04:00
d10f738304 add command sign blocking
todo: move all these blockings to blackout
2022-04-07 14:05:15 -04:00
3666379645 a few fixes & optimizations 2022-04-07 13:12:38 -04:00
1496e5a55c make disabled sound relative to what is disabled 2022-04-07 12:55:12 -04:00
e9e5db7c2b mob blocker
yay :D
2022-04-07 10:59:04 -04:00
bb78816dec developer'd 2022-04-07 10:27:57 -04:00
8801c740a6 fix message lol 2022-04-07 10:09:07 -04:00
0187b4ef84 remove a part that doesnt work anyways
lol
2022-04-07 09:47:11 -04:00
fa75ea945d Merge remote-tracking branch 'origin/master' 2022-04-07 00:37:46 -07:00
9ddf3ceeda fix mongo support 2022-04-07 00:37:31 -07:00
c9d3b26930 Forgot to do it here 2022-04-07 02:16:37 -05:00
02393f6be3 Change update URL 2022-04-07 02:04:36 -05:00
804e0af63c Only publish if its the master branch 2022-04-07 01:55:59 -05:00
85eff9a26d I have no idea how to securely set credentials 2022-04-07 01:32:06 -05:00
d4ddf09c32 OF COURSE 2022-04-07 01:17:53 -05:00
2d3f017c01 This should work 2022-04-07 01:16:22 -05:00
b7926830f0 WHAT AM I SUPPOSED TO DO 2022-04-07 00:26:24 -05:00
0430a64ccf Lets try this 2022-04-07 00:25:03 -05:00
ff4f0a30c7 it would help if there was better documentation 2022-04-07 00:19:47 -05:00
498aa8f2fd I am an idiot 2022-04-07 00:11:59 -05:00
7e3c48536a So this is what it is 2022-04-07 00:07:26 -05:00
6527e51159 Use Gradle 2022-04-07 00:05:15 -05:00
6a91d6a761 Update Jenkinsfile 2022-04-07 00:01:06 -05:00
9708f871c8 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-06 23:49:50 -05:00
eaa40e7013 Attempt to fix updater 2022-04-06 23:49:45 -05:00
c6aa4cf0a4 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-07 00:41:31 -04:00
72b8774731 add dispenser filter & touch up spawn egg filter 2022-04-07 00:41:29 -04:00
ca18b12164 Try this 2022-04-06 23:14:44 -05:00
ea862e152f check for update status instead of sending msg 2022-04-06 21:08:03 -07:00
639365bd52 realize spawneggservice is useless 2022-04-07 00:06:18 -04:00
262b600b11 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-07 00:02:57 -04:00
199832e020 add block blocker
in the future, this will be it's own module or something
2022-04-07 00:02:45 -04:00
1f653ab5df Add /plex update 2022-04-06 20:55:54 -07:00
5012d0478b Switch UUID in PlexPlayer to an actual UUID and fix notes 2022-04-06 22:55:01 -05:00
00d00eb4e5 Merge pull request #11 from plexusorg/spawneggfilter
add spawn egg filtering
2022-04-06 21:50:36 -05:00
c18eb6fedd Merge branch 'master' into spawneggfilter 2022-04-06 22:50:02 -04:00
96de4cdb1d fix!! 2022-04-06 22:46:21 -04:00
b22a36948a this isnt working 2022-04-06 21:39:45 -05:00
21bef1280d fix autowiping
so it can work with reloads
2022-04-06 22:08:51 -04:00
34d1eafaaf reload services and add ids to notes 2022-04-06 19:05:29 -07:00
48bf9bdbe5 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-06 21:00:33 -05:00
41e81449bd half working 2022-04-06 21:00:28 -05:00
705500bddd autowipe + toggledrops
yay!
2022-04-06 21:48:51 -04:00
03e5833f0a add item builder class 2022-04-06 18:39:13 -07:00
f2ee3bf7a5 begin notes system
store task id
2022-04-06 17:38:15 -07:00
f62e0a42d1 i have no idea what im doing 2022-04-06 19:18:12 -05:00
2105f51b44 comment out useless teleporting
not necessary lol
2022-04-06 20:16:16 -04:00
fcf41fe58e add spawn egg filtering 2022-04-06 20:06:50 -04:00
1d8ce6001c add getting players by username 2022-04-06 16:59:34 -07:00
0b9f9d74ba add /mp, and refine /rd to only non-mobs by default
awesome
2022-04-06 19:42:47 -04:00
035b579fc1 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-06 18:01:34 -05:00
f547f10e0f Fix typo 2022-04-06 18:01:29 -05:00
9eacb2287a Add /entitywipe + fix messageComponent
lol
2022-04-06 18:43:49 -04:00
e0632644ab Fix the updater 2022-04-05 15:46:21 -05:00
7420e7e721 Optimize imports 2022-04-05 15:40:42 -05:00
7ed0549ec6 Fixed a few bugs 2022-04-05 15:40:25 -05:00
2fcf44c6a8 Merge pull request #9 from plexusorg/punishments
so far it is working but the only thing preventing me from going to f…
2022-04-05 13:15:46 -05:00
f5a89384a0 Remove commented out things 2022-04-05 13:14:53 -05:00
08bdeaac48 Merge branch 'master' into punishments 2022-04-05 13:10:08 -05:00
56db357743 Revert "Lets try something"
This reverts commit 3c4eea4c3c.
2022-04-04 18:48:21 -05:00
3c4eea4c3c Lets try something 2022-04-04 18:45:09 -05:00
8a0c354682 actually fix it this time 2022-04-04 15:22:04 -05:00
c8a64cc9cb Fix NPE in unban command 2022-04-04 15:18:20 -05:00
6f4bc5aec1 so far it is working but the only thing preventing me from going to fully asynchronous calls for punishments is httpd... 2022-04-04 01:36:50 -07:00
35d436bb61 remove <v> and swap it to {number} for messages 2022-04-03 21:07:48 -07:00
511506348f Ban service now works with JSON 2022-04-03 17:59:16 -05:00
894cda2ede Remove some of this duplicate code 2022-04-03 16:45:32 -05:00
470f652e0b Actually add IPs to punishment 2022-04-02 18:03:58 -05:00
0c6d90e653 Merge remote-tracking branch 'origin/master' 2022-04-02 13:14:58 -07:00
c41c09710d update gson to fix error with parsing arrays 2022-04-02 13:14:37 -07:00
fd9fafb6bb I'd say this is pretty important 2022-04-02 15:12:38 -05:00
aa18e5d11a Add new IPs 2022-04-02 14:55:47 -05:00
a4ce9511fd this is enough coding for one day 2022-04-02 01:25:24 -05:00
82343815dd Remove debug 2022-04-02 00:36:04 -05:00
4d0cf96b97 Revert "Let's try something"
This reverts commit ccdefe97a3.
2022-04-02 00:32:04 -05:00
ccdefe97a3 Let's try something 2022-04-01 23:56:56 -05:00
787458f1df Remove debugging from command loader 2022-04-01 23:21:37 -05:00
0f898380db this is why we need an API 2022-04-01 23:09:43 -05:00
c484f4b2b2 Not tested, remove automatic loading of properties 2022-04-01 23:04:51 -05:00
1f2eed78de add custom module config class
fix npe in tab listener
add getter for indefinite bans
fix npe in plex cmd
remove spring boot and add jetty
2022-04-01 20:58:03 -07:00
099680d068 Add missing retention policy to annotation classes 2022-04-02 12:46:04 +11:00
90cccb804a Remove this 2022-04-01 16:13:09 -05:00
bb92805fa5 Add caching to the updater 2022-04-01 15:00:55 -05:00
bbb41aa052 Good thing we haven't had a release yet! 2022-04-01 14:34:12 -05:00
228b67a592 Nope 2022-04-01 14:31:05 -05:00
986a9c6f22 lets see if we can do this 2022-04-01 14:28:15 -05:00
af40217a57 Revamp Maven publishing 2022-04-01 14:24:04 -05:00
be428d58f2 Fix formatting 2022-04-01 03:17:42 -05:00
48fb4f919a Make update checking better 2022-04-01 03:08:17 -05:00
9ebbeb3c15 Revamp update checker 2022-04-01 02:54:22 -05:00
8ebb1c91a0 add get all admins method to get all admin objects 2022-03-31 22:47:15 -07:00
f0a05a8256 Try to automate Jenkins publishing 2022-03-31 02:01:29 -05:00
20fe89edbc Merge remote-tracking branch 'origin/master' 2022-03-30 23:56:11 -07:00
47b3054739 Allow publishing snapshots once again 2022-03-31 01:54:25 -05:00
ad2273f5ab Merge remote-tracking branch 'origin/master' 2022-03-30 23:51:45 -07:00
6e768c0e0f find player by ip + reload system on /plex reload 2022-03-30 23:50:53 -07:00
6d30b2a14d Create LICENSE.md 2022-03-31 01:40:10 -05:00
d350ff4542 Update dependencies 2022-03-27 00:42:18 -05:00
7bc42c25a7 ok it actually works now 2022-03-26 17:53:25 -05:00
e5ae89a072 try this 2022-03-26 17:50:59 -05:00
56e71b10fa idk why its not working 2022-03-26 17:49:03 -05:00
cc2ba42e87 Oops 2022-03-26 17:46:58 -05:00
df87cd73fd fix a few things 2022-03-26 17:44:26 -05:00
222eec2eac do it for both 2022-03-26 17:37:58 -05:00
94da9ff7fe Set author to jenkins 2022-03-26 17:31:36 -05:00
def38eed06 fix it all 2022-03-26 17:22:08 -05:00
85f91b046b Delete build.properties 2022-03-26 16:40:04 -05:00
8ae3f6a71b Update .gitignore 2022-03-26 16:39:05 -05:00
4646b87893 Add build number 2022-03-26 16:36:29 -05:00
0d662c18ea Test build number 2022-03-26 16:29:25 -05:00
635c1beba7 Revert "intellij "code cleanup" just adds final everywhere"
This reverts commit eb8571b6e9.
2022-03-25 00:54:21 -05:00
eb8571b6e9 intellij "code cleanup" just adds final everywhere 2022-03-25 00:52:06 -05:00
273dd8a5ef Add blockedit command 2022-03-25 00:45:55 -05:00
262368ed18 Optimize imports 2022-03-20 20:06:36 -05:00
d0b89d995c Add global gamerules 2022-03-20 20:05:50 -05:00
580f87f28b Move mute into its own class 2022-03-20 13:13:34 +11:00
117852e6d0 Few changes to toggleable listener system 2022-03-20 13:04:55 +11:00
d55886dcbd Back to snapshot 2022-03-19 15:20:52 -05:00
bce3d90cc0 Plex 0.9 2022-03-19 15:04:48 -05:00
1b7511e817 Reflections API for listeners 2022-03-19 14:27:55 -05:00
159ed046cb Removed deprecated methods from custom world and fixed a missing Jedis check 2022-03-19 20:38:09 +11:00
d669da9f28 Prevent all commands from being loaded 2022-03-19 15:17:43 +11:00
172080576c Merge pull request #7 from PlexDevelopment/reflection
Use Google's reflection library to register commands
2022-03-18 22:44:18 -05:00
cc97612101 Use Google's reflection library to register commands 2022-03-19 14:33:23 +11:00
6a569bb638 Fix many bugs 2022-03-18 20:12:05 -05:00
d8c6c3b4a8 Improvements for servers using permissions 2022-03-18 19:01:20 -05:00
d7cbbc8d52 Fix errors when unloading modules with listeners 2022-03-18 14:15:05 -05:00
06e51926be Major changes
- Convert prefixes to Component
- Styling improvements to the list command
- Fix tab completing on plex command
- Allow console to check ranks of other players
- Add coloring in tab for admins
- Add color field to ranks and titles
- Fix debug logging not working
2022-03-17 20:18:35 -05:00
3c0b79ba06 Start getting rid of legacy strings 2022-03-17 17:16:17 -05:00
8f7fed5835 Taah broke it 2022-03-10 19:55:03 -06:00
aa3aa7cb0e Update usage 2022-03-06 00:43:37 -06:00
8e9acec1ff Bump to snapshot 2022-03-06 00:31:59 -06:00
afd793cdba Plex 0.8 2022-03-05 22:54:02 -06:00
1d9662acde Merge branch 'master' of https://github.com/PlexDevelopment/Plex 2022-03-05 19:56:51 -06:00
89199eb580 Let's not make ourselves permbanned by default 2022-03-05 19:56:46 -06:00
0aa9669f5f lol i disabled modules on reload 2022-03-05 17:22:30 -08:00
46d8debd18 - don't reload indefinite bans 2022-03-05 17:20:51 -08:00
69541a20b8 - Add command and listener support 2022-03-05 17:17:14 -08:00
87ddf355b5 - Begin BETA module system 2022-03-05 17:04:34 -08:00
2804f6bc41 - Change indefinite bans config system to be more organized
- Store indefinite bans through an object instead
- Add debug redis messages
- Make loading keys from the jar optional
2022-03-05 15:44:38 -08:00
aa5e184a56 Don't check for updates if it's a snapshot version 2022-03-05 17:28:52 -06:00
0a3594370a Merge pull request #5 from PlexDevelopment/dev/1.18.2
Update to 1.18.2
2022-03-04 15:50:47 -06:00
2cdd3a0e78 Merge branch 'master' into dev/1.18.2 2022-03-04 15:50:34 -06:00
14fb24a380 Bump to 0.8-SNAPSHOT 2022-03-03 19:51:07 -06:00
e258e27814 Replace with Kyori 2022-03-03 16:56:52 -06:00
41f4029877 Merge branch 'master' of https://github.com/PlexDevelopment/Plex into dev/1.18.2 2022-03-03 15:45:51 -06:00
0b5425b8d2 Begin work on 1.18.2
- Add update checking
- World generation is broken
- Won't compile unless 1.18.2 is in your local Maven repository
- No longer need MiniMessage bundled in Plex
- Customizable namehistory
- Set comments in config.yml if they're missing
2022-03-03 15:45:19 -06:00
113 changed files with 5232 additions and 1385 deletions

2
.gitignore vendored
View File

@ -1,6 +1,8 @@
/.idea/
/.idea/codeStyles/codeStyleConfig.xml
*.iml
/target/
/src/main/resources/build.properties
# OS
.DS_Store

32
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,32 @@
pipeline {
agent any
stages {
stage("build") {
steps {
withGradle {
sh "./gradlew build javadoc --no-daemon"
}
}
}
stage("publish") {
when {
branch "master"
}
steps {
withCredentials([usernamePassword(credentialsId: '85b7099f-2e65-461e-b2ce-124edec41ed6', passwordVariable: 'plexPassword', usernameVariable: 'plexUser')]) {
withGradle {
sh "./gradlew publish --no-daemon"
}
}
}
}
}
post {
always {
archiveArtifacts artifacts: "build/libs/*.jar", fingerprint: true
javadoc javadocDir: "build/docs/javadoc", keepAll: false
discordSend description: "**Build:** ${env.BUILD_NUMBER}\n**Status:** ${currentBuild.currentResult}", enableArtifactsList: true, footer: "Built with Jenkins", link: env.BUILD_URL, result: currentBuild.currentResult, scmWebUrl: "https://github.com/plexusorg/Plex", showChangeset: true, title: env.JOB_NAME, webhookURL: env.PLEX_WEBHOOK_URL
cleanWs()
}
}
}

674
LICENSE.md Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -19,34 +19,36 @@ repositories {
url = uri("https://repo.maven.apache.org/maven2/")
}
maven {
name = "sonatype-oss-snapshots"
url = uri("https://oss.sonatype.org/content/repositories/snapshots/")
}
mavenCentral()
}
dependencies {
library "org.projectlombok:lombok:1.18.22"
annotationProcessor "org.projectlombok:lombok:1.18.22"
library "org.json:json:20211205"
library "org.json:json:20220320"
library "commons-io:commons-io:2.11.0"
library "dev.morphia.morphia:morphia-core:2.2.3"
library "redis.clients:jedis:4.1.1"
library "org.mariadb.jdbc:mariadb-java-client:3.0.3"
library "dev.morphia.morphia:morphia-core:2.2.6"
library "redis.clients:jedis:4.2.1"
library "org.mariadb.jdbc:mariadb-java-client:3.0.4"
library "com.zaxxer:HikariCP:5.0.1"
library "org.apache.httpcomponents:httpclient:4.5.13"
library "org.apache.commons:commons-lang3:3.12.0"
compileOnly "io.papermc.paper:paper-api:1.18.1-R0.1-SNAPSHOT"
library "org.apache.maven.resolver:maven-resolver-api:1.7.3"
library "org.apache.maven.resolver:maven-resolver-impl:1.7.3"
library "org.apache.maven.resolver:maven-resolver-connector-basic:1.7.3"
library "org.apache.maven.resolver:maven-resolver-transport-http:1.7.3"
library "org.apache.maven:maven-resolver-provider:3.8.5"
library "org.eclipse.jetty:jetty-server:11.0.9"
library "org.eclipse.jetty:jetty-servlet:11.0.9"
library "org.eclipse.jetty:jetty-proxy:11.0.9"
library "com.google.code.gson:gson:2.9.0"
compileOnly "io.papermc.paper:paper-api:1.18.2-R0.1-SNAPSHOT"
implementation "org.bstats:bstats-base:3.0.0"
implementation "org.bstats:bstats-bukkit:3.0.0"
implementation("net.kyori:adventure-text-minimessage:4.2.0-SNAPSHOT") {
exclude group: "net.kyori", module: "adventure-api"
exclude group: "org.jetbrains", module: "annotations"
}
}
group = "dev.plex"
version = "0.7"
version = "1.0"
description = "Plex"
shadowJar {
@ -64,6 +66,47 @@ bukkit {
apiVersion = "1.18"
}
String getGitHash() {
def stdout = new ByteArrayOutputStream()
try {
exec {
commandLine "git", "rev-parse", "--short", "HEAD"
standardOutput = stdout
ignoreExitValue = true
}
} catch (GradleException e) {
logger.error("Couldn't determine Git head because Git is not installed. " + e.getMessage())
}
return stdout.size() > 0 ? stdout.toString().trim() : "unknown"
}
String getBuildNumber() {
def stdout = new ByteArrayOutputStream()
try {
exec {
commandLine "git", "rev-list", "HEAD", "--count"
standardOutput = stdout
ignoreExitValue = true
}
} catch (GradleException e) {
logger.error("Couldn't determine build number because Git is not installed. " + e.getMessage())
}
return stdout.size() ? stdout.toString().trim() + " (local)" : "unknown"
}
static def getDate() {
return new Date().format("MM/dd/yyyy '<light_purple>at<gold>' hh:mm:ss a")
}
task buildProperties {
ant.propertyfile(file: "$project.rootDir/src/main/resources/build.properties") {
entry(key: "buildAuthor", default: System.getenv("JENKINS_URL") != null ? "jenkins" : "unknown")
entry(key: "buildNumber", value: System.getenv("JENKINS_URL") != null ? System.getenv("BUILD_NUMBER") + " (Jenkins)" : getBuildNumber())
entry(key: "buildDate", value: getDate())
entry(key: "buildHead", value: getGitHash())
}
}
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
}
@ -73,16 +116,15 @@ publishing {
maven(MavenPublication) {
from(components.java)
}
plexReleases(MavenPublication) {
from(components.java)
}
repositories {
maven {
url("https://nexus.telesphoreo.me/repository/plex-releases/")
def releasesRepoUrl = uri("https://nexus.telesphoreo.me/repository/plex-releases/")
def snapshotsRepoUrl = uri("https://nexus.telesphoreo.me/repository/plex-snapshots/")
url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
credentials {
username = System.getenv("plex_repo_user")
password = System.getenv("plex_repo_pass")
}
}
username = System.getenv("plexUser")
password = System.getenv("plexPassword")
}
}
}
@ -95,18 +137,10 @@ tasks.withType(JavaCompile) {
tasks {
build {
dependsOn(shadowJar)
if (System.getenv("plex_repo_user") != null && System.getenv("plex_repo_pass") != null) {
if (!getVersion().toString().toLowerCase().endsWith("-snapshot")) {
dependsOn(publishPlexReleasesPublicationToMavenRepository)
}
}
finalizedBy(buildProperties)
}
javadoc {
options.memberLevel = JavadocMemberLevel.PRIVATE
}
}
task publishRelease {
dependsOn(publishPlexReleasesPublicationToMavenRepository)
}

View File

@ -3,14 +3,17 @@ package dev.plex;
import dev.plex.admin.Admin;
import dev.plex.admin.AdminList;
import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.SQLPlayerData;
import dev.plex.cache.player.MongoPlayerData;
import dev.plex.cache.player.PlayerCache;
import dev.plex.cache.player.SQLPlayerData;
import dev.plex.cache.sql.SQLNotes;
import dev.plex.cache.sql.SQLPunishment;
import dev.plex.command.blocker.CommandBlockerManager;
import dev.plex.config.Config;
import dev.plex.handlers.CommandHandler;
import dev.plex.handlers.ListenerHandler;
import dev.plex.module.ModuleManager;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.PunishmentManager;
import dev.plex.rank.RankManager;
import dev.plex.services.ServiceManager;
@ -22,21 +25,29 @@ import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.UpdateChecker;
import dev.plex.world.CustomWorld;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;
@Getter
@Setter
public class Plex extends JavaPlugin
{
public static final BuildProperties build = new BuildProperties();
private static Plex plugin;
public Config config;
public Config messages;
public Config indefBans;
public Config blockedCommands;
public File modulesFolder;
private StorageType storageType = StorageType.SQLITE;
private SQLConnection sqlConnection;
@ -46,15 +57,17 @@ public class Plex extends JavaPlugin
private MongoPlayerData mongoPlayerData;
private SQLPlayerData sqlPlayerData;
private SQLPunishment sqlPunishment;
private SQLNotes sqlNotes;
private ModuleManager moduleManager;
private RankManager rankManager;
private ServiceManager serviceManager;
private PunishmentManager punishmentManager;
private CommandBlockerManager commandBlockerManager;
private AdminList adminList;
private UpdateChecker updateChecker;
private String system;
public static Plex get()
@ -69,10 +82,18 @@ public class Plex extends JavaPlugin
config = new Config(this, "config.yml");
messages = new Config(this, "messages.yml");
indefBans = new Config(this, "indefbans.yml");
blockedCommands = new Config(this, "commands.yml");
build.load(this);
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
modulesFolder = new File(this.getDataFolder() + File.separator + "modules");
if (!modulesFolder.exists())
{
modulesFolder.mkdir();
}
moduleManager = new ModuleManager();
moduleManager.loadAllModules();
moduleManager.loadModules();
}
@Override
@ -80,15 +101,24 @@ public class Plex extends JavaPlugin
{
config.load();
messages.load();
indefBans.load();
system = config.getString("commands.permissions");
// Don't add default entries to indefinite ban file
indefBans.load(false);
blockedCommands.load();
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager.enableModules();
system = config.getString("system");
PlexLog.log("Attempting to connect to DB: {0}", plugin.config.getString("data.central.db"));
try
{
PlexUtils.testConnections();
PlexLog.log("Connected to " + storageType.name().toUpperCase());
}
catch (Exception e)
} catch (Exception e)
{
PlexLog.error("Failed to connect to " + storageType.name().toUpperCase());
e.printStackTrace();
@ -101,12 +131,11 @@ public class Plex extends JavaPlugin
Metrics metrics = new Metrics(this, 14143);
PlexLog.log("Enabled Metrics");
if (redisConnection.isEnabled())
if (redisConnection != null && redisConnection.isEnabled())
{
redisConnection.getJedis();
PlexLog.log("Connected to Redis!");
}
else
} else
{
PlexLog.log("Redis is disabled in the configuration file, not connecting.");
}
@ -114,16 +143,16 @@ public class Plex extends JavaPlugin
if (storageType == StorageType.MONGODB)
{
mongoPlayerData = new MongoPlayerData();
}
else
} else
{
sqlPlayerData = new SQLPlayerData();
sqlPunishment = new SQLPunishment();
sqlNotes = new SQLNotes();
}
new ListenerHandler();
new CommandHandler();
rankManager = new RankManager();
rankManager.generateDefaultRanks();
rankManager.importDefaultRanks();
@ -134,6 +163,9 @@ public class Plex extends JavaPlugin
punishmentManager.mergeIndefiniteBans();
PlexLog.log("Punishment System initialized");
commandBlockerManager = new CommandBlockerManager();
PlexLog.log("Command Blocker initialized");
generateWorlds();
serviceManager = new ServiceManager();
@ -153,23 +185,24 @@ public class Plex extends JavaPlugin
if (plugin.getRankManager().isAdmin(plexPlayer))
{
plugin.getAdminList().removeFromCache(UUID.fromString(plexPlayer.getUuid()));
plugin.getAdminList().removeFromCache(plexPlayer.getUuid());
}
if (mongoPlayerData != null) //back to mongo checking
{
mongoPlayerData.update(plexPlayer); //update the player's document
}
else if (sqlPlayerData != null) //sql checking
} else if (sqlPlayerData != null) //sql checking
{
sqlPlayerData.update(plexPlayer);
}
});
if (redisConnection.isEnabled() && redisConnection.getJedis().isConnected())
if (redisConnection != null && redisConnection.isEnabled() && redisConnection.getJedis().isConnected())
{
PlexLog.log("Disabling Redis/Jedis. No memory leaks in this Anarchy server!");
redisConnection.getJedis().close();
}
moduleManager.disableModules();
}
private void generateWorlds()
@ -188,14 +221,43 @@ public class Plex extends JavaPlugin
{
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
PlayerCache.getPunishedPlayerMap().put(player.getUniqueId(), new PunishedPlayer(player.getUniqueId()));
if (plugin.getRankManager().isAdmin(plexPlayer))
{
Admin admin = new Admin(UUID.fromString(plexPlayer.getUuid()));
Admin admin = new Admin(plexPlayer.getUuid());
admin.setRank(plexPlayer.getRankFromString());
plugin.getAdminList().addToCache(admin);
}
});
}
public static class BuildProperties
{
public String number;
public String author;
public String date;
public String head;
public void load(Plex plugin)
{
try
{
final Properties props;
try (InputStream in = plugin.getResource("build.properties"))
{
props = new Properties();
props.load(in);
}
number = props.getProperty("buildNumber", "unknown");
author = props.getProperty("buildAuthor", "unknown");
date = props.getProperty("buildDate", "unknown");
head = props.getProperty("buildHead", "unknown");
} catch (Exception ex)
{
PlexLog.error("Could not load build properties! Did you compile with NetBeans/Maven?");
}
}
}
}

View File

@ -29,19 +29,19 @@ public class Admin
/**
* Returns if the admin has command spy or not
* <br>
* Contains a #isCommandSpy and #setCommandSpy by lombok
* Contains a #isCommandSpy and #setCommandSpy by Lombok
*/
private boolean commandSpy = true;
private boolean commandSpy = false;
/**
* Returns if the admin has staff chat toggled or not
* Returns if the admin has admin chat toggled or not
* <br>
* Contains a #isStaffChat and #setStaffChat by lombok
* Contains a #isAdminChat and #setAdminChat by Lombok
*/
private boolean staffChat = false;
private boolean adminChat = false;
/**
* Creates an admin with the startig ADMIN rank
* Creates an admin with the ADMIN rank as the default rank
*
* @param uuid
* @see UUID
@ -52,6 +52,4 @@ public class Admin
this.uuid = uuid;
this.rank = Rank.ADMIN;
}
}

View File

@ -2,9 +2,11 @@ package dev.plex.admin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.morphia.Datastore;
import dev.morphia.query.Query;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.storage.StorageType;
@ -23,7 +25,7 @@ import java.util.stream.Collectors;
* @see Admin
*/
public class AdminList
public class AdminList extends PlexBase
{
/**
* Key / Value storage, where the key is the unique ID of the admin
@ -52,24 +54,24 @@ public class AdminList
}
/**
* Gathers every admin's username (cached and databsed)
* Gathers every admin's username (cached and in the database)
*
* @return An array list of the names of every admin
*/
public List<String> getAllAdmins()
{
List<String> admins = Lists.newArrayList();
if (Plex.get().getStorageType() == StorageType.MONGODB)
if (plugin.getStorageType() == StorageType.MONGODB)
{
Datastore store = Plex.get().getMongoConnection().getDatastore();
Datastore store = plugin.getMongoConnection().getDatastore();
Query<PlexPlayer> query = store.find(PlexPlayer.class);
admins.addAll(query.stream().filter(plexPlayer -> plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN)).map(PlexPlayer::getName).collect(Collectors.toList()));
admins.addAll(query.stream().filter(plexPlayer -> plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN) && plexPlayer.isAdminActive()).map(PlexPlayer::getName).toList());
}
else
{
try (Connection con = Plex.get().getSqlConnection().getCon())
try (Connection con = plugin.getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE rank IN(?, ?, ?)");
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE rank IN(?, ?, ?) AND adminActive=true");
statement.setString(1, Rank.ADMIN.name().toLowerCase());
statement.setString(2, Rank.SENIOR_ADMIN.name().toLowerCase());
statement.setString(3, Rank.EXECUTIVE.name().toLowerCase());
@ -79,7 +81,6 @@ public class AdminList
{
admins.add(set.getString("name"));
}
}
catch (SQLException throwables)
{
@ -89,4 +90,61 @@ public class AdminList
return admins;
}
/**
* Gathers every admin (cached and in the database)
*
* @return An array list of the names of every admin
*/
public List<PlexPlayer> getAllAdminPlayers()
{
List<PlexPlayer> plexPlayers = Lists.newArrayList();
if (plugin.getStorageType() == StorageType.MONGODB)
{
Datastore store = plugin.getMongoConnection().getDatastore();
Query<PlexPlayer> query = store.find(PlexPlayer.class);
return query.stream().toList().stream().filter(player -> plugin.getRankManager().isAdmin(player)).collect(Collectors.toList());
}
else
{
try (Connection con = plugin.getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE rank IN(?, ?, ?) AND adminActive=true");
statement.setString(1, Rank.ADMIN.name().toLowerCase());
statement.setString(2, Rank.SENIOR_ADMIN.name().toLowerCase());
statement.setString(3, Rank.EXECUTIVE.name().toLowerCase());
ResultSet set = statement.executeQuery();
while (set.next())
{
String uuid = set.getString("uuid");
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
PlexPlayer plexPlayer = new PlexPlayer(UUID.fromString(uuid));
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
plexPlayers.add(plexPlayer);
}
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
return plexPlayers;
}
}

View File

@ -1,6 +1,7 @@
package dev.plex.cache;
import dev.plex.Plex;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import java.util.UUID;
@ -53,16 +54,41 @@ public class DataUtils
}
}
public static PlexPlayer getPlayer(String username)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
return Plex.get().getMongoPlayerData().getByName(username);
}
else
{
return Plex.get().getSqlPlayerData().getByName(username);
}
}
/**
* Gets a player from cache or from the database
*
* @param name Username of the player
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public static PlexPlayer getPlayer(String name)
public static PlexPlayer getPlayerByIP(String ip)
{
return getPlayer(Bukkit.getPlayer(name).getUniqueId());
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
return Plex.get().getMongoPlayerData().getByIP(ip);
}
else
{
return Plex.get().getSqlPlayerData().getByIP(ip);
}
}
/**

View File

@ -1,150 +0,0 @@
package dev.plex.cache;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
/**
* SQL fetching utilities for players
*/
public class SQLPlayerData
{
private final String SELECT = "SELECT * FROM `players` WHERE uuid=?";
private final String UPDATE = "UPDATE `players` SET name=?, login_msg=?, prefix=?, rank=?, ips=?, coins=?, vanished=?, commandspy=? WHERE uuid=?";
private final String INSERT = "INSERT INTO `players` (`uuid`, `name`, `login_msg`, `prefix`, `rank`, `ips`, `coins`, `vanished`, `commandspy`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
/**
* Checks if a player exists in the SQL database
*
* @param uuid The unique ID of the player
* @return true if the player was found in the database
*/
public boolean exists(UUID uuid)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
return set.next();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return false;
}
/**
* Gets the player from cache or from the SQL database
*
* @param uuid The unique ID of the player
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByUUID(UUID uuid)
{
if (PlayerCache.getPlexPlayerMap().containsKey(uuid))
{
return PlayerCache.getPlexPlayerMap().get(uuid);
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = new PlexPlayer(uuid);
while (set.next())
{
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
/**
* Updates a player's information in the SQL database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void update(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE);
statement.setString(1, player.getName());
statement.setString(2, player.getLoginMessage());
statement.setString(3, player.getPrefix());
statement.setString(4, player.getRank().toLowerCase());
statement.setString(5, new Gson().toJson(player.getIps()));
statement.setLong(6, player.getCoins());
statement.setBoolean(7, player.isVanished());
statement.setBoolean(8, player.isCommandSpy());
statement.setString(9, player.getUuid());
statement.executeUpdate();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
/**
* Inserts the player's information in the database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void insert(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, player.getUuid());
statement.setString(2, player.getName());
statement.setString(3, player.getLoginMessage());
statement.setString(4, player.getPrefix());
statement.setString(5, player.getRank().toLowerCase());
statement.setString(6, new Gson().toJson(player.getIps()));
statement.setLong(7, player.getCoins());
statement.setBoolean(8, player.isVanished());
statement.setBoolean(9, player.isCommandSpy());
statement.execute();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}

View File

@ -0,0 +1,44 @@
package dev.plex.cache.notes;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
public class PlayerNotes
{
private final String SELECT = "SELECT * FROM `notes` WHERE uuid=?";
//private final String UPDATE = "UPDATE `notes` SET name=?, written_by=?, note=? WHERE uuid=?";
private final String INSERT = "INSERT INTO `notes` (`uuid`, `name`, `written_by`, `note`) VALUES (?, ?, ?, ?);";
public PlexPlayer getByUUID(UUID uuid)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = new PlexPlayer(uuid);
while (set.next())
{
String name = set.getString("name");
String writtenBy = set.getString("written_by");
String note = set.getString("note");
}
return plexPlayer;
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
}

View File

@ -1,4 +1,4 @@
package dev.plex.cache;
package dev.plex.cache.player;
import dev.morphia.Datastore;
import dev.morphia.query.Query;
@ -7,6 +7,8 @@ import dev.morphia.query.experimental.filters.Filters;
import dev.morphia.query.experimental.updates.UpdateOperators;
import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
@ -36,7 +38,7 @@ public class MongoPlayerData
public boolean exists(UUID uuid)
{
Query<PlexPlayer> query = datastore.find(PlexPlayer.class)
.filter(Filters.eq("uuid", uuid.toString()));
.filter(Filters.eq("uuid", uuid));
return query.first() != null;
}
@ -55,7 +57,38 @@ public class MongoPlayerData
return PlayerCache.getPlexPlayerMap().get(uuid);
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.eq("uuid", uuid.toString()));
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.eq("uuid", uuid));
return query2.first();
}
public PlexPlayer getByName(String username)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getName().equalsIgnoreCase(username)).findFirst().orElse(null);
if (player != null)
{
return player;
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.regex("name").caseInsensitive().pattern(username));
return query2.first();
}
/**
* Gets the player from cache or from mongo's database
*
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByIP(String ip)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.in("ips", Collections.singleton(ip)));
return query2.first();
}
@ -73,17 +106,25 @@ public class MongoPlayerData
Update<PlexPlayer> updateOps = filter
.update(
UpdateOperators.set("name", player.getName()),
UpdateOperators.set("loginMSG", player.getLoginMessage()),
UpdateOperators.set("loginMessage", player.getLoginMessage()),
UpdateOperators.set("prefix", player.getPrefix()),
UpdateOperators.set("vanished", player.isVanished()),
UpdateOperators.set("commandSpy", player.isCommandSpy()),
UpdateOperators.set("adminActive", player.isAdminActive()),
UpdateOperators.set("rank", player.getRank().toLowerCase()),
UpdateOperators.set("ips", player.getIps()),
UpdateOperators.set("coins", player.getCoins()),
UpdateOperators.set("vanished", player.isVanished()),
UpdateOperators.set("commandspy", player.isCommandSpy()));
UpdateOperators.set("punishments", player.getPunishments()),
UpdateOperators.set("notes", player.getNotes()));
updateOps.execute();
}
public List<PlexPlayer> getPlayers()
{
return datastore.find(PlexPlayer.class).stream().toList();
}
/**
* Saves the player's information in the database

View File

@ -1,8 +1,7 @@
package dev.plex.cache;
package dev.plex.cache.player;
import com.google.common.collect.Maps;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import java.util.Map;
import java.util.UUID;
@ -20,19 +19,18 @@ public class PlayerCache
/**
* A key/value pair where the key is the unique ID of the Punished Player
*/
private static final Map<UUID, PunishedPlayer> punishedPlayerMap = Maps.newHashMap();
public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
{
return punishedPlayerMap;
}
// private static final Map<UUID, PunishedPlayer> punishedPlayerMap = Maps.newHashMap();
// public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
// {
// return punishedPlayerMap;
// }
public static Map<UUID, PlexPlayer> getPlexPlayerMap()
{
return plexPlayerMap;
}
public static PunishedPlayer getPunishedPlayer(UUID uuid)
/*public static PunishedPlayer getPunishedPlayer(UUID uuid)
{
if (!getPunishedPlayerMap().containsKey(uuid))
{
@ -40,7 +38,7 @@ public class PlayerCache
}
return getPunishedPlayerMap().get(uuid);
}
*/
public static PlexPlayer getPlexPlayer(UUID uuid)
{
return getPlexPlayerMap().get(uuid);

View File

@ -0,0 +1,256 @@
package dev.plex.cache.player;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
/**
* SQL fetching utilities for players
*/
public class SQLPlayerData
{
private final String SELECT = "SELECT * FROM `players` WHERE uuid=?";
private final String UPDATE = "UPDATE `players` SET name=?, login_msg=?, prefix=?, rank=?, adminActive=?, ips=?, coins=?, vanished=?, commandspy=? WHERE uuid=?";
private final String INSERT = "INSERT INTO `players` (`uuid`, `name`, `login_msg`, `prefix`, `rank`, `adminActive`, `ips`, `coins`, `vanished`, `commandspy`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
/**
* Checks if a player exists in the SQL database
*
* @param uuid The unique ID of the player
* @return true if the player was found in the database
*/
public boolean exists(UUID uuid)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
return set.next();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return false;
}
/**
* Gets the player from cache or from the SQL database
*
* @param uuid The unique ID of the player
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByUUID(UUID uuid)
{
if (PlayerCache.getPlexPlayerMap().containsKey(uuid))
{
return PlayerCache.getPlexPlayerMap().get(uuid);
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = new PlexPlayer(uuid);
while (set.next())
{
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
public PlexPlayer getByName(String username)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getName().equalsIgnoreCase(username)).findFirst().orElse(null);
if (player != null)
{
return player;
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE name=? LIMIT 1");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
while (set.next())
{
PlexPlayer plexPlayer = new PlexPlayer(UUID.fromString(set.getString("uuid")));
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer.setName(username);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
return plexPlayer;
}
return null;
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
/**
* Gets the player from cache or from the SQL database
*
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByIP(String ip)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("select * from `players` where json_search(ips, ?, ?) IS NOT NULL LIMIT 1");
statement.setString(1, "one");
statement.setString(2, ip);
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = null;
while (set.next())
{
String uuid = set.getString("uuid");
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer = new PlexPlayer(UUID.fromString(uuid));
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
/**
* Updates a player's information in the SQL database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void update(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE);
statement.setString(1, player.getName());
statement.setString(2, player.getLoginMessage());
statement.setString(3, player.getPrefix());
statement.setString(4, player.getRank().toLowerCase());
statement.setBoolean(5, player.isAdminActive());
statement.setString(6, new Gson().toJson(player.getIps()));
statement.setLong(7, player.getCoins());
statement.setBoolean(8, player.isVanished());
statement.setBoolean(9, player.isCommandSpy());
statement.setString(10, player.getUuid().toString());
statement.executeUpdate();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
/**
* Inserts the player's information in the database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void insert(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, player.getUuid().toString());
statement.setString(2, player.getName());
statement.setString(3, player.getLoginMessage());
statement.setString(4, player.getPrefix());
statement.setString(5, player.getRank().toLowerCase());
statement.setBoolean(6, player.isAdminActive());
statement.setString(7, new Gson().toJson(player.getIps()));
statement.setLong(8, player.getCoins());
statement.setBoolean(9, player.isVanished());
statement.setBoolean(10, player.isCommandSpy());
statement.execute();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}

View File

@ -0,0 +1,97 @@
package dev.plex.cache.sql;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.punishment.extra.Note;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SQLNotes
{
private static final String SELECT = "SELECT * FROM `notes` WHERE uuid=?";
private static final String INSERT = "INSERT INTO `notes` (`id`, `uuid`, `written_by`, `note`, `timestamp`) VALUES(?, ?, ?, ?, ?)";
private static final String DELETE = "DELETE FROM `notes` WHERE uuid=? AND id=?";
public CompletableFuture<List<Note>> getNotes(UUID uuid)
{
return CompletableFuture.supplyAsync(() ->
{
List<Note> notes = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Note note = new Note(
uuid,
set.getString("note"),
UUID.fromString(set.getString("written_by")),
LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("timestamp")), ZoneId.systemDefault())
);
note.setId(set.getInt("id"));
notes.add(note);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return notes;
});
}
public CompletableFuture<Void> deleteNote(int id, UUID uuid)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(DELETE);
statement.setString(1, uuid.toString());
statement.setInt(2, id);
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
public CompletableFuture<Void> addNote(Note note)
{
return CompletableFuture.runAsync(() ->
{
getNotes(note.getUuid()).whenComplete((notes, throwable) ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setInt(1, notes.size() + 1);
statement.setString(2, note.getUuid().toString());
statement.setString(3, note.getWrittenBy().toString());
statement.setString(4, note.getNote());
statement.setLong(5, note.getTimestamp().toInstant(ZoneOffset.UTC).toEpochMilli());
statement.execute();
note.setId(notes.size());
}
catch (SQLException e)
{
e.printStackTrace();
}
});
});
}
}

View File

@ -0,0 +1,133 @@
package dev.plex.cache.sql;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.util.PlexLog;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SQLPunishment
{
private static final String SELECT = "SELECT * FROM `punishments` WHERE punished=?";
private static final String SELECT_BY = "SELECT * FROM `punishments` WHERE punisher=?";
private static final String INSERT = "INSERT INTO `punishments` (`punished`, `punisher`, `punishedUsername`, `ip`, `type`, `reason`, `customTime`, `active`, `endDate`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String UPDATE_BAN = "UPDATE `punishments` SET active=? WHERE active=? AND punished=? AND type=?";
public CompletableFuture<List<Punishment>> getPunishments()
{
return CompletableFuture.supplyAsync(() ->
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `punishments`");
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), UUID.fromString(set.getString("punisher")));
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.systemDefault()));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return punishments;
});
}
public List<Punishment> getPunishments(UUID uuid)
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), set.getString("punisher") == null ? null : UUID.fromString(set.getString("punisher")));
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.systemDefault()));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return punishments;
}
public CompletableFuture<Void> insertPunishment(Punishment punishment)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PlexLog.debug("Running execute punishment on " + punishment.getPunished().toString());
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, punishment.getPunished().toString());
statement.setString(2, punishment.getPunisher() == null ? null : punishment.getPunisher().toString());
statement.setString(3, punishment.getPunishedUsername());
statement.setString(4, punishment.getIp());
statement.setString(5, punishment.getType().name());
statement.setString(6, punishment.getReason());
statement.setBoolean(7, punishment.isCustomTime());
statement.setBoolean(8, punishment.isActive());
statement.setLong(9, punishment.getEndDate().toInstant(ZoneOffset.UTC).toEpochMilli());
PlexLog.debug("Executing punishment");
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
public CompletableFuture<Void> removeBan(UUID uuid)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE_BAN);
statement.setBoolean(1, false);
statement.setBoolean(2, true);
statement.setString(3, uuid.toString());
statement.setString(4, PunishmentType.BAN.name());
statement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
}

View File

@ -2,37 +2,31 @@ package dev.plex.command;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.player.PlayerCache;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.exception.ConsoleMustDefinePlayerException;
import dev.plex.command.exception.ConsoleOnlyException;
import dev.plex.command.exception.PlayerNotBannedException;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.exception.*;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.UUID;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.UUID;
/**
* Superclass for all commands
*/
@ -90,9 +84,8 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
* Executes the command
*
* @param sender The sender of the command
* @param playerSender The player who executed the command (null if command source is console or if command source is any but console executed)
* @param playerSender The player who executed the command (null if CommandSource is console or if CommandSource is any but console executed)
* @param args A Kyori Component to send to the sender (can be null)
* @return
*/
protected abstract Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args);
@ -129,20 +122,25 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (!plexPlayer.getRankFromString().isAtLeast(getLevel()))
{
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
} else
{
if (getLevel().isAtLeast(Rank.ADMIN) && !plexPlayer.isAdminActive())
{
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (!player.hasPermission(perms.permission()))
{
send(sender, messageComponent("noPermissionNode", perms.permission()));
return true;
}
}
else
} else
{
PlexLog.error("Neither permissions or ranks were selected to be used in the configuration file!");
send(sender, "There is a server misconfiguration. Please alert a developer or the owner");
@ -156,8 +154,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
{
send(sender, component);
}
}
catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException | ConsoleMustDefinePlayerException | PlayerNotBannedException ex)
} catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException | ConsoleMustDefinePlayerException | PlayerNotBannedException ex)
{
send(sender, MiniMessage.miniMessage().deserialize(ex.getMessage()));
}
@ -165,9 +162,9 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
}
/**
* Checks if the string given is a command string
* Checks if the String given is a matching command
*
* @param label The string to check
* @param label The String to check
* @return true if the string is a command name or alias
*/
private boolean matches(String label)
@ -181,8 +178,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
return true;
}
}
}
else if (params.aliases().split(",").length < 1)
} else if (params.aliases().split(",").length < 1)
{
return getName().equalsIgnoreCase(label);
}
@ -202,9 +198,9 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
}
/**
* Sends a message to an audience
* Sends a message to an Audience
*
* @param audience The audience to send the message to
* @param audience The Audience to send the message to
* @param s The message to send
*/
protected void send(Audience audience, String s)
@ -213,10 +209,10 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
}
/**
* Sends a message to an audience
* Sends a message to an Audience
*
* @param audience The audience to send the message to
* @param component The component to send
* @param audience The Audience to send the message to
* @param component The Component to send
*/
protected void send(Audience audience, Component component)
{
@ -226,7 +222,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
/**
* Checks whether a sender has enough permissions or is high enough a rank
*
* @param sender A command sender
* @param sender A CommandSender
* @param rank The rank to check (if the server is using ranks)
* @param permission The permission to check (if the server is using permissions)
* @return true if the sender has enough permissions
@ -263,8 +259,11 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
{
throw new CommandFailException(PlexUtils.messageString("noPermissionRank", ChatColor.stripColor(rank.getLoginMessage())));
}
if (rank.isAtLeast(Rank.ADMIN) && !plexPlayer.isAdminActive())
{
throw new CommandFailException(PlexUtils.messageString("noPermissionRank", ChatColor.stripColor(rank.getLoginMessage())));
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (!player.hasPermission(permission))
{
@ -274,6 +273,23 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
return true;
}
protected boolean silentCheckRank(Player player, Rank rank, String permission)
{
if (player instanceof ConsoleCommandSender)
{
return true;
}
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
return rank.isAtLeast(Rank.ADMIN) ? plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(rank) : plexPlayer.getRankFromString().isAtLeast(rank);
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
return player.hasPermission(permission);
}
return false;
}
/**
* Checks whether a sender has enough permissions or is high enough a rank
*
@ -306,9 +322,8 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
return plexPlayer.getRankFromString().isAtLeast(rank);
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
return rank.isAtLeast(Rank.ADMIN) ? plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(rank) : plexPlayer.getRankFromString().isAtLeast(rank);
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
return player.hasPermission(permission);
}
@ -415,7 +430,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
*
* @param s The message entry
* @param objects Any objects to replace in order
* @return A Kyori component
* @return A Kyori Component
*/
protected Component messageComponent(String s, Object... objects)
{
@ -435,25 +450,25 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
}
/**
* Converts usage to a component
* Converts usage to a Component
*
* @return A Kyori component stating the usage
* @return A Kyori Component stating the usage
*/
protected Component usage()
{
return componentFromString(ChatColor.YELLOW + "Correct Usage: " + ChatColor.GRAY + this.getUsage());
return Component.text("Correct Usage: ").color(NamedTextColor.YELLOW).append(componentFromString(this.getUsage()).color(NamedTextColor.GRAY));
}
/**
* Converts usage to a component
* Converts usage to a Component
* <p>
* s The usage to convert
*
* @return A Kyori component stating the usage
* @return A Kyori Component stating the usage
*/
protected Component usage(String s)
{
return componentFromString(ChatColor.YELLOW + "Correct Usage: " + ChatColor.GRAY + s);
return Component.text("Correct Usage: ").color(NamedTextColor.YELLOW).append(componentFromString(s).color(NamedTextColor.GRAY));
}
protected Player getNonNullPlayer(String name)
@ -498,25 +513,30 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
}
/**
* Converts a string to a legacy Kyori component
* Converts a String to a legacy Kyori Component
*
* @param s The string to convert
* @param s The String to convert
* @return A Kyori component
*/
protected Component componentFromString(String s)
{
return LegacyComponentSerializer.legacyAmpersand().deserialize(s).colorIfAbsent(NamedTextColor.GRAY);
}
protected Component noColorComponentFromString(String s)
{
return LegacyComponentSerializer.legacyAmpersand().deserialize(s);
}
/**
* Converts a string to a mini message kyori component
* Converts a String to a MiniMessage Component
*
* @param s The string to convert
* @return A Kyori component
* @param s The String to convert
* @return A Kyori Component
*/
protected Component mmString(String s)
{
return MiniMessage.miniMessage().parse(s);
return MiniMessage.miniMessage().deserialize(s);
}
public Rank getLevel()

View File

@ -0,0 +1,12 @@
package dev.plex.command.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface System
{
String value() default "";
boolean debug() default false;
}

View File

@ -0,0 +1,22 @@
package dev.plex.command.blocker;
import dev.plex.rank.enums.Rank;
import lombok.Getter;
@Getter
public class BaseCommand
{
private final Rank rank;
private final String message;
public BaseCommand(Rank r, String m)
{
rank = r;
message = m;
}
public String toString()
{
return "BaseCommand (Rank: " + (rank == null ? "ALL" : rank.name()) + ", Message: " + message + ")";
}
}

View File

@ -0,0 +1,108 @@
package dev.plex.command.blocker;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
@Getter
public class CommandBlockerManager extends PlexBase
{
private List<BaseCommand> blockedCommands = new ArrayList<>();
public boolean loadedYet;
public void syncCommands()
{
loadedYet = false;
blockedCommands.clear();
List<String> raw = plugin.blockedCommands.getStringList("blockedCommands");
for (String cmd : raw)
{
int lastDelim = cmd.lastIndexOf(':');
String cmdWithoutMsg = cmd.substring(0, lastDelim);
String[] rawPieces = cmdWithoutMsg.split(":", 3);
String rawType = rawPieces[0].toLowerCase();
String rawRank = rawPieces[1].toLowerCase();
String regexOrMatch = rawPieces[2];
String message = cmd.substring(lastDelim + 1);
if (message.equals("_"))
{
message = PlexUtils.messageString("commandBlocked");
}
Rank rank = switch (rawRank)
{
case "e" -> null;
case "a" -> Rank.ADMIN;
case "s" -> Rank.SENIOR_ADMIN;
default -> null;
};
if (rawType.equals("r"))
{
blockedCommands.add(new RegexCommand(Pattern.compile(regexOrMatch, Pattern.CASE_INSENSITIVE), rank, message));
}
else if (rawType.equals("m"))
{
int ind = regexOrMatch.indexOf(' ');
if (ind == -1 && regexOrMatch.endsWith(":"))
{
String pluginName = regexOrMatch.substring(0, regexOrMatch.length() - 1);
Plugin plugin = Arrays.stream(Bukkit.getServer().getPluginManager().getPlugins()).filter(pl -> pl.getName().equalsIgnoreCase(pluginName)).findAny().orElse(null);
if (plugin != null)
{
List<Command> commandList = PluginCommandYamlParser.parse(plugin);
for (Command command : commandList)
{
blockedCommands.add(new MatchCommand(command.getName(), rank, message));
blockedCommands.add(new MatchCommand(pluginName + ":" + command.getName(), rank, message));
for (String alias : command.getAliases())
{
blockedCommands.add(new MatchCommand(alias, rank, message));
blockedCommands.add(new MatchCommand(pluginName + ":" + alias, rank, message));
}
}
}
}
String blockedArgs = ind == -1 ? "" : regexOrMatch.substring(ind + 1);
if (!blockedArgs.isEmpty())
{
blockedArgs = " " + blockedArgs; // necessary in case no args
}
PluginCommand pluginCommand = Plex.get().getServer().getPluginCommand(ind == -1 ? regexOrMatch : regexOrMatch.substring(0, ind));
if (pluginCommand != null)
{
String pluginName = pluginCommand.getPlugin().getName();
blockedCommands.add(new MatchCommand(pluginCommand.getName() + blockedArgs, rank, message));
blockedCommands.add(new MatchCommand(pluginName + ":" + pluginCommand.getName() + blockedArgs, rank, message));
List<String> aliases = pluginCommand.getAliases();
for (String alias : aliases)
{
blockedCommands.add(new MatchCommand(alias + blockedArgs, rank, message));
blockedCommands.add(new MatchCommand(pluginName + ":" + alias + blockedArgs, rank, message));
}
}
}
}
loadedYet = true;
}
}

View File

@ -0,0 +1,21 @@
package dev.plex.command.blocker;
import dev.plex.rank.enums.Rank;
import lombok.Getter;
@Getter
public class MatchCommand extends BaseCommand
{
private final String match;
public MatchCommand(String r1, Rank r2, String m1)
{
super(r2, m1);
match = r1;
}
public String toString()
{
return "MatchCommand (Rank: " + (getRank() == null ? "ALL" : getRank().name()) + ", Match: " + match + ", Message: " + getMessage() + ")";
}
}

View File

@ -0,0 +1,23 @@
package dev.plex.command.blocker;
import dev.plex.rank.enums.Rank;
import lombok.Getter;
import java.util.regex.Pattern;
@Getter
public class RegexCommand extends BaseCommand
{
private final Pattern regex;
public RegexCommand(Pattern r1, Rank r2, String m1)
{
super(r2, m1);
regex = r1;
}
public String toString()
{
return "RegexCommand (Rank: " + (getRank() == null ? "ALL" : getRank().name()) + ", Regex: " + regex.toString() + ", Message: " + getMessage() + ")";
}
}

View File

@ -5,6 +5,7 @@ import dev.plex.cache.DataUtils;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.command.exception.ConsoleOnlyException;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
@ -13,6 +14,7 @@ import dev.plex.event.AdminRemoveEvent;
import dev.plex.event.AdminSetRankEvent;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.List;
@ -26,7 +28,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, source = RequiredCommandSource.ANY)
@CommandParameters(name = "admin", usage = "/<command> <add | remove | setrank | list> [player] [rank]", aliases = "saconfig,slconfig,adminconfig,adminmanage", description = "Manage all admins")
@CommandParameters(name = "admin", usage = "/<command> <add <player> | remove <player> | setrank <player> <rank> | list>", aliases = "saconfig,slconfig,adminconfig,adminmanage", description = "Manage all admins")
@System(value = "ranks")
public class AdminCMD extends PlexCommand
{
//TODO: Better return messages
@ -53,6 +56,11 @@ public class AdminCMD extends PlexCommand
UUID targetUUID = PlexUtils.getFromName(args[1]);
if (targetUUID != null)
{
PlexLog.debug("Admin Adding UUID: " + targetUUID);
}
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();

View File

@ -1,13 +1,16 @@
package dev.plex.command.impl;
import dev.plex.cache.player.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.listener.impl.ChatListener;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@ -25,7 +28,30 @@ public class AdminChatCMD extends PlexCommand
return usage();
}
ChatListener.adminChat(sender, StringUtils.join(args, " "));
adminChat(sender, StringUtils.join(args, " "));
return null;
}
private void adminChat(CommandSender sender, String message)
{
for (Player player : Bukkit.getOnlinePlayers())
{
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
if (plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN) && plexPlayer.isAdminActive())
{
player.sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (player.hasPermission("plex.adminchat"))
{
player.sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
}
}
plugin.getServer().getConsoleSender().sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
}

View File

@ -1,15 +1,14 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -40,7 +39,6 @@ public class BanCMD extends PlexCommand
}
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
@ -62,12 +60,14 @@ public class BanCMD extends PlexCommand
}
}
if (plugin.getPunishmentManager().isBanned(targetUUID))
plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
{
return messageComponent("playerBanned");
if (aBoolean)
{
send(sender, messageComponent("playerBanned"));
return;
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
String reason;
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 1)
@ -84,13 +84,22 @@ public class BanCMD extends PlexCommand
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
Bukkit.getScheduler().runTask(Plex.get(), () ->
{
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + punishedPlayer.getUuid());
});
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + plexPlayer.getUuid());
});
return null;
}

View File

@ -0,0 +1,98 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.listener.impl.BlockListener;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.blockedit")
@CommandParameters(name = "blockedit", usage = "/<command> [list | purge | all | <player>]", aliases = "bedit", description = "Prevent players from modifying blocks")
public class BlockEditCMD extends PlexCommand
{
private final BlockListener bl = new BlockListener();
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args)
{
if (args.length == 0)
{
return usage();
}
if (args[0].equalsIgnoreCase("list"))
{
send(sender, "The following have block modification abilities restricted:");
int count = 0;
for (String player : bl.blockedPlayers.stream().toList())
{
send(sender, "- " + player);
++count;
}
if (count == 0)
{
send(sender, "- none");
}
return null;
}
else if (args[0].equalsIgnoreCase("purge"))
{
PlexUtils.broadcast(componentFromString(sender.getName() + " - Unblocking block modification abilities for all players").color(NamedTextColor.AQUA));
int count = 0;
for (String player : bl.blockedPlayers.stream().toList())
{
if (bl.blockedPlayers.contains(player))
{
bl.blockedPlayers.remove(player);
++count;
}
}
return messageComponent("unblockedEditsSize", count);
}
else if (args[0].equalsIgnoreCase("all"))
{
PlexUtils.broadcast(componentFromString(sender.getName() + " - Blocking block modification abilities for all non-admins").color(NamedTextColor.RED));
int count = 0;
for (final Player player : Bukkit.getOnlinePlayers())
{
if (!silentCheckRank(player, Rank.ADMIN, "plex.blockedit"))
{
bl.blockedPlayers.add(player.getName());
++count;
}
}
return messageComponent("blockedEditsSize", count);
}
final Player player = getNonNullPlayer(args[0]);
if (!bl.blockedPlayers.contains(player.getName()))
{
if (silentCheckRank(player, Rank.ADMIN, "plex.blockedit"))
{
send(sender, messageComponent("higherRankThanYou"));
return null;
}
PlexUtils.broadcast(messageComponent("blockingEditFor", sender.getName(), player.getName()));
bl.blockedPlayers.add(player.getName());
send(player, messageComponent("yourEditsHaveBeenBlocked"));
send(sender, messageComponent("editsBlocked", player.getName()));
}
else
{
PlexUtils.broadcast(messageComponent("unblockingEditFor", sender.getName(), player.getName()));
bl.blockedPlayers.remove(player.getName());
send(player, messageComponent("yourEditsHaveBeenUnblocked"));
send(sender, messageComponent("editsUnblocked", player.getName()));
}
return null;
}
}

View File

@ -27,9 +27,9 @@ public class CommandSpyCMD extends PlexCommand
PlexPlayer plexPlayer = DataUtils.getPlayer(playerSender.getUniqueId());
plexPlayer.setCommandSpy(!plexPlayer.isCommandSpy());
DataUtils.update(plexPlayer);
return Component.text(PlexUtils.messageString("toggleCommandSpy")).color(NamedTextColor.GRAY)
send(sender, messageComponent("toggleCommandSpy")
.append(Component.space())
.append(Component.text(plexPlayer.isCommandSpy() ? PlexUtils.messageString("enabled") : PlexUtils.messageString("disabled")).color(NamedTextColor.GRAY));
.append(plexPlayer.isCommandSpy() ? messageComponent("enabled") : messageComponent("disabled")));
}
return null;
}

View File

@ -4,10 +4,12 @@ import com.google.common.collect.ImmutableList;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.List;
import java.util.Locale;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
@ -17,8 +19,9 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "debug", description = "Debug command", usage = "/<command> <redis-reset | gamerules> [player]")
@CommandParameters(name = "pdebug", description = "Plex's debug command", usage = "/<command> <redis-reset <player> | gamerules>")
@CommandPermissions(level = Rank.EXECUTIVE, permission = "plex.debug")
@System(debug = true)
public class DebugCMD extends PlexCommand
{
@Override
@ -42,8 +45,17 @@ public class DebugCMD extends PlexCommand
{
for (World world : Bukkit.getWorlds())
{
PlexUtils.commitGameRules(world);
PlexLog.debug("Set gamerules for world: " + world.getName());
PlexUtils.commitGlobalGameRules(world);
PlexLog.log("Set global gamerules for world: " + world.getName());
}
for (String world : plugin.config.getConfigurationSection("worlds").getKeys(false))
{
World bukkitWorld = Bukkit.getWorld(world);
if (bukkitWorld != null)
{
PlexUtils.commitSpecificGameRules(bukkitWorld);
PlexLog.log("Set specific gamerules for world: " + world.toLowerCase(Locale.ROOT));
}
}
return mmString("<aqua>Re-applied game all the game rules!");
}

View File

@ -3,6 +3,7 @@ package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
@ -14,6 +15,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "deopall", description = "Deop everyone on the server", aliases = "deopa")
@CommandPermissions(level = Rank.ADMIN)
@System(value = "ranks")
public class DeopAllCMD extends PlexCommand
{
@Override

View File

@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableList;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
@ -15,6 +16,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "deop", description = "Deop a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.deop")
@System(value = "ranks")
public class DeopCMD extends PlexCommand
{
@Override

View File

@ -0,0 +1,111 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.ArrayList;
import java.util.Collections;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.entitywipe", source = RequiredCommandSource.ANY)
@CommandParameters(name = "entitywipe", description = "Remove various server entities that may cause lag, such as dropped items, minecarts, and boats.", usage = "/<command> [name]", aliases = "ew,rd")
public class EntityWipeCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args)
{
List<String> entityBlacklist = plugin.config.getStringList("entitywipe_list");
List<String> entityWhitelist = new LinkedList<>(Arrays.asList(args));
EntityType[] entityTypes = EntityType.values();
entityWhitelist.removeIf(name ->
{
boolean res = Arrays.stream(entityTypes).noneMatch(entityType -> name.equalsIgnoreCase(entityType.name()));
if (res)
{
sender.sendMessage(messageComponent("invalidEntityType", name));
}
return res;
});
boolean useBlacklist = args.length == 0;
HashMap<String, Integer> entityCounts = new HashMap<>();
for (World world : Bukkit.getWorlds())
{
for (Entity entity : world.getEntities())
{
if (entity.getType() != EntityType.PLAYER)
{
String type = entity.getName();
if (useBlacklist ? entityBlacklist.stream().noneMatch(entityName -> entityName.equalsIgnoreCase(type)) : entityWhitelist.stream().anyMatch(entityName -> entityName.equalsIgnoreCase(type)))
{
entity.remove();
entityCounts.put(type, entityCounts.getOrDefault(type, 0) + 1);
}
}
}
}
int entityCount = entityCounts.values().stream().mapToInt(a -> a).sum();
if (useBlacklist)
{
PlexUtils.broadcast(messageComponent("removedEntities", sender.getName(), entityCount));
}
else
{
if (entityCount == 0)
{
sender.sendMessage(messageComponent("noRemovedEntities"));
return null;
}
String list = String.join(", ", entityCounts.keySet());
list = list.replaceAll("(, )(?!.*\1)", (list.indexOf(", ") == list.lastIndexOf(", ") ? "" : ",") + " and ");
PlexUtils.broadcast(messageComponent("removedEntitiesOfTypes", sender.getName(), entityCount, list));
}
/*entityCounts.forEach((entityName, numRemoved) -> {
sender.sendMessage(messageComponent("removedEntitiesOfType", sender.getName(), numRemoved, entityName));
});*/
return null;
}
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
List<String> entities = new ArrayList<>();
for (World world : Bukkit.getWorlds())
{
for (Entity entity : world.getEntities())
{
if (entity.getType() != EntityType.PLAYER)
{
entities.add(entity.getName());
}
}
}
return entities.stream().toList();
}
}

View File

@ -1,25 +1,23 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.LocalDateTime;
import java.util.List;
@CommandParameters(name = "freeze", description = "Freeze a player on the server", usage = "/<command> <player>", aliases = "fr")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.freeze")
public class FreezeCMD extends PlexCommand
@ -32,7 +30,7 @@ public class FreezeCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getPlexPlayer(player);
if (punishedPlayer.isFrozen())
{
@ -45,22 +43,23 @@ public class FreezeCMD extends PlexCommand
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()))
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()) && getPlexPlayer(player).isAdminActive())
{
return messageComponent("higherRankThanYou");
}
}
}
Punishment punishment = new Punishment(UUID.fromString(punishedPlayer.getUuid()), getUUID(sender));
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
punishment.setCustomTime(false);
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
punishment.setType(PunishmentType.FREEZE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("frozePlayer", sender.getName(), player.getName()));
return null;
}

View File

@ -1,14 +1,12 @@
package dev.plex.command.impl;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -49,8 +47,6 @@ public class KickCMD extends PlexCommand
{
throw new PlayerNotFoundException();
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.KICK);
if (args.length > 1)
@ -63,7 +59,8 @@ public class KickCMD extends PlexCommand
punishment.setEndDate(LocalDateTime.now());
punishment.setCustomTime(false);
punishment.setActive(false);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("kickedPlayer", sender.getName(), plexPlayer.getName()));
player.kick(componentFromString(reason));
return null;

View File

@ -4,26 +4,28 @@ import com.google.common.collect.Lists;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import java.util.List;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "list", description = "Show a list of all online players")
@CommandParameters(name = "list", description = "Show a list of all online players", aliases = "lsit")
@CommandPermissions(level = Rank.OP, permission = "plex.list")
@System(value = "ranks")
public class ListCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
List<Player> players = Lists.newArrayList(Bukkit.getOnlinePlayers());
Component component = Component.text("There " + (players.size() == 1 ? "is" : "are") + " currently").color(NamedTextColor.GRAY)
Component list = Component.empty();
Component header = Component.text("There " + (players.size() == 1 ? "is" : "are") + " currently").color(NamedTextColor.GRAY)
.append(Component.space())
.append(Component.text(players.size()).color(NamedTextColor.YELLOW))
.append(Component.space())
@ -33,18 +35,17 @@ public class ListCMD extends PlexCommand
.append(Component.space())
.append(Component.text(Bukkit.getMaxPlayers()).color(NamedTextColor.YELLOW))
.append(Component.space())
.append(Component.text(Bukkit.getMaxPlayers() == 1 ? "player." : "players.").color(NamedTextColor.GRAY))
.append(Component.newline());
.append(Component.text(Bukkit.getMaxPlayers() == 1 ? "player." : "players.").color(NamedTextColor.GRAY));
send(sender, header);
for (int i = 0; i < players.size(); i++)
{
Player player = players.get(i);
component = component.append(LegacyComponentSerializer.legacyAmpersand().deserialize(getPlexPlayer(player).getRankFromString().getPrefix())).append(Component.space()).append(Component.text(player.getName()).color(NamedTextColor.WHITE));
list = list.append(getPlexPlayer(player).getRankFromString().getPrefix()).append(Component.space()).append(Component.text(player.getName()).color(NamedTextColor.WHITE));
if (i != players.size() - 1)
{
component = component.append(Component.text(",")).append(Component.space());
list = list.append(Component.text(",")).append(Component.space());
}
}
return component;
return list;
}
}

View File

@ -1,26 +1,19 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@CommandParameters(name = "lockup", description = "Lockup a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.lockup")
public class LockupCMD extends PlexCommand
@ -33,7 +26,7 @@ public class LockupCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (isAdmin(getPlexPlayer(player)))
{
@ -49,7 +42,7 @@ public class LockupCMD extends PlexCommand
}
punishedPlayer.setLockedUp(!punishedPlayer.isLockedUp());
PlexUtils.broadcast(messageComponent(punishedPlayer.isLockedUp() ? "lockedUpPlayer" : "unlockedUpPlayer", sender.getName(), player.getName()));
PlexUtils.broadcast(messageComponent(punishedPlayer.isLockedUp() ? "lockedUpPlayer" : "unlockedPlayer", sender.getName(), player.getName()));
return null;
}

View File

@ -0,0 +1,51 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.mobpurge", source = RequiredCommandSource.ANY)
@CommandParameters(name = "mobpurge", description = "Purge all mobs.", usage = "/<command>", aliases = "mp")
public class MobPurgeCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args)
{
HashMap<String, Integer> entityCounts = new HashMap<>();
for (World world : Bukkit.getWorlds())
{
for (Entity entity : world.getEntities())
{
if (entity instanceof Mob)
{
String type = entity.getType().name();
entity.remove();
entityCounts.put(type, entityCounts.getOrDefault(type, 0) + 1);
}
}
}
int entityCount = entityCounts.values().stream().mapToInt(a -> a).sum();
PlexUtils.broadcast(messageComponent("removedMobs", sender.getName(), entityCount));
/*entityCounts.forEach((entityName, numRemoved) -> {
sender.sendMessage(messageComponent("removedEntitiesOfType", sender.getName(), numRemoved, entityName));
});*/
return null;
}
}

View File

@ -1,12 +1,10 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -32,7 +30,7 @@ public class MuteCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (punishedPlayer.isMuted())
{
@ -52,15 +50,16 @@ public class MuteCMD extends PlexCommand
}
}
Punishment punishment = new Punishment(UUID.fromString(punishedPlayer.getUuid()), getUUID(sender));
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
punishment.setCustomTime(false);
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
punishment.setType(PunishmentType.MUTE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("mutedPlayer", sender.getName(), player.getName()));
return null;
}

View File

@ -15,7 +15,6 @@ import java.util.Arrays;
import java.util.List;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@ -49,11 +48,9 @@ public class NameHistoryCMD extends PlexCommand
if (history.getLocalDateTime() != null)
{
historyList.add(
Component.text(history.getUsername()).color(NamedTextColor.GOLD)
.append(Component.space())
.append(Component.text("-").color(NamedTextColor.DARK_GRAY))
.append(Component.space())
.append(Component.text(DATE_FORMAT.format(history.getLocalDateTime())).color(NamedTextColor.GOLD)));
messageComponent("nameHistoryBody",
history.getUsername(),
DATE_FORMAT.format(history.getLocalDateTime())));
}
else
{
@ -62,8 +59,8 @@ public class NameHistoryCMD extends PlexCommand
.append(Component.space()));
}
});
send(sender, Component.text("Name History (" + username + ")").color(NamedTextColor.GOLD));
send(sender, Component.text("-----------------------------").color(NamedTextColor.GOLD).decoration(TextDecoration.STRIKETHROUGH, true));
send(sender, messageComponent("nameHistoryTitle", username));
send(sender, messageComponent("nameHistorySeparator"));
historyList.forEach(component -> send(sender, component));
return null;
}

View File

@ -0,0 +1,190 @@
package dev.plex.command.impl;
import dev.plex.cache.DataUtils;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.extra.Note;
import dev.plex.rank.enums.Rank;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
@CommandParameters(name = "notes", description = "Manage notes for a player", usage = "/<command> <player> <list | add <note> | remove <id> | clear>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.notes")
public class NotesCMD extends PlexCommand
{
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length < 2)
{
return usage();
}
Player player = getNonNullPlayer(args[0]);
PlexPlayer plexPlayer = getPlexPlayer(player);
switch (args[1].toLowerCase())
{
case "list":
{
if (plugin.getStorageType() != StorageType.MONGODB)
{
plugin.getSqlNotes().getNotes(plexPlayer.getUuid()).whenComplete((notes, ex) ->
{
if (notes.size() == 0)
{
send(sender, mmString("<red>This player has no notes!"));
return;
}
readNotes(sender, plexPlayer, notes);
});
}
else
{
List<Note> notes = plexPlayer.getNotes();
if (notes.size() == 0)
{
return mmString("<red>This player has no notes!");
}
readNotes(sender, plexPlayer, notes);
}
return null;
}
case "add":
{
if (args.length < 3)
{
return usage();
}
String content = StringUtils.join(ArrayUtils.subarray(args, 2, args.length), " ");
if (playerSender != null)
{
Note note = new Note(plexPlayer.getUuid(), content, playerSender.getUniqueId(), LocalDateTime.now());
plexPlayer.getNotes().add(note);
if (plugin.getStorageType() != StorageType.MONGODB)
{
plugin.getSqlNotes().addNote(note);
}
else
{
DataUtils.update(plexPlayer);
}
return Component.text("Note added.").color(NamedTextColor.GREEN);
}
}
case "remove":
{
int id;
try
{
id = Integer.parseInt(args[2]);
}
catch (NumberFormatException ignored)
{
return Component.text("Invalid number: " + args[2]).color(NamedTextColor.RED);
}
if (plugin.getStorageType() != StorageType.MONGODB)
{
plugin.getSqlNotes().getNotes(plexPlayer.getUuid()).whenComplete((notes, ex) ->
{
for (Note note : notes)
{
if (note.getId() == id)
{
plugin.getSqlNotes().deleteNote(id, plexPlayer.getUuid()).whenComplete((notes1, ex1) ->
send(sender, Component.text("Removed note with ID: " + id).color(NamedTextColor.GREEN)));
}
else
{
send(sender, mmString("<red>A note with this ID could not be found"));
}
}
plexPlayer.getNotes().removeIf(note -> note.getId() == id);
});
}
else
{
if (plexPlayer.getNotes().removeIf(note -> note.getId() == id))
{
return Component.text("Removed note with ID: " + id).color(NamedTextColor.GREEN);
}
return mmString("<red>A note with this ID could not be found");
}
}
case "clear":
{
if (plugin.getStorageType() != StorageType.MONGODB)
{
plugin.getSqlNotes().getNotes(plexPlayer.getUuid()).whenComplete((notes, ex) ->
{
for (Note note : notes)
{
plugin.getSqlNotes().deleteNote(note.getId(), plexPlayer.getUuid());
}
plexPlayer.getNotes().clear();
send(sender, Component.text("Cleared " + notes.size() + " note(s).").color(NamedTextColor.GREEN));
});
}
else
{
int count = plexPlayer.getNotes().size();
plexPlayer.getNotes().clear();
DataUtils.update(plexPlayer);
return Component.text("Cleared " + count + " note(s).").color(NamedTextColor.GREEN);
}
return null;
}
default:
{
return usage();
}
}
}
private void readNotes(@NotNull CommandSender sender, PlexPlayer plexPlayer, List<Note> notes)
{
AtomicReference<Component> noteList = new AtomicReference<>(Component.text("Player notes for: " + plexPlayer.getName()).color(NamedTextColor.GREEN));
for (Note note : notes)
{
Component noteLine = Component.text(note.getId() + " - Written by: " + DataUtils.getPlayer(note.getWrittenBy()).getName() + " on " + DATE_FORMAT.format(note.getTimestamp())).color(NamedTextColor.YELLOW).decoration(TextDecoration.ITALIC, false);
noteLine = noteLine.append(Component.text(note.getNote())).color(NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, true);
noteList.set(noteList.get().append(Component.newline()));
noteList.set(noteList.get().append(noteLine));
}
send(sender, noteList.get());
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1)
{
return PlexUtils.getPlayerNameList();
}
if (args.length == 2)
{
return Arrays.asList("list", "add", "remove", "clear");
}
return Collections.emptyList();
}
}

View File

@ -3,6 +3,7 @@ package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
@ -14,6 +15,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "opall", description = "Op everyone on the server", aliases = "opa")
@CommandPermissions(level = Rank.ADMIN)
@System(value = "ranks")
public class OpAllCMD extends PlexCommand
{
@Override
@ -26,5 +28,4 @@ public class OpAllCMD extends PlexCommand
PlexUtils.broadcast(messageComponent("oppedAllPlayers", sender.getName()));
return null;
}
}

View File

@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableList;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
@ -15,6 +16,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "op", description = "Op a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.OP)
@System(value = "ranks")
public class OpCMD extends PlexCommand
{
@Override

View File

@ -1,23 +1,31 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.module.PlexModule;
import dev.plex.module.PlexModuleFile;
import dev.plex.rank.enums.Rank;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.ChatColor;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.plex", source = RequiredCommandSource.ANY)
@CommandParameters(name = "plex", usage = "/<command> [reload | redis]", aliases = "plexhelp", description = "Show information about Plex or reload it")
@CommandParameters(name = "plex", usage = "/<command> [reload | redis | modules [reload]]", description = "Show information about Plex or reload it")
public class PlexCMD extends PlexCommand
{
// Don't modify this command
@ -26,9 +34,13 @@ public class PlexCMD extends PlexCommand
{
if (args.length == 0)
{
send(sender, ChatColor.LIGHT_PURPLE + "Plex - A new freedom plugin.");
send(sender, ChatColor.LIGHT_PURPLE + "Plugin version: " + plugin.getDescription().getVersion());
return componentFromString(ChatColor.LIGHT_PURPLE + "Authors: " + ChatColor.GOLD + "Telesphoreo, Taahh");
send(sender, mmString("<light_purple>Plex - A new freedom plugin."));
send(sender, mmString("<light_purple>Plugin version: <gold>" + plugin.getDescription().getVersion() + " #" + Plex.build.number + " <light_purple>Git: <gold>" + Plex.build.head));
send(sender, mmString("<light_purple>Authors: <gold>Telesphoreo, Taahh"));
send(sender, mmString("<light_purple>Built by: <gold>" + Plex.build.author + " <light_purple>on <gold>" + Plex.build.date));
send(sender, mmString("<light_purple>Run <gold>/plex modules <light_purple>to see a list of modules."));
plugin.getUpdateChecker().getUpdateStatusMessage(sender, true, 2);
return null;
}
if (args[0].equalsIgnoreCase("reload"))
{
@ -37,12 +49,20 @@ public class PlexCMD extends PlexCommand
send(sender, "Reloaded config file");
plugin.messages.load();
send(sender, "Reloaded messages file");
plugin.indefBans.load();
plugin.indefBans.load(false);
plugin.getPunishmentManager().mergeIndefiniteBans();
send(sender, "Reloaded indefinite bans");
plugin.blockedCommands.load();
plugin.getCommandBlockerManager().syncCommands();
send(sender, "Reloaded blocked commands file");
plugin.getRankManager().importDefaultRanks();
send(sender, "Imported ranks");
plugin.setSystem(plugin.config.getString("system"));
plugin.getServiceManager().endServices();
plugin.getServiceManager().startServices();
PlexLog.debug("Restarted services");
send(sender, "Plex successfully reloaded.");
return null;
}
else if (args[0].equalsIgnoreCase("redis"))
{
@ -55,6 +75,36 @@ public class PlexCMD extends PlexCommand
send(sender, "Set test to 123. Now outputting key test...");
send(sender, plugin.getRedisConnection().getJedis().get("test"));
plugin.getRedisConnection().getJedis().close();
return null;
}
else if (args[0].equalsIgnoreCase("modules"))
{
if (args.length == 1)
{
return mmString("<gold>Modules (" + plugin.getModuleManager().getModules().size() + "): <yellow>" + StringUtils.join(plugin.getModuleManager().getModules().stream().map(PlexModule::getPlexModuleFile).map(PlexModuleFile::getName).collect(Collectors.toList()), ", "));
}
if (args[1].equalsIgnoreCase("reload"))
{
checkRank(sender, Rank.SENIOR_ADMIN, "plex.modules.reload");
plugin.getModuleManager().unloadModules();
plugin.getModuleManager().loadAllModules();
plugin.getModuleManager().loadModules();
plugin.getModuleManager().enableModules();
return mmString("<green>All modules reloaded!");
}
}
else if (args[0].equalsIgnoreCase("update"))
{
if (sender instanceof Player player && !PlexUtils.DEVELOPERS.contains(player.getUniqueId().toString()))
{
return messageComponent("noPermissionRank", "a developer");
}
if (!plugin.getUpdateChecker().getUpdateStatusMessage(sender, false, 0))
{
return mmString("<red>Plex is already up to date!");
}
plugin.getUpdateChecker().updateJar(sender);
return null;
}
else
{
@ -66,6 +116,14 @@ public class PlexCMD extends PlexCommand
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return ImmutableList.of("reload", "redis");
if (args.length == 1)
{
return Arrays.asList("reload", "redis", "modules");
}
else if (args[0].equalsIgnoreCase("modules"))
{
return List.of("reload");
}
return Collections.emptyList();
}
}

View File

@ -22,7 +22,7 @@ public class PunishmentsCMD extends PlexCommand
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
new PunishmentMenu().openInv(((Player)sender), 0);
new PunishmentMenu().openInv(playerSender, 0);
return null;
}

View File

@ -3,16 +3,22 @@ package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.Collections;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.rank", source = RequiredCommandSource.IN_GAME)
@CommandPermissions(level = Rank.OP, permission = "plex.rank", source = RequiredCommandSource.ANY)
@CommandParameters(name = "rank", description = "Displays your rank")
@System(value = "ranks")
public class RankCMD extends PlexCommand
{
@Override
@ -20,6 +26,10 @@ public class RankCMD extends PlexCommand
{
if (args.length == 0)
{
if (isConsole(sender))
{
throw new CommandFailException("<red>When using the console, you must specify a player's rank.");
}
if (!(playerSender == null))
{
Rank rank = getPlexPlayer(playerSender).getRankFromString();
@ -34,4 +44,14 @@ public class RankCMD extends PlexCommand
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1)
{
return PlexUtils.getPlayerNameList();
}
return Collections.emptyList();
}
}

View File

@ -0,0 +1,150 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.title.Title;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.smite", source = RequiredCommandSource.ANY)
@CommandParameters(name = "smite", usage = "/<command> <player> [reason] [-ci | -q]", description = "Someone being a little bitch? Smite them down...")
public class SmiteCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length < 1)
{
return usage();
}
String reason = null;
boolean silent = false;
boolean clearinv = false;
if (args.length >= 2)
{
if (args[args.length - 1].equalsIgnoreCase("-q"))
{
if (args[args.length - 1].equalsIgnoreCase("-q"))
{
silent = true;
}
if (args.length >= 3)
{
reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length - 1), " ");
}
}
else if (args[args.length - 1].equalsIgnoreCase("-ci"))
{
if (args[args.length - 1].equalsIgnoreCase("-ci"))
{
clearinv = true;
}
if (args.length >= 3)
{
reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length - 1), " ");
}
}
else
{
reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " ");
}
}
final Player player = getNonNullPlayer(args[0]);
final PlexPlayer plexPlayer = getPlexPlayer(player);
Title title = Title.title(Component.text("You've been smitten.").color(NamedTextColor.RED), Component.text("Be sure to follow the rules!").color(NamedTextColor.YELLOW));
player.showTitle(title);
if (!silent)
{
PlexUtils.broadcast(mmString("<red>" + player.getName() + " has been a naughty, naughty boy."));
if (reason != null)
{
PlexUtils.broadcast(mmString(" <red>Reason: " + "<yellow>" + reason));
}
PlexUtils.broadcast(mmString(" <red>Smitten by: " + "<yellow>" + sender.getName()));
}
else
{
send(sender, "Smitten " + player.getName() + " quietly.");
}
// Deop
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
player.setOp(false);
}
// Set gamemode to survival
player.setGameMode(GameMode.SURVIVAL);
// Clear inventory
if (clearinv)
{
player.getInventory().clear();
}
// Strike with lightning effect
final Location targetPos = player.getLocation();
final World world = player.getWorld();
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location strike_pos = new Location(world, targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z);
world.strikeLightning(strike_pos);
}
}
// Kill
player.setHealth(0.0);
Punishment punishment = new Punishment(plexPlayer.getUuid(), getUUID(sender));
punishment.setCustomTime(false);
punishment.setEndDate(LocalDateTime.now());
punishment.setType(PunishmentType.SMITE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
if (reason != null)
{
punishment.setReason(reason);
send(player, mmString("<red>You've been smitten. Reason: <yellow>" + reason));
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (checkTab(sender, Rank.ADMIN, "plex.smite") && args.length == 1)
{
return PlexUtils.getPlayerNameList();
}
return Collections.emptyList();
}
}

View File

@ -19,7 +19,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.tag", source = RequiredCommandSource.ANY)
@CommandParameters(name = "tag", aliases = "prefix", description = "Manages your prefix", usage = "/<command> <set | clear> <prefix | player>")
@CommandParameters(name = "tag", aliases = "prefix", description = "Set or clear your prefix", usage = "/<command> <set <prefix> | clear <player>>")
public class TagCMD extends PlexCommand
{
@Override
@ -47,8 +47,7 @@ public class TagCMD extends PlexCommand
return usage("/tag set <prefix>");
}
String prefix = StringUtils.join(args, " ", 1, args.length);
Component convertedComponent = removeEvents(componentFromString(prefix));
Component convertedComponent = removeEvents(noColorComponentFromString(prefix));
convertedComponent = removeEvents(MiniMessage.miniMessage().deserialize(LegacyComponentSerializer.legacySection().serialize(convertedComponent)));
if (PlainTextComponentSerializer.plainText().serialize(convertedComponent).length() > plugin.config.getInt("chat.max-tag-length", 16))
@ -57,6 +56,7 @@ public class TagCMD extends PlexCommand
}
player.setPrefix(MiniMessage.miniMessage().serialize(convertedComponent));
DataUtils.update(player);
return messageComponent("prefixSetTo", MiniMessage.miniMessage().serialize(convertedComponent));
}
@ -69,8 +69,14 @@ public class TagCMD extends PlexCommand
return messageComponent("noPermissionConsole");
}
if (playerSender == null)
{
return null;
}
PlexPlayer player = DataUtils.getPlayer(playerSender.getUniqueId());
player.setPrefix("");
DataUtils.update(player);
return messageComponent("prefixCleared");
}
@ -78,6 +84,7 @@ public class TagCMD extends PlexCommand
Player target = getNonNullPlayer(args[1]);
PlexPlayer plexTarget = DataUtils.getPlayer(target.getUniqueId());
plexTarget.setPrefix("");
DataUtils.update(plexTarget);
messageComponent("otherPrefixCleared");
}
return usage();

View File

@ -2,14 +2,12 @@ package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
@ -54,7 +52,7 @@ public class TempbanCMD extends PlexCommand
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()) && plexPlayer.isAdminActive())
{
return messageComponent("higherRankThanYou");
}
@ -65,8 +63,6 @@ public class TempbanCMD extends PlexCommand
{
return messageComponent("playerBanned");
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 2)
@ -82,7 +78,11 @@ public class TempbanCMD extends PlexCommand
punishment.setEndDate(PlexUtils.parseDateOffset(args[1]));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{

View File

@ -0,0 +1,38 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.services.ServiceManager;
import dev.plex.services.impl.AutoWipeService;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.toggledrops", source = RequiredCommandSource.ANY)
@CommandParameters(name = "toggledrops", description = "Toggle immediately removing drops.", usage = "/<command>", aliases = "td")
public class ToggleDropsCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args)
{
plugin.config.set("allowdrops", !plugin.config.getBoolean("allowdrops"));
plugin.config.save();
send(sender, plugin.config.getBoolean("allowdrops") ? messageComponent("allowDropsEnabled") : messageComponent("allowDropsDisabled"));
return null;
}
}

View File

@ -14,6 +14,7 @@ import dev.plex.util.PlexUtils;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@ -35,20 +36,23 @@ public class UnbanCMD extends PlexCommand
if (args.length == 1)
{
UUID targetUUID = PlexUtils.getFromName(args[0]);
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
if (!DataUtils.hasPlayedBefore(targetUUID))
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
if (!plugin.getPunishmentManager().isBanned(targetUUID))
plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
{
throw new PlayerNotBannedException();
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
if (!aBoolean)
{
send(sender, MiniMessage.miniMessage().deserialize(new PlayerNotBannedException().getMessage()));
return;
}
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName()));
});
}
return null;
}

View File

@ -1,12 +1,11 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
@ -28,7 +27,7 @@ public class UnfreezeCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isFrozen())
{
throw new CommandFailException(PlexUtils.messageString("playerNotFrozen"));

View File

@ -1,12 +1,11 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
@ -28,7 +27,7 @@ public class UnmuteCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (!punishedPlayer.isMuted())
{
throw new CommandFailException(PlexUtils.messageString("playerNotMuted"));

View File

@ -50,15 +50,22 @@ public class Config extends YamlConfiguration
}
}
public void load()
{
this.load(true);
}
/**
* Loads the configuration file
*/
public void load()
public void load(boolean loadFromFile)
{
try
{
if (loadFromFile)
{
YamlConfiguration externalYamlConfig = YamlConfiguration.loadConfiguration(file);
InputStreamReader internalConfigFileStream = new InputStreamReader(Plex.get().getResource(name), StandardCharsets.UTF_8);
InputStreamReader internalConfigFileStream = new InputStreamReader(plugin.getResource(name), StandardCharsets.UTF_8);
YamlConfiguration internalYamlConfig = YamlConfiguration.loadConfiguration(internalConfigFileStream);
// Gets all the keys inside the internal file and iterates through all of it's key pairs
@ -69,6 +76,7 @@ public class Config extends YamlConfiguration
{
// If it doesn't contain the key, we set the key based off what was found inside the plugin jar
externalYamlConfig.setComments(string, internalYamlConfig.getComments(string));
externalYamlConfig.setInlineComments(string, internalYamlConfig.getInlineComments(string));
externalYamlConfig.set(string, internalYamlConfig.get(string));
PlexLog.log("Setting key: " + string + " in " + this.name + " to the default value(s) since it does not exist!");
added = true;
@ -80,6 +88,7 @@ public class Config extends YamlConfiguration
PlexLog.log("Saving new file...");
added = false;
}
}
super.load(file);
}
catch (Exception ex)

View File

@ -0,0 +1,123 @@
package dev.plex.config;
import dev.plex.module.PlexModule;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
/**
* Creates a custom Config object
*/
public class ModuleConfig extends YamlConfiguration
{
/**
* The plugin instance
*/
private PlexModule module;
/**
* The File instance
*/
private File file;
/**
* The file name
*/
private String name;
/**
* Creates a config object
*
* @param module The module instance
* @param name The file name
*/
public ModuleConfig(PlexModule module, String name)
{
this.module = module;
this.file = new File(module.getDataFolder(), name);
this.name = name;
if (!file.exists())
{
saveDefault();
}
}
public void load()
{
try
{
super.load(file);
}
catch (IOException | InvalidConfigurationException ex)
{
ex.printStackTrace();
}
}
/**
* Saves the configuration file
*/
public void save()
{
try
{
super.save(file);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* Moves the configuration file from the plugin's resources folder to the data folder (plugins/Plex/)
*/
private void saveDefault()
{
try
{
Files.copy(module.getClass().getResourceAsStream("/" + name), this.file.toPath());
}
catch (IOException e)
{
e.printStackTrace();
}
/*if (name == null || name.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
name = name.replace('\\', '/');
InputStream in = module.getResource("/" + name);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + name + "'");
}
File outFile = new File(module.getDataFolder(), name);
int lastIndex = name.lastIndexOf('/');
File outDir = new File(module.getDataFolder(), name.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists()) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
module.getLogger().log(org.apache.logging.log4j.Level.INFO, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
module.getLogger().log(Level.ERROR, "Could not save " + outFile.getName() + " to " + outFile, ex);
}*/
}
}

View File

@ -1,6 +1,6 @@
package dev.plex.event;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
@ -17,7 +17,7 @@ public abstract class PunishedPlayerEvent extends PlayerEvent implements Cancell
/**
* The player who was punished
*/
protected PunishedPlayer punishedPlayer;
protected PlexPlayer punishedPlayer;
/**
* Whether the event was cancelled
@ -29,11 +29,11 @@ public abstract class PunishedPlayerEvent extends PlayerEvent implements Cancell
* Creates an event object
*
* @param punishedPlayer The player who was punished
* @see PunishedPlayer
* @see PlexPlayer
*/
protected PunishedPlayerEvent(PunishedPlayer punishedPlayer)
protected PunishedPlayerEvent(PlexPlayer punishedPlayer)
{
super(Bukkit.getPlayer(UUID.fromString(punishedPlayer.getUuid())));
super(Bukkit.getPlayer(punishedPlayer.getUuid()));
this.punishedPlayer = punishedPlayer;
}
}

View File

@ -1,6 +1,6 @@
package dev.plex.event;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import lombok.Getter;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerFreezeEvent extends PunishedPlayerEvent implements Ca
* @param punishedPlayer The player who was punished
* @param frozen The new frozen status
*/
public PunishedPlayerFreezeEvent(PunishedPlayer punishedPlayer, boolean frozen)
public PunishedPlayerFreezeEvent(PlexPlayer punishedPlayer, boolean frozen)
{
super(punishedPlayer);
this.frozen = frozen;

View File

@ -1,6 +1,6 @@
package dev.plex.event;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import lombok.Getter;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerLockupEvent extends PunishedPlayerEvent implements Ca
* @param punishedPlayer The player who was punished
* @param lockedUp The new muted status
*/
public PunishedPlayerLockupEvent(PunishedPlayer punishedPlayer, boolean lockedUp)
public PunishedPlayerLockupEvent(PlexPlayer punishedPlayer, boolean lockedUp)
{
super(punishedPlayer);
this.lockedUp = lockedUp;

View File

@ -1,6 +1,6 @@
package dev.plex.event;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import lombok.Getter;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
@ -24,7 +24,7 @@ public class PunishedPlayerMuteEvent extends PunishedPlayerEvent implements Canc
* @param punishedPlayer The player who was punished
* @param muted The new muted status
*/
public PunishedPlayerMuteEvent(PunishedPlayer punishedPlayer, boolean muted)
public PunishedPlayerMuteEvent(PlexPlayer punishedPlayer, boolean muted)
{
super(punishedPlayer);
this.muted = muted;

View File

@ -3,56 +3,47 @@ package dev.plex.handlers;
import com.google.common.collect.Lists;
import dev.plex.PlexBase;
import dev.plex.command.PlexCommand;
import dev.plex.command.impl.*;
import dev.plex.command.annotation.System;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
//TODO: Switch to Reflections API
public class CommandHandler extends PlexBase
{
public CommandHandler()
{
Set<Class<? extends PlexCommand>> commandSet = PlexUtils.getClassesBySubType("dev.plex.command.impl", PlexCommand.class);
List<PlexCommand> commands = Lists.newArrayList();
if (plugin.getSystem().equalsIgnoreCase("ranks"))
commandSet.forEach(clazz ->
{
commands.add(new AdminCMD());
commands.add(new DeopAllCMD());
commands.add(new DeopCMD());
commands.add(new OpAllCMD());
commands.add(new OpCMD());
commands.add(new RankCMD());
}
if (plugin.config.getBoolean("debug"))
try
{
commands.add(new DebugCMD());
if (clazz.isAnnotationPresent(System.class))
{
System annotation = clazz.getDeclaredAnnotation(System.class);
if (annotation.value().equalsIgnoreCase(plugin.getSystem().toLowerCase()))
{
commands.add(clazz.getConstructor().newInstance());
}
commands.add(new AdminChatCMD());
commands.add(new AdminworldCMD());
commands.add(new AdventureCMD());
commands.add(new BanCMD());
commands.add(new CommandSpyCMD());
commands.add(new CreativeCMD());
commands.add(new FlatlandsCMD());
commands.add(new FreezeCMD());
commands.add(new KickCMD());
commands.add(new ListCMD());
commands.add(new LocalSpawnCMD());
commands.add(new LockupCMD());
commands.add(new MasterbuilderworldCMD());
commands.add(new MuteCMD());
commands.add(new NameHistoryCMD());
commands.add(new PlexCMD());
commands.add(new PunishmentsCMD());
commands.add(new RawSayCMD());
commands.add(new SpectatorCMD());
commands.add(new SurvivalCMD());
commands.add(new TagCMD());
commands.add(new TempbanCMD());
commands.add(new UnbanCMD());
commands.add(new UnfreezeCMD());
commands.add(new UnmuteCMD());
commands.add(new WorldCMD());
PlexLog.log(String.format("Registered %s commands!", commands.size()));
if (plugin.config.getBoolean("debug") && annotation.debug())
{
commands.add(clazz.getConstructor().newInstance());
}
}
else
{
commands.add(clazz.getConstructor().newInstance());
}
}
catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException ex)
{
PlexLog.error("Failed to register " + clazz.getSimpleName() + " as a command!");
}
});
PlexLog.log(String.format("Registered %s commands from %s classes!", commands.size(), commandSet.size()));
}
}

View File

@ -1,34 +1,44 @@
package dev.plex.handlers;
import com.google.common.collect.Lists;
import dev.plex.PlexBase;
import dev.plex.listener.PlexListener;
import dev.plex.listener.impl.AdminListener;
import dev.plex.listener.impl.BanListener;
import dev.plex.listener.impl.ChatListener;
import dev.plex.listener.impl.CommandListener;
import dev.plex.listener.impl.FreezeListener;
import dev.plex.listener.impl.GameModeListener;
import dev.plex.listener.impl.PlayerListener;
import dev.plex.listener.impl.ServerListener;
import dev.plex.listener.impl.WorldListener;
import dev.plex.listener.annotation.Toggleable;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
//TODO: Switch to Reflections API
public class ListenerHandler
public class ListenerHandler extends PlexBase
{
public ListenerHandler()
{
Set<Class<? extends PlexListener>> listenerSet = PlexUtils.getClassesBySubType("dev.plex.listener.impl", PlexListener.class);
List<PlexListener> listeners = Lists.newArrayList();
listeners.add(new AdminListener());
listeners.add(new BanListener());
listeners.add(new ChatListener());
listeners.add(new CommandListener());
listeners.add(new FreezeListener());
listeners.add(new GameModeListener());
listeners.add(new PlayerListener());
listeners.add(new ServerListener());
listeners.add(new WorldListener());
PlexLog.log(String.format("Registered %s listeners!", listeners.size()));
listenerSet.forEach(clazz ->
{
try
{
if (clazz.isAnnotationPresent(Toggleable.class))
{
Toggleable annotation = clazz.getDeclaredAnnotation(Toggleable.class);
if (plugin.config.get(annotation.value()) != null && plugin.config.getBoolean(annotation.value()))
{
listeners.add(clazz.getConstructor().newInstance());
}
}
else
{
listeners.add(clazz.getConstructor().newInstance());
}
}
catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException ex)
{
PlexLog.error("Failed to register " + clazz.getSimpleName() + " as a listener!");
}
});
PlexLog.log(String.format("Registered %s listeners from %s classes!", listeners.size(), listenerSet.size()));
}
}

View File

@ -0,0 +1,10 @@
package dev.plex.listener.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Toggleable
{
String value();
}

View File

@ -18,17 +18,25 @@ public class AdminListener extends PlexListener
{
String userSender = event.getSender().getName();
PlexPlayer target = event.getPlexPlayer();
if (!target.getRank().isEmpty())
{
PlexUtils.broadcast(messageComponent("adminReadded", userSender, target.getName(), target.getRankFromString().getReadable()));
} else {
target.setRank(Rank.ADMIN.name());
DataUtils.update(target);
PlexUtils.broadcast(messageComponent("newAdminAdded", userSender, target.getName()));
}
target.setAdminActive(true);
DataUtils.update(target);
}
@EventHandler
public void onAdminRemove(AdminRemoveEvent event)
{
String userSender = event.getSender().getName();
PlexPlayer target = event.getPlexPlayer();
target.setRank("");
// target.setRank("");
target.setAdminActive(false);
DataUtils.update(target);
PlexUtils.broadcast(messageComponent("adminRemoved", userSender, target.getName()));
}

View File

@ -1,8 +1,8 @@
package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.DataUtils;
import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import org.bukkit.event.EventHandler;
@ -36,7 +36,7 @@ public class BanListener extends PlexListener
if (plugin.getPunishmentManager().isBanned(event.getUniqueId()))
{
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getUniqueId());
PlexPlayer player = DataUtils.getPlayer(event.getUniqueId());
player.getPunishments().stream().filter(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive()).findFirst().ifPresent(punishment ->
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
Punishment.generateBanMessage(punishment)));

View File

@ -0,0 +1,97 @@
package dev.plex.listener.impl;
import dev.plex.listener.PlexListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockListener extends PlexListener
{
public List<String> blockedPlayers = new ArrayList<>();
private static final List<Material> blockedBlocks = new ArrayList<>();
private static List<String> cachedBlockedBlocksConfig = null;
private static final List<Material> SIGNS = Arrays.stream(Material.values()).filter((mat) -> mat.name().endsWith("_SIGN")).toList();
@EventHandler(priority = EventPriority.LOW)
public void onBlockPlace(BlockPlaceEvent event)
{
List<String> blockedBlocksConfig = plugin.config.getStringList("blockedBlocks");
if (blockedBlocksConfig != cachedBlockedBlocksConfig)
{
blockedBlocks.clear();
cachedBlockedBlocksConfig = blockedBlocksConfig;
for (String block : blockedBlocksConfig)
{
try
{
blockedBlocks.add(Material.valueOf(block.toUpperCase()));
}
catch (IllegalArgumentException e)
{
//
}
}
}
Block block = event.getBlock();
if (blockedPlayers.contains(event.getPlayer().getName()))
{
event.setCancelled(true);
return;
}
if (blockedBlocks.contains(block.getType()))
{
block.setType(Material.CAKE);
PlexUtils.disabledEffect(event.getPlayer(), block.getLocation().add(0.5,0.5,0.5));
}
if(SIGNS.contains(block.getType()))
{
Sign sign = (Sign) block.getState();
boolean anythingChanged = false;
for (int i = 0; i < sign.lines().size(); i++)
{
Component line = sign.line(i);
if(line.clickEvent() != null)
{
anythingChanged = true;
sign.line(i, line.clickEvent(null));
}
}
if (anythingChanged)
{
sign.update(true);
PlexUtils.disabledEffect(event.getPlayer(), block.getLocation().add(0.5, 0.5, 0.5));
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(BlockBreakEvent event)
{
if (blockedPlayers.size() == 0)
{
return;
}
if (blockedPlayers.contains(event.getPlayer().getName()))
{
event.setCancelled(true);
return;
}
}
}

View File

@ -1,63 +1,31 @@
package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.listener.annotation.Toggleable;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import io.papermc.paper.chat.ChatRenderer;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.jetbrains.annotations.NotNull;
@Toggleable("chat.enabled")
public class ChatListener extends PlexListener
{
private final PlexChatRenderer renderer = new PlexChatRenderer();
public static void adminChat(CommandSender sender, String message)
{
for (Player player : Bukkit.getOnlinePlayers())
{
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
if (plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN))
{
player.sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (player.hasPermission("plex.adminchat"))
{
player.sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
}
}
plugin.getServer().getConsoleSender().sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}
@EventHandler
public void onChat(AsyncChatEvent event)
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(event.getPlayer().getUniqueId());
if (PlayerCache.getPunishedPlayer(event.getPlayer().getUniqueId()).isMuted())
{
event.getPlayer().sendMessage(PlexUtils.messageComponent("muted"));
event.setCancelled(true);
return;
}
String prefix = plugin.getRankManager().getPrefix(plexPlayer);
if (!prefix.isEmpty())
Component prefix = plugin.getRankManager().getPrefix(plexPlayer);
if (prefix != null)
{
renderer.hasPrefix = true;
renderer.prefix = prefix;
@ -73,14 +41,15 @@ public class ChatListener extends PlexListener
public static class PlexChatRenderer implements ChatRenderer
{
public boolean hasPrefix;
public String prefix;
public Component prefix;
@Override
public @NotNull Component render(@NotNull Player source, @NotNull Component sourceDisplayName, @NotNull Component message, @NotNull Audience viewer)
{
if (hasPrefix)
{
return Component.empty().append(MiniMessage.miniMessage().deserialize(prefix))
return Component.empty()
.append(prefix)
.append(Component.space())
.append(LegacyComponentSerializer.legacyAmpersand().deserialize("&" + plugin.config.getString("chat.name-color") + LegacyComponentSerializer.legacyAmpersand().serialize(sourceDisplayName)))
.append(Component.space())
@ -89,7 +58,7 @@ public class ChatListener extends PlexListener
.append(message);
}
return Component.empty()
.append(sourceDisplayName)
.append(LegacyComponentSerializer.legacyAmpersand().deserialize("&" + plugin.config.getString("chat.name-color") + LegacyComponentSerializer.legacyAmpersand().serialize(sourceDisplayName)))
.append(Component.space())
.append(Component.text("»").color(NamedTextColor.GRAY))
.append(Component.space())

View File

@ -1,7 +1,14 @@
package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.command.blocker.BaseCommand;
import dev.plex.command.blocker.MatchCommand;
import dev.plex.command.blocker.RegexCommand;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
@ -23,5 +30,44 @@ public class CommandListener extends PlexListener
pl.sendMessage(ChatColor.GRAY + player.getName() + ": " + command);
}
});
if (!plugin.getCommandBlockerManager().loadedYet)
{
event.setCancelled(true);
return;
}
Player player = event.getPlayer();
String message = event.getMessage().substring(1).stripLeading(); // stripLeading() is VITAL for workaround blocking (/ minecraft:summon)
for (BaseCommand blockedCommand : plugin.getCommandBlockerManager().getBlockedCommands())
{
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
if (blockedCommand.getRank() != null && plexPlayer.getRankFromString().isAtLeast(blockedCommand.getRank()))
{
continue;
}
boolean isBlocked = false;
if (blockedCommand instanceof RegexCommand regexCommand)
{
if (regexCommand.getRegex().matcher(message).lookingAt())
{
isBlocked = true;
}
}
else if (blockedCommand instanceof MatchCommand matchCommand)
{
if (message.toLowerCase().startsWith(matchCommand.getMatch().toLowerCase()))
{
isBlocked = true;
}
}
if (isBlocked)
{
event.setCancelled(true);
//PlexLog.debug("Command blocked.");
player.sendMessage(MiniMessage.miniMessage().deserialize(PlexUtils.messageString("blockedCommandColor") + blockedCommand.getMessage()));
return;
}
}
}
}

View File

@ -0,0 +1,14 @@
package dev.plex.listener.impl;
import dev.plex.listener.PlexListener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerDropItemEvent;
public class DropListener extends PlexListener
{
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if (!plugin.config.getBoolean("allowdrops")) event.setCancelled(true);
}
}

View File

@ -1,8 +1,8 @@
package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.DataUtils;
import dev.plex.listener.PlexListener;
import dev.plex.player.PunishedPlayer;
import dev.plex.player.PlexPlayer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
@ -11,7 +11,7 @@ public class FreezeListener extends PlexListener
@EventHandler
public void onPlayerMove(PlayerMoveEvent e)
{
PunishedPlayer player = PlayerCache.getPunishedPlayer(e.getPlayer().getUniqueId());
PlexPlayer player = DataUtils.getPlayer(e.getPlayer().getUniqueId());
if (player.isFrozen())
{
e.setCancelled(true);

View File

@ -0,0 +1,22 @@
package dev.plex.listener.impl;
import dev.plex.cache.DataUtils;
import dev.plex.listener.PlexListener;
import dev.plex.util.PlexUtils;
import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
public class MuteListener extends PlexListener
{
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncChatEvent event)
{
if (DataUtils.getPlayer(event.getPlayer().getUniqueId()).isMuted())
{
event.getPlayer().sendMessage(PlexUtils.messageComponent("muted"));
event.setCancelled(true);
}
}
}

View File

@ -1,21 +1,14 @@
package dev.plex.listener.impl;
import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.SQLPlayerData;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Collections;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -24,11 +17,11 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.Arrays;
import java.util.List;
public class PlayerListener extends PlexListener
{
private final MongoPlayerData mongoPlayerData = plugin.getMongoPlayerData() != null ? plugin.getMongoPlayerData() : null;
private final SQLPlayerData sqlPlayerData = plugin.getSqlPlayerData() != null ? plugin.getSqlPlayerData() : null;
// setting up a player's data
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerSetup(PlayerJoinEvent event)
@ -52,31 +45,47 @@ public class PlayerListener extends PlexListener
PlexLog.log("A player with this name has not joined the server before, creating new entry.");
plexPlayer = new PlexPlayer(player.getUniqueId()); // it doesn't! okay so now create the object
plexPlayer.setName(player.getName()); // set the name of the player
plexPlayer.setIps(Collections.singletonList(player.getAddress().getAddress().getHostAddress().trim())); //set the arraylist of ips
plexPlayer.setIps(Arrays.asList(player.getAddress().getAddress().getHostAddress().trim())); // set the arraylist of ips
DataUtils.insert(plexPlayer); // insert data in some wack db
}
else
{
plexPlayer = DataUtils.getPlayer(player.getUniqueId());
List<String> ips = plexPlayer.getIps();
String currentIP = player.getAddress().getAddress().getHostAddress().trim();
if (!ips.contains(currentIP))
{
PlexLog.debug("New IP address detected for player: " + player.getName() + ". Adding " + currentIP + " to the database.");
ips.add(currentIP);
plexPlayer.setIps(ips);
DataUtils.update(plexPlayer);
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
punishedPlayer.convertPunishments();
if (punishedPlayer.isLockedUp())
if (!plexPlayer.getName().equals(player.getName()))
{
PlexLog.log(plexPlayer.getName() + " has a new name. Changing it to " + player.getName());
plexPlayer.setName(player.getName());
DataUtils.update(plexPlayer);
}
}
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer);
if (plexPlayer.isLockedUp())
{
player.openInventory(player.getInventory());
}
assert plexPlayer != null;
String loginMessage = plugin.getRankManager().getLoginMessage(plexPlayer);
if (!loginMessage.isEmpty())
{
PlexUtils.broadcast(
Component.text(ChatColor.AQUA + player.getName() + " is ").color(NamedTextColor.AQUA)
.append(LegacyComponentSerializer.legacyAmpersand().deserialize(loginMessage)));
PlexUtils.broadcast(MiniMessage.miniMessage().deserialize("<aqua>" + player.getName() + " is " + loginMessage));
}
if (plugin.getStorageType() != StorageType.MONGODB)
{
plexPlayer.loadNotes().whenComplete((notes, throwable) ->
{
//TODO: Send note messages to admins
});
}
}
@ -88,25 +97,17 @@ public class PlayerListener extends PlexListener
if (plugin.getRankManager().isAdmin(plexPlayer))
{
plugin.getAdminList().removeFromCache(UUID.fromString(plexPlayer.getUuid()));
}
if (mongoPlayerData != null) //back to mongo checking
{
mongoPlayerData.update(plexPlayer); //update the player's document
}
else if (sqlPlayerData != null) //sql checking
{
sqlPlayerData.update(plexPlayer);
plugin.getAdminList().removeFromCache(plexPlayer.getUuid());
}
DataUtils.update(plexPlayer);
PlayerCache.getPlexPlayerMap().remove(event.getPlayer().getUniqueId()); //remove them from cache
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInventoryClose(InventoryCloseEvent event)
{
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getPlayer().getUniqueId());
PlexPlayer player = DataUtils.getPlayer(event.getPlayer().getUniqueId());
if (player.isLockedUp())
{
Bukkit.getScheduler().runTaskLater(plugin, () -> event.getPlayer().openInventory(event.getInventory()), 1L);
@ -116,7 +117,7 @@ public class PlayerListener extends PlexListener
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event)
{
PunishedPlayer player = PlayerCache.getPunishedPlayer(event.getWhoClicked().getUniqueId());
PlexPlayer player = DataUtils.getPlayer(event.getWhoClicked().getUniqueId());
if (player.isLockedUp())
{
event.setCancelled(true);

View File

@ -0,0 +1,131 @@
package dev.plex.listener.impl;
import dev.plex.listener.PlexListener;
import dev.plex.util.PlexUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.Directional;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class SpawnListener extends PlexListener
{
private static final List<Material> SPAWN_EGGS = Arrays.stream(Material.values()).filter((mat) -> mat.name().endsWith("_SPAWN_EGG")).toList();
@EventHandler
public void onEntitySpawn(EntitySpawnEvent event)
{
if (event.getEntity().getEntitySpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG)
{
// for the future, we can instead filter and restrict nbt tags right here.
// currently, however, the entity from spawn eggs are spawned by other event handlers
event.setCancelled(true);
return;
}
if (plugin.config.getStringList("blockedEntities").stream().anyMatch(type -> type.equalsIgnoreCase(event.getEntityType().name())))
{
event.setCancelled(true);
Location location = event.getLocation();
Collection<Player> coll = location.getNearbyEntitiesByType(Player.class, 10);
PlexUtils.disabledEffectMultiple(coll.toArray(new Player[coll.size()]), location); // dont let intellij auto correct toArray to an empty array (for efficiency)
}
}
@EventHandler
public void onDispense(BlockDispenseEvent event)
{
ItemStack item = event.getItem();
Material itemType = item.getType();
if (SPAWN_EGGS.contains(itemType))
{
Block block = event.getBlock();
Location blockLoc = block.getLocation().add(0.5,0.5,0.5).add(((Directional) block.getBlockData()).getFacing().getDirection().multiply(0.8));
EntityType eggType = spawnEggToEntityType(itemType);
if (eggType != null)
{
blockLoc.getWorld().spawnEntity(blockLoc, eggType);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityClick(PlayerInteractEntityEvent event)
{
Material handItem = event.getPlayer().getEquipment().getItem(event.getHand()).getType();
if (event.getRightClicked() instanceof Ageable entity)
{
if (SPAWN_EGGS.contains(handItem))
{
EntityType eggType = spawnEggToEntityType(handItem);
if (eggType != null)
{
Entity spawned = entity.getWorld().spawnEntity(entity.getLocation(), eggType);
if (spawned instanceof Ageable ageable)
{
ageable.setBaby();
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)
{
if (SPAWN_EGGS.contains(event.getMaterial()))
{
event.setCancelled(true);
Block clickedBlock = event.getClickedBlock();
if (clickedBlock == null)
{
return;
}
EntityType eggType = spawnEggToEntityType(event.getMaterial());
if (eggType != null)
{
clickedBlock.getWorld().spawnEntity(clickedBlock.getLocation().add(event.getBlockFace().getDirection().multiply(0.8)).add(0.5, 0.5, 0.5), eggType);
}
return;
}
}
}
private static EntityType spawnEggToEntityType(Material mat){
EntityType eggType;
try
{
if (mat == Material.MOOSHROOM_SPAWN_EGG)
{
eggType = EntityType.MUSHROOM_COW;
}
else
{
eggType = EntityType.valueOf(mat.name().substring(0, mat.name().length() - 10));
}
}
catch (IllegalArgumentException ignored)
{
return null;
}
return eggType;
}
}

View File

@ -0,0 +1,60 @@
package dev.plex.listener.impl;
import dev.plex.cache.DataUtils;
import dev.plex.event.AdminAddEvent;
import dev.plex.event.AdminRemoveEvent;
import dev.plex.event.AdminSetRankEvent;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
public class TabListener extends PlexListener
{
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onAdminAdd(AdminAddEvent event)
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onAdminRemove(AdminRemoveEvent event)
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onAdminSetRank(AdminSetRankEvent event)
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
}

View File

@ -1,7 +1,8 @@
package dev.plex.listener.impl;
import dev.plex.Plex;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
@ -12,6 +13,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
@ -19,11 +21,12 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.jetbrains.annotations.NotNull;
public class WorldListener extends PlexListener
{
@EventHandler
public void onBlockPlace(BlockPlaceEvent e)
{
@ -118,6 +121,29 @@ public class WorldListener extends PlexListener
e.setCancelled(true);
}
// TODO: Add an entry setting in the config.yml and allow checking for all worlds
@EventHandler
public void onWorldTeleport(PlayerTeleportEvent e)
{
final World adminworld = Bukkit.getWorld("adminworld");
if (adminworld == null)
{
return;
}
PlexPlayer plexPlayer = DataUtils.getPlayer(e.getPlayer().getUniqueId());
if (e.getTo().getWorld().equals(adminworld))
{
if (plugin.getSystem().equals("ranks") && !plexPlayer.isAdminActive())
{
e.setCancelled(true);
}
else if (plugin.getSystem().equals("permissions") && !e.getPlayer().hasPermission("plex.enter.adminworld"))
{
e.setCancelled(true);
}
}
}
private boolean checkLevel(PlexPlayer player, String[] requiredList)
{
PlexLog.debug("Checking world required levels " + Arrays.toString(requiredList));
@ -132,7 +158,7 @@ public class WorldListener extends PlexListener
switch (title)
{
case DEV -> {
hasAccess = PlexUtils.DEVELOPERS.contains(player.getUuid());
hasAccess = PlexUtils.DEVELOPERS.contains(player.getUuid().toString());
}
case MASTER_BUILDER -> {
hasAccess = Plex.get().config.contains("titles.masterbuilders") && Plex.get().config.getStringList("titles.masterbuilders").contains(player.getName());
@ -149,7 +175,7 @@ public class WorldListener extends PlexListener
{
String rankString = required.split("\\.")[1];
Rank rank = Rank.valueOf(rankString.toUpperCase(Locale.ROOT));
hasAccess = player.getRankFromString().isAtLeast(rank);
hasAccess = rank.isAtLeast(Rank.ADMIN) ? player.isAdminActive() && player.getRankFromString().isAtLeast(rank) : player.getRankFromString().isAtLeast(rank);
}
}
return hasAccess;

View File

@ -1,8 +1,9 @@
package dev.plex.menu;
import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.util.menu.AbstractMenu;
import java.util.Collections;
@ -23,11 +24,11 @@ import org.bukkit.inventory.meta.SkullMeta;
public class PunishedPlayerMenu extends AbstractMenu
{
private final PunishedPlayer punishedPlayer;
private final PlexPlayer punishedPlayer;
private final List<Inventory> inventories = Lists.newArrayList();
public PunishedPlayerMenu(PunishedPlayer player)
public PunishedPlayerMenu(PlexPlayer player)
{
super("§c§lPunishments");
this.punishedPlayer = player;
@ -162,7 +163,7 @@ public class PunishedPlayerMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
assert player != null;
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPlexPlayer(player.getUniqueId());
if (punishedPlayer == null)
{
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -1,8 +1,8 @@
package dev.plex.menu;
import com.google.common.collect.Lists;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.cache.DataUtils;
import dev.plex.player.PlexPlayer;
import dev.plex.util.menu.AbstractMenu;
import java.util.List;
import org.bukkit.Bukkit;
@ -138,7 +138,7 @@ public class PunishmentMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
assert player != null;
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId());
PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId());
if (punishedPlayer == null)
{
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -0,0 +1,143 @@
package dev.plex.module;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.module.exception.ModuleLoadException;
import dev.plex.module.loader.LibraryLoader;
import dev.plex.util.PlexLog;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.bukkit.configuration.file.YamlConfiguration;
@Getter
public class ModuleManager
{
private final List<PlexModule> modules = Lists.newArrayList();
private final LibraryLoader libraryLoader;
public ModuleManager()
{
this.libraryLoader = new LibraryLoader(Plex.get().getLogger());
}
public void loadAllModules()
{
this.modules.clear();
PlexLog.debug(String.valueOf(Plex.get().getModulesFolder().listFiles().length));
Arrays.stream(Plex.get().getModulesFolder().listFiles()).forEach(file ->
{
if (file.getName().endsWith(".jar"))
{
try
{
URLClassLoader loader = new URLClassLoader(
new URL[]{file.toURI().toURL()},
Plex.class.getClassLoader()
);
InputStreamReader internalModuleFile = new InputStreamReader(loader.getResourceAsStream("module.yml"), StandardCharsets.UTF_8);
YamlConfiguration internalModuleConfig = YamlConfiguration.loadConfiguration(internalModuleFile);
String name = internalModuleConfig.getString("name");
if (name == null)
{
throw new ModuleLoadException("Plex module name can't be null!");
}
String main = internalModuleConfig.getString("main");
if (main == null)
{
throw new ModuleLoadException("Plex module main class can't be null!");
}
String description = internalModuleConfig.getString("description", "A Plex module");
String version = internalModuleConfig.getString("version", "1.0");
List<String> libraries = internalModuleConfig.getStringList("libraries");
PlexModuleFile plexModuleFile = new PlexModuleFile(name, main, description, version);
plexModuleFile.setLibraries(libraries);
Class<? extends PlexModule> module = (Class<? extends PlexModule>)Class.forName(main, true, loader);
PlexModule plexModule = module.getConstructor().newInstance();
plexModule.setPlex(Plex.get());
plexModule.setPlexModuleFile(plexModuleFile);
plexModule.setDataFolder(new File(Plex.get().getModulesFolder() + File.separator + plexModuleFile.getName()));
if (!plexModule.getDataFolder().exists())
{
plexModule.getDataFolder().mkdir();
}
plexModule.setLogger(LogManager.getLogger(plexModuleFile.getName()));
modules.add(plexModule);
}
catch (MalformedURLException | ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e)
{
e.printStackTrace();
}
}
});
}
public void loadModules()
{
this.modules.forEach(module ->
{
PlexLog.log("Loading module " + module.getPlexModuleFile().getName() + " with version " + module.getPlexModuleFile().getVersion());
module.load();
// this.libraryLoader.createLoader(module, module.getPlexModuleFile());
});
}
public void enableModules()
{
this.modules.forEach(module ->
{
PlexLog.log("Enabling module " + module.getPlexModuleFile().getName() + " with version " + module.getPlexModuleFile().getVersion());
module.enable();
});
}
public void disableModules()
{
this.modules.forEach(module ->
{
PlexLog.log("Disabling module " + module.getPlexModuleFile().getName() + " with version " + module.getPlexModuleFile().getVersion());
module.getCommands().stream().toList().forEach(plexCommand ->
{
module.unregisterCommand(plexCommand);
Plex.get().getServer().getCommandMap().getKnownCommands().remove(plexCommand.getName());
plexCommand.getAliases().forEach(alias -> Plex.get().getServer().getCommandMap().getKnownCommands().remove(alias));
});
module.getListeners().stream().toList().forEach(module::unregisterListener);
module.disable();
});
}
public void unloadModules()
{
this.disableModules();
this.modules.forEach(module ->
{
try
{
((URLClassLoader)module.getClass().getClassLoader()).close();
}
catch (IOException e)
{
e.printStackTrace();
}
});
}
}

View File

@ -0,0 +1,95 @@
package dev.plex.module;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.listener.PlexListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.Logger;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Getter
@Setter(AccessLevel.MODULE)
public abstract class PlexModule
{
@Getter(AccessLevel.MODULE)
private final List<PlexCommand> commands = Lists.newArrayList();
@Getter(AccessLevel.MODULE)
private final List<PlexListener> listeners = Lists.newArrayList();
private Plex plex;
private PlexModuleFile plexModuleFile;
private File dataFolder;
private Logger logger;
public void load()
{
}
public void enable()
{
}
public void disable()
{
}
public void registerListener(PlexListener listener)
{
listeners.add(listener);
}
public void unregisterListener(PlexListener listener)
{
listeners.remove(listener);
HandlerList.unregisterAll(listener);
}
public void registerCommand(PlexCommand command)
{
commands.add(command);
}
public void unregisterCommand(PlexCommand command)
{
commands.remove(command);
}
public PlexCommand getCommand(String name)
{
return commands.stream().filter(plexCommand -> plexCommand.getName().equalsIgnoreCase(name) || plexCommand.getAliases().stream().map(String::toLowerCase).toList().contains(name.toLowerCase(Locale.ROOT))).findFirst().orElse(null);
}
@Nullable
public InputStream getResource(@NotNull String filename)
{
try
{
URL url = this.getClass().getClassLoader().getResource(filename);
if (url == null)
{
return null;
}
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
}
catch (IOException ex)
{
return null;
}
}
}

View File

@ -0,0 +1,17 @@
package dev.plex.module;
import com.google.common.collect.ImmutableList;
import java.util.List;
import lombok.Data;
@Data
public class PlexModuleFile
{
private final String name;
private final String main;
private final String description;
private final String version;
//TODO: does not work
private List<String> libraries = ImmutableList.of();
}

View File

@ -0,0 +1,10 @@
package dev.plex.module.exception;
public class ModuleLoadException extends RuntimeException
{
public ModuleLoadException(String s)
{
super(s);
}
}

View File

@ -0,0 +1,70 @@
package dev.plex.module.loader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class CustomClassLoader extends URLClassLoader
{
/*public CustomClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
for (URL url : urls) {
super.addURL(url);
}
}*/
public CustomClassLoader(URL jarInJar, ClassLoader parent)
{
super(new URL[]{extractJar(jarInJar)}, parent);
addURL(jarInJar);
}
static URL extractJar(URL jarInJar) throws RuntimeException
{
// get the jar-in-jar resource
if (jarInJar == null)
{
throw new RuntimeException("Could not locate jar-in-jar");
}
// create a temporary file
// on posix systems by default this is only read/writable by the process owner
Path path;
try
{
path = Files.createTempFile("plex-jarinjar", ".jar.tmp");
}
catch (IOException e)
{
throw new RuntimeException("Unable to create a temporary file", e);
}
// mark that the file should be deleted on exit
path.toFile().deleteOnExit();
// copy the jar-in-jar to the temporary file path
try (InputStream in = jarInJar.openStream())
{
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
throw new RuntimeException("Unable to copy jar-in-jar to temporary path", e);
}
try
{
return path.toUri().toURL();
}
catch (MalformedURLException e)
{
throw new RuntimeException("Unable to get URL from path", e);
}
}
}

View File

@ -0,0 +1,266 @@
package dev.plex.module.loader;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.module.PlexModule;
import dev.plex.module.PlexModuleFile;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.RepositoryPolicy;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResolutionException;
import org.eclipse.aether.resolution.DependencyResult;
import org.eclipse.aether.spi.connector.RepositoryConnectorFactory;
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transfer.AbstractTransferListener;
import org.eclipse.aether.transfer.TransferCancelledException;
import org.eclipse.aether.transfer.TransferEvent;
import org.eclipse.aether.transport.http.HttpTransporterFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
//TODO: doesn't work
public class LibraryLoader
{
private final Logger logger;
private final RepositorySystem repository;
private final DefaultRepositorySystemSession session;
private final List<RemoteRepository> repositories;
public LibraryLoader(@NotNull Logger logger)
{
this.logger = logger;
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
this.repository = locator.getService(RepositorySystem.class);
this.session = MavenRepositorySystemUtils.newSession();
session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_FAIL);
session.setLocalRepositoryManager(repository.newLocalRepositoryManager(session, new LocalRepository("libraries")));
session.setTransferListener(new AbstractTransferListener()
{
@Override
public void transferStarted(@NotNull TransferEvent event) throws TransferCancelledException
{
logger.log(Level.INFO, "Downloading {0}", event.getResource().getRepositoryUrl() + event.getResource().getResourceName());
}
});
session.setReadOnly();
this.repositories = repository.newResolutionRepositories(session, Arrays.asList(new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build()));
}
@Nullable
public ClassLoader createLoader(@NotNull PlexModule module, @NotNull PlexModuleFile moduleFile)
{
if (moduleFile.getLibraries().isEmpty())
{
return null;
}
logger.log(Level.INFO, "Loading libraries for {0}", new Object[]{moduleFile.getName()});
logger.log(Level.INFO, "[{0}] Loading {1} libraries... please wait", new Object[]
{
moduleFile.getName(), moduleFile.getLibraries().size()
});
List<Dependency> dependencies = new ArrayList<>();
List<Class<?>> classes = Lists.newArrayList();
List<File> files = Lists.newArrayList();
for (String library : moduleFile.getLibraries())
{
Artifact artifact = new DefaultArtifact(library);
Dependency dependency = new Dependency(artifact, null);
dependencies.add(dependency);
}
DependencyResult result;
try
{
result = repository.resolveDependencies(session, new DependencyRequest(new CollectRequest((Dependency)null, dependencies, repositories), null));
}
catch (DependencyResolutionException ex)
{
throw new RuntimeException("Error resolving libraries", ex);
}
List<URL> jarFiles = new ArrayList<>();
for (ArtifactResult artifact : result.getArtifactResults())
{
File file = artifact.getArtifact().getFile();
files.add(file);
URL url;
try
{
url = file.toURI().toURL();
}
catch (MalformedURLException ex)
{
throw new AssertionError(ex);
}
jarFiles.add(url);
logger.log(Level.INFO, "[{0}] Loaded library {1}", new Object[]
{
moduleFile.getName(), file
});
}
/*List<URL> jarFiles = Lists.newArrayList();
List<Artifact> artifacts = Lists.newArrayList();
List<Class<?>> classes = new ArrayList<>();
for (String library : moduleFile.getLibraries()) {
Artifact artifact = new DefaultArtifact(library);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(artifact);
request.addRepository(this.repositories.get(0));
try {
ArtifactResult result = this.repository.resolveArtifact(this.session, request);
artifact = result.getArtifact();
jarFiles.add(artifact.getFile().toURI().toURL());
logger.log(Level.INFO, "Loaded library {0} for {1}", new Object[]{
artifact.getFile().toURI().toURL().toString(),
moduleFile.getName()
});
artifacts.add(artifact);
} catch (ArtifactResolutionException | MalformedURLException e) {
e.printStackTrace();
}
}*/
logger.log(Level.INFO, "Loaded {0} libraries for {1}", new Object[]{jarFiles.size(), moduleFile.getName()});
// jarFiles.forEach(jar -> new CustomClassLoader(jar, Plex.class.getClassLoader()));
// jarFiles.forEach(jar -> new CustomClassLoader(jar, Plex.class.getClassLoader()));
/*URLClassLoader loader = new URLClassLoader(jarFiles.toArray(URL[]::new), Plex.class.getClassLoader());
dependencies.forEach(artifact -> {
ArrayList<String> classNames;
try {
classNames = getClassNamesFromJar(new JarFile(artifact.getArtifact().getFile()));
for (String className : classNames) {
Class<?> classToLoad = Class.forName(className, true, loader);
classes.add(classToLoad);
}
} catch (Exception e) {
e.printStackTrace();
}
});
classes.forEach(clazz -> logger.log(Level.INFO, "Loading class {0}", new Object[]{clazz.getName()}));*/
jarFiles.forEach(url ->
{
JarURLConnection connection;
try
{
URL url2 = new URL("jar:" + url.toString() + "!/");
/*
connection = (JarURLConnection) url2.openConnection();
logger.log(Level.INFO, "Jar File: " + connection.getJarFileURL().toString());*/
}
catch (IOException e)
{
e.printStackTrace();
}
});
return new URLClassLoader(files.stream().map(File::toURI).map(uri ->
{
try
{
return uri.toURL();
}
catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
}).toList().toArray(URL[]::new)/*jarFiles.stream().map(url -> {
try {
return new URL("jar:" + url.toString() + "!/");
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}).toList().toArray(URL[]::new)*/, Plex.class.getClassLoader())/*new CustomClassLoader(jarFiles.toArray(URL[]::new), Plex.class.getClassLoader())*/;
}
/*public List<Class<?>> loadDependency(List<Path> paths) throws Exception {
List<Class<?>> classes = new ArrayList<>();
for (Path path : paths) {
URL url = path.toUri().toURL();
URLClassLoader child = new URLClassLoader(new URL[]{url}, this.getClass().getClassLoader());
ArrayList<String> classNames = getClassNamesFromJar(path.toString());
for (String className : classNames) {
Class classToLoad = Class.forName(className, true, child);
classes.add(classToLoad);
}
}
return classes;
}*/
private ArrayList<String> getClassNamesFromJar(JarFile file) throws Exception
{
ArrayList<String> classNames = new ArrayList<>();
try
{
//Iterate through the contents of the jar file
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
//Pick file that has the extension of .class
if ((entry.getName().endsWith(".class")))
{
String className = entry.getName().replaceAll("/", "\\.");
String myClass = className.substring(0, className.lastIndexOf('.'));
classNames.add(myClass);
}
}
}
catch (Exception e)
{
throw new Exception("Error while getting class names from jar", e);
}
return classNames;
}
}

View File

@ -1,13 +1,24 @@
package dev.plex.player;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.extra.Note;
import dev.plex.rank.enums.Rank;
import java.util.ArrayList;
import dev.plex.storage.StorageType;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import dev.plex.util.adapter.LocalDateTimeSerializer;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@ -27,11 +38,11 @@ public class PlexPlayer
@Setter(AccessLevel.NONE)
@Indexed(options = @IndexOptions(unique = true))
private String uuid;
private UUID uuid;
@Indexed
private String name;
private Player player;
private transient Player player;
private String loginMessage;
private String prefix;
@ -39,11 +50,20 @@ public class PlexPlayer
private boolean vanished;
private boolean commandSpy;
// These fields are transient so MongoDB doesn't automatically drop them in.
private transient boolean frozen;
private transient boolean muted;
private transient boolean lockedUp;
private boolean adminActive;
private long coins;
private String rank;
private List<String> ips;
private List<String> ips = Lists.newArrayList();
private List<Punishment> punishments = Lists.newArrayList();
private List<Note> notes = Lists.newArrayList();
public PlexPlayer()
{
@ -51,9 +71,9 @@ public class PlexPlayer
public PlexPlayer(UUID playerUUID)
{
this.uuid = playerUUID.toString();
this.uuid = playerUUID;
this.id = uuid.substring(0, 8);
this.id = uuid.toString().substring(0, 8);
this.name = "";
this.player = Bukkit.getPlayer(name);
@ -66,9 +86,8 @@ public class PlexPlayer
this.coins = 0;
this.ips = new ArrayList<>();
this.rank = "";
this.loadPunishments();
}
public String displayName()
@ -78,8 +97,8 @@ public class PlexPlayer
public Rank getRankFromString()
{
OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(uuid));
if (rank.isEmpty())
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (rank.isEmpty() || !isAdminActive())
{
if (player.isOp())
{
@ -95,4 +114,26 @@ public class PlexPlayer
return Rank.valueOf(rank.toUpperCase());
}
}
public void loadPunishments()
{
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
this.setPunishments(Plex.get().getSqlPunishment().getPunishments(this.getUuid()).stream().filter(punishment -> punishment.getPunished().equals(this.getUuid())).collect(Collectors.toList()));
}
}
public CompletableFuture<List<Note>> loadNotes()
{
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
return Plex.get().getSqlNotes().getNotes(this.getUuid());
}
return null;
}
public String toJSON()
{
return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer()).create().toJson(this);
}
}

View File

@ -1,222 +0,0 @@
package dev.plex.player;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.event.PunishedPlayerFreezeEvent;
import dev.plex.event.PunishedPlayerLockupEvent;
import dev.plex.event.PunishedPlayerMuteEvent;
import dev.plex.punishment.Punishment;
import dev.plex.util.PlexLog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
@Getter
public class PunishedPlayer extends PlexBase
{
//everything in here will be stored in redis
@Setter(AccessLevel.NONE)
private String uuid;
private boolean muted;
private boolean frozen;
private boolean lockedUp;
public PunishedPlayer(UUID playerUUID)
{
this.uuid = playerUUID.toString();
this.muted = false;
this.frozen = false;
this.lockedUp = false;
}
public void setFrozen(boolean frozen)
{
PunishedPlayerFreezeEvent e = new PunishedPlayerFreezeEvent(this, this.frozen);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.frozen = frozen;
}
}
public void setMuted(boolean muted)
{
PunishedPlayerMuteEvent e = new PunishedPlayerMuteEvent(this, this.muted);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.muted = muted;
}
}
public void setLockedUp(boolean lockedUp)
{
PunishedPlayerLockupEvent e = new PunishedPlayerLockupEvent(this, this.lockedUp);
Bukkit.getServer().getPluginManager().callEvent(e);
if (!e.isCancelled())
{
this.lockedUp = lockedUp;
Player self = Bukkit.getPlayer(UUID.fromString(this.uuid));
if (self != null)
{
self.openInventory(self.getInventory());
}
}
}
public File getPunishmentsFile()
{
File folder = new File(Plex.get().getDataFolder() + File.separator + "punishments");
if (!folder.exists())
{
folder.mkdir();
}
File file = new File(folder, getUuid() + ".json");
if (!file.exists())
{
try
{
file.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return file;
}
@SneakyThrows
public void convertPunishments()
{
if (!plugin.getRedisConnection().isEnabled())
{
return;
}
List<Punishment> punishments = Lists.newArrayList();
File file = getPunishmentsFile();
//Converting from File to Redis
if (isNotEmpty(file))
{
PlexLog.debug("Starting converting punishments from file to Redis for " + uuid + "...");
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
JSONArray array = object.getJSONObject(getUuid()).getJSONArray("punishments");
for (int i = 0; i < array.toList().size(); i++)
{
Punishment punishment = Punishment.fromJson(array.get(i).toString());
punishments.add(punishment);
}
PlexLog.debug("Successfully converted all file punishments into array (" + punishments.size() + ")");
if (!punishments.isEmpty())
{
Map<String, List<String>> filesList = Maps.newHashMap();
filesList.put("punishments", punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
JSONObject obj = new JSONObject().put(uuid, filesList);
if (plugin.getRedisConnection().getJedis().exists(uuid))
{
PlexLog.debug("File and Redis Matches? " + plugin.getRedisConnection().getJedis().get(uuid).equalsIgnoreCase(obj.toString()));
if (!plugin.getRedisConnection().getJedis().get(uuid).equalsIgnoreCase(obj.toString()))
{
plugin.getRedisConnection().getJedis().set(uuid, obj.toString());
PlexLog.debug("Updated Redis Punishments to match with file");
}
}
else
{
plugin.getRedisConnection().getJedis().set(uuid, obj.toString());
}
}
}
}
@SneakyThrows
public List<Punishment> getPunishments()
{
List<Punishment> punishments = Lists.newArrayList();
if (plugin.getRedisConnection().isEnabled())
{
PlexLog.debug("Getting punishments from Redis...");
if (!plugin.getRedisConnection().getJedis().exists(uuid))
{
return punishments;
}
String strObj = plugin.getRedisConnection().getJedis().get(uuid);
if (strObj.isEmpty() || !strObj.startsWith("{"))
{
return punishments;
}
JSONObject object = new JSONObject(strObj);
object.getJSONObject(uuid).getJSONArray("punishments").forEach(obj ->
{
JSONObject converted = new JSONObject(obj.toString());
if (converted.isNull("active"))
{
converted.put("active", false);
}
Punishment punishment = Punishment.fromJson(converted.toString());
punishments.add(punishment);
});
plugin.getRedisConnection().getJedis().close();
return punishments;
}
File file = getPunishmentsFile();
if (isNotEmpty(file))
{
try
{
PlexLog.debug("Getting punishments from locally stored JSON files...");
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
object.getJSONObject(getUuid()).getJSONArray("punishments").forEach(obj ->
{
Punishment punishment = Punishment.fromJson(obj.toString());
punishments.add(punishment);
});
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
return punishments;
}
private boolean isNotEmpty(File file)
{
try
{
return !FileUtils.readFileToString(file, StandardCharsets.UTF_8).trim().isEmpty();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
}

View File

@ -1,7 +1,7 @@
package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import dev.morphia.annotations.Entity;
import dev.plex.Plex;
import dev.plex.util.MojangUtils;
import dev.plex.util.PlexUtils;
@ -9,7 +9,6 @@ import dev.plex.util.adapter.LocalDateTimeDeserializer;
import dev.plex.util.adapter.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
@ -17,30 +16,31 @@ import net.kyori.adventure.text.Component;
@Getter
@Setter
@Entity
public class Punishment
{
private static final String banUrl = Plex.get().config.getString("banning.ban_url");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
private final UUID punished;
private final UUID punisher;
private final List<String> IPS;
private String ip;
private String punishedUsername;
private PunishmentType type;
private String reason;
private boolean customTime;
private boolean active; // Field is only for bans
private LocalDateTime endDate;
public Punishment()
{
this.punished = null;
this.punisher = null;
}
public Punishment(UUID punished, UUID punisher)
{
this.punished = punished;
this.punisher = punisher;
this.IPS = Lists.newArrayList();
this.punishedUsername = "";
this.type = null;
this.reason = "";
this.customTime = false;
this.endDate = null;
}
public static Component generateBanMessage(Punishment punishment)

View File

@ -1,75 +1,56 @@
package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.DataUtils;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject;
import org.json.JSONTokener;
import redis.clients.jedis.Jedis;
public class PunishmentManager extends PlexBase
{
private final List<String> bannedIPs = Lists.newArrayList();
private final List<String> bannedUsernames = Lists.newArrayList();
private final List<UUID> bannedUUIDs = Lists.newArrayList();
@Getter
private final List<IndefiniteBan> indefiniteBans = Lists.newArrayList();
public void mergeIndefiniteBans()
{
this.bannedUsernames.clear();
this.bannedIPs.clear();
this.bannedUUIDs.clear();
this.bannedUUIDs.addAll(Plex.get().indefBans.getStringList("uuids").stream().filter(string ->
this.indefiniteBans.clear();
Plex.get().indefBans.getKeys(false).forEach(key ->
{
try
{
UUID uuid = UUID.fromString(string);
return true;
} catch (IllegalArgumentException e)
{
return false;
}
}).map(UUID::fromString).toList());
IndefiniteBan ban = new IndefiniteBan();
ban.ips.addAll(Plex.get().getIndefBans().getStringList(key + ".ips"));
ban.usernames.addAll(Plex.get().getIndefBans().getStringList(key + ".users"));
ban.uuids.addAll(Plex.get().getIndefBans().getStringList(key + ".uuids").stream().map(UUID::fromString).toList());
this.indefiniteBans.add(ban);
});
this.bannedIPs.addAll(Plex.get().indefBans.getStringList("ips"));
this.bannedUsernames.addAll(Plex.get().indefBans.getStringList("usernames"));
PlexLog.log("Loaded {0} UUID(s), {1} IP(s), and {2} username(s) as indefinitely banned", this.bannedUUIDs.size(), this.bannedIPs.size(), this.bannedUsernames.size());
PlexLog.log("Loaded {0} UUID(s), {1} IP(s), and {2} username(s) as indefinitely banned", this.indefiniteBans.stream().map(IndefiniteBan::getUuids).mapToLong(Collection::size).sum(), this.indefiniteBans.stream().map(IndefiniteBan::getIps).mapToLong(Collection::size).sum(), this.indefiniteBans.stream().map(IndefiniteBan::getUsernames).mapToLong(Collection::size).sum());
if (Plex.get().getRedisConnection().isEnabled())
{
PlexLog.log("Asynchronously uploading all indefinite bans to Redis");
Plex.get().getRedisConnection().runAsync(jedis -> {
jedis.set("indefbanned-uuids", new Gson().toJson(this.bannedUUIDs));
jedis.set("indefbanned-ips", new Gson().toJson(this.bannedIPs));
jedis.set("indefbanned-users", new Gson().toJson(this.bannedUsernames));
this.bannedIPs.clear();
this.bannedUsernames.clear();
this.bannedUUIDs.clear();
Plex.get().getRedisConnection().runAsync(jedis ->
{
jedis.set("indefbans", new Gson().toJson(indefiniteBans));
});
}
}
@ -78,81 +59,54 @@ public class PunishmentManager extends PlexBase
{
if (Plex.get().getRedisConnection().isEnabled())
{
List<UUID> uuids = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbanned-uuids"), new TypeToken<List<UUID>>(){}.getType());
return uuids.contains(uuid);
PlexLog.debug("Checking if UUID is banned in Redis");
List<IndefiniteBan> bans = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbans"), new TypeToken<List<IndefiniteBan>>()
{
}.getType());
return bans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUuids().contains(uuid));
}
return this.bannedUUIDs.contains(uuid);
return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUuids().contains(uuid));
}
public boolean isIndefIPBanned(String ip)
{
if (Plex.get().getRedisConnection().isEnabled())
{
List<String> ips = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbanned-ips"), new TypeToken<List<String>>(){}.getType());
return ips.contains(ip);
PlexLog.debug("Checking if IP is banned in Redis");
List<IndefiniteBan> bans = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbans"), new TypeToken<List<IndefiniteBan>>()
{
}.getType());
return bans.stream().anyMatch(indefiniteBan -> indefiniteBan.getIps().contains(ip));
}
return this.bannedIPs.contains(ip);
return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getIps().contains(ip));
}
public boolean isIndefUserBanned(String username)
{
if (Plex.get().getRedisConnection().isEnabled())
{
List<String> users = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbanned-users"), new TypeToken<List<String>>(){}.getType());
return users.contains(username);
PlexLog.debug("Checking if username is banned in Redis");
List<IndefiniteBan> bans = new Gson().fromJson(Plex.get().getRedisConnection().getJedis().get("indefbans"), new TypeToken<List<IndefiniteBan>>()
{
}.getType());
return bans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUsernames().contains(username));
}
return this.bannedUsernames.contains(username);
return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUsernames().contains(username));
}
public void insertPunishment(PunishedPlayer player, Punishment punishment)
public void issuePunishment(PlexPlayer plexPlayer, Punishment punishment)
{
File file = player.getPunishmentsFile();
try
plexPlayer.getPunishments().add(punishment);
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
if (isNotEmpty(file))
CompletableFuture.runAsync(() ->
{
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
object.getJSONObject(punishment.getPunished().toString()).getJSONArray("punishments").put(punishment.toJSON());
if (plugin.getRedisConnection().isEnabled())
{
plugin.getRedisConnection().getJedis().set(player.getUuid(), object.toString());
PlexLog.debug("Added " + player.getUuid() + "'s punishment to the Redis database.");
plugin.getRedisConnection().getJedis().close();
}
FileWriter writer = new FileWriter(file);
writer.append(object.toString(8));
writer.flush();
writer.close();
DataUtils.update(plexPlayer);
});
}
else
{
JSONObject object = new JSONObject();
Map<String, List<String>> punishments = Maps.newHashMap();
List<String> punishmentList = Lists.newArrayList();
punishmentList.add(punishment.toJSON());
punishments.put("punishments", punishmentList);
object.put(punishment.getPunished().toString(), punishments);
if (plugin.getRedisConnection().isEnabled())
{
plugin.getRedisConnection().getJedis().set(player.getUuid(), object.toString());
PlexLog.debug("Added " + player.getUuid() + "'s punishment to the Redis database.");
plugin.getRedisConnection().getJedis().close();
}
FileWriter writer = new FileWriter(file);
writer.append(object.toString(8));
writer.flush();
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
Plex.get().getSqlPunishment().insertPunishment(punishment);
}
}
@ -169,43 +123,49 @@ public class PunishmentManager extends PlexBase
return false;
}
public CompletableFuture<Boolean> isAsyncBanned(UUID uuid)
{
return CompletableFuture.supplyAsync(() ->
{
PlexPlayer player = DataUtils.getPlayer(uuid);
player.loadPunishments();
return player.getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
});
}
public boolean isBanned(UUID uuid)
{
return PlayerCache.getPunishedPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
/*if (!DataUtils.hasPlayedBefore(uuid))
{
return false;
}*/
return DataUtils.getPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
}
public boolean isBanned(PunishedPlayer player)
public boolean isBanned(PlexPlayer player)
{
return isBanned(UUID.fromString(player.getUuid()));
return isBanned(player.getUuid());
}
public List<Punishment> getActiveBans()
public CompletableFuture<List<Punishment>> getActiveBans()
{
List<Punishment> punishments = Lists.newArrayList();
Jedis jedis = Plex.get().getRedisConnection().getJedis();
jedis.keys("*").forEach(key ->
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
try
return CompletableFuture.supplyAsync(() ->
{
UUID uuid = UUID.fromString(key);
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
object.getJSONObject(uuid.toString()).getJSONArray("punishments").forEach(json ->
{
Punishment punishment = Punishment.fromJson(json.toString());
if (punishment.isActive() && punishment.getType() == PunishmentType.BAN)
{
punishments.add(punishment);
}
List<PlexPlayer> players = Plex.get().getMongoPlayerData().getPlayers();
return players.stream().map(PlexPlayer::getPunishments).flatMap(Collection::stream).filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).toList();
});
}
catch (IllegalArgumentException ignored)
else
{
}
CompletableFuture<List<Punishment>> future = new CompletableFuture<>();
Plex.get().getSqlPunishment().getPunishments().whenComplete((punishments, throwable) ->
{
future.complete(punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).toList());
});
return punishments;
return future;
}
}
public void unban(Punishment punishment)
@ -213,63 +173,25 @@ public class PunishmentManager extends PlexBase
this.unban(punishment.getPunished());
}
public void unban(UUID uuid)
public CompletableFuture<Void> unban(UUID uuid)
{
if (Plex.get().getRedisConnection().isEnabled())
if (Plex.get().getStorageType() == StorageType.MONGODB)
{
Jedis jedis = Plex.get().getRedisConnection().getJedis();
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
List<Punishment> punishments = object.getJSONObject(uuid.toString()).getJSONArray("punishments").toList().stream().map(obj -> Punishment.fromJson(obj.toString())).collect(Collectors.toList());
while (punishments.stream().anyMatch(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN))
return CompletableFuture.runAsync(() ->
{
punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).findFirst().ifPresent(punishment ->
{
int index = punishments.indexOf(punishment);
punishment.setActive(false);
punishments.set(index, punishment);
PlexPlayer plexPlayer = DataUtils.getPlayer(uuid);
plexPlayer.setPunishments(plexPlayer.getPunishments().stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN)
.peek(punishment -> punishment.setActive(false)).collect(Collectors.toList()));
DataUtils.update(plexPlayer);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
jedis.set(uuid.toString(), object.toString());
}
PunishedPlayer player = PlayerCache.getPunishedPlayer(uuid);
File file = player.getPunishmentsFile();
if (isNotEmpty(file))
else
{
try (FileInputStream fis = new FileInputStream(file))
{
JSONTokener tokener = new JSONTokener(fis);
JSONObject object = new JSONObject(tokener);
List<Punishment> punishments = object.getJSONObject(uuid.toString()).getJSONArray("punishments").toList().stream().map(obj -> Punishment.fromJson(obj.toString())).collect(Collectors.toList());
while (punishments.stream().anyMatch(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN))
{
punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).findFirst().ifPresent(punishment ->
{
int index = punishments.indexOf(punishment);
punishment.setActive(false);
punishments.set(index, punishment);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
FileWriter writer = new FileWriter(file);
writer.append(object.toString());
writer.flush();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return Plex.get().getSqlPunishment().removeBan(uuid);
}
}
private void issuePunishment(PunishedPlayer player, Punishment punishment)
private void doPunishment(PlexPlayer player, Punishment punishment)
{
if (punishment.getType() == PunishmentType.FREEZE)
{
@ -288,7 +210,7 @@ public class PunishmentManager extends PlexBase
return;
}
player.setFrozen(false);
Bukkit.broadcast(PlexUtils.messageComponent("unfrozePlayer", "Plex", Bukkit.getOfflinePlayer(UUID.fromString(player.getUuid())).getName()));
Bukkit.broadcast(PlexUtils.messageComponent("unfrozePlayer", "Plex", Bukkit.getOfflinePlayer(player.getUuid()).getName()));
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
@ -309,15 +231,23 @@ public class PunishmentManager extends PlexBase
return;
}
player.setMuted(false);
Bukkit.broadcast(PlexUtils.messageComponent("unmutedPlayer", "Plex", Bukkit.getOfflinePlayer(UUID.fromString(player.getUuid())).getName()));
Bukkit.broadcast(PlexUtils.messageComponent("unmutedPlayer", "Plex", Bukkit.getOfflinePlayer(player.getUuid()).getName()));
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
}
public void doPunishment(PunishedPlayer player, Punishment punishment)
public void punish(PlexPlayer player, Punishment punishment)
{
issuePunishment(player, punishment);
insertPunishment(player, punishment);
doPunishment(player, punishment);
}
@Data
public static class IndefiniteBan
{
private final List<String> usernames = Lists.newArrayList();
private final List<UUID> uuids = Lists.newArrayList();
private final List<String> ips = Lists.newArrayList();
}
}

View File

@ -2,5 +2,5 @@ package dev.plex.punishment;
public enum PunishmentType
{
MUTE, FREEZE, BAN, KICK
MUTE, FREEZE, BAN, KICK, SMITE
}

View File

@ -0,0 +1,26 @@
package dev.plex.punishment.extra;
import com.google.gson.GsonBuilder;
import dev.morphia.annotations.Entity;
import dev.plex.util.adapter.LocalDateTimeSerializer;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.UUID;
@Data
@Entity
public class Note
{
private final UUID uuid;
private final String note;
private final UUID writtenBy;
private final LocalDateTime timestamp;
private int id; // This will be automatically set from addNote
public String toJSON()
{
return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer()).create().toJson(this);
}
}

View File

@ -12,6 +12,9 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
@ -88,17 +91,17 @@ public class RankManager
}
}
public String getPrefix(PlexPlayer player)
public Component getPrefix(PlexPlayer player)
{
if (!player.getPrefix().isEmpty())
if (!player.getPrefix().equals(""))
{
return player.getPrefix();
return MiniMessage.miniMessage().deserialize(player.getPrefix());
}
if (Plex.get().config.contains("titles.owners") && Plex.get().config.getStringList("titles.owners").contains(player.getName()))
{
return Title.OWNER.getPrefix();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid())) // don't remove or we will front door ur mother
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
{
return Title.DEV.getPrefix();
}
@ -110,7 +113,7 @@ public class RankManager
{
return player.getRankFromString().getPrefix();
}
return "";
return null;
}
public String getLoginMessage(PlexPlayer player)
@ -123,7 +126,7 @@ public class RankManager
{
return Title.OWNER.getLoginMessage();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid())) // don't remove or we will front door ur mother
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
{
return Title.DEV.getLoginMessage();
}
@ -138,13 +141,34 @@ public class RankManager
return "";
}
public NamedTextColor getColor(PlexPlayer player)
{
if (Plex.get().config.contains("titles.owners") && Plex.get().config.getStringList("titles.owners").contains(player.getName()))
{
return Title.OWNER.getColor();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
{
return Title.DEV.getColor();
}
if (Plex.get().config.contains("titles.masterbuilders") && Plex.get().config.getStringList("titles.masterbuilders").contains(player.getName()))
{
return Title.MASTER_BUILDER.getColor();
}
if (Plex.get().getSystem().equalsIgnoreCase("ranks") && isAdmin(player))
{
return player.getRankFromString().getColor();
}
return NamedTextColor.WHITE;
}
public boolean isAdmin(PlexPlayer plexPlayer)
{
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN);
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN) && plexPlayer.isAdminActive();
}
public boolean isSeniorAdmin(PlexPlayer plexPlayer)
{
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.SENIOR_ADMIN);
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.SENIOR_ADMIN) && plexPlayer.isAdminActive();
}
}

View File

@ -2,20 +2,20 @@ package dev.plex.rank.enums;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.ChatColor;
import org.json.JSONObject;
@Getter
public enum Rank
{
IMPOSTOR(-1, ChatColor.AQUA + "an " + ChatColor.YELLOW + "Impostor", "Impostor", "&8[&eImp&8]"),
NONOP(0, "a " + ChatColor.WHITE + "Non-Op", "Non-Op", ""),
OP(1, "an " + ChatColor.GREEN + "Operator", "Operator", "&8[&aOP&8]"),
ADMIN(2, "an " + ChatColor.DARK_GREEN + "Admin", "Admin", "&8[&2Admin&8]"),
SENIOR_ADMIN(3, "a " + ChatColor.GOLD + "Senior Admin", "Senior Admin", "&8[&6SrA&8]"),
EXECUTIVE(4, "an " + ChatColor.RED + "Executive", "Executive", "&8[&cExec&8]");
IMPOSTOR(-1, "<aqua>an <yellow>Impostor<reset>", "Impostor", "<dark_gray>[<yellow>Imp<dark_gray>]", NamedTextColor.YELLOW),
NONOP(0, "a <white>Non-Op<reset>", "Non-Op", "", NamedTextColor.WHITE),
OP(1, "an <green>Op<reset>", "Operator", "<dark_gray>[<green>OP<dark_gray>]", NamedTextColor.GREEN),
ADMIN(2, "an <dark_green>Admin<reset>", "Admin", "<dark_gray>[<green>Admin<dark_gray>]", NamedTextColor.DARK_GREEN),
SENIOR_ADMIN(3, "a <gold>Senior Admin<reset>", "Senior Admin", "<dark_gray>[<gold>SrA<dark_gray>]", NamedTextColor.GOLD),
EXECUTIVE(4, "an <red>Executive<reset>", "Executive", "<dark_gray>[<red>Exec<dark_gray>]", NamedTextColor.RED);
private final int level;
@ -28,12 +28,16 @@ public enum Rank
@Setter
private String prefix;
Rank(int level, String loginMessage, String readable, String prefix)
@Getter
private NamedTextColor color;
Rank(int level, String loginMessage, String readable, String prefix, NamedTextColor color)
{
this.level = level;
this.loginMessage = loginMessage;
this.readable = readable;
this.prefix = prefix;
this.color = color;
}
public boolean isAtLeast(Rank rank)
@ -41,9 +45,9 @@ public enum Rank
return this.level >= rank.getLevel();
}
public String getPrefix()
public Component getPrefix()
{
return MiniMessage.miniMessage().serialize(LegacyComponentSerializer.legacyAmpersand().deserialize(this.prefix));
return MiniMessage.miniMessage().deserialize(this.prefix);
}
public JSONObject toJSON()

View File

@ -2,17 +2,17 @@ package dev.plex.rank.enums;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.ChatColor;
import org.json.JSONObject;
@Getter
public enum Title
{
MASTER_BUILDER(0, ChatColor.AQUA + "a " + ChatColor.DARK_AQUA + "Master Builder", "Master Builder", "&8[&3Master Builder&8]"),
DEV(1, ChatColor.AQUA + "a " + ChatColor.DARK_PURPLE + "Developer", "Developer", "&8[&5Developer&8]"),
OWNER(2, ChatColor.AQUA + "an " + ChatColor.BLUE + "Owner", "Owner", "&8[&9Owner&8]");
MASTER_BUILDER(0, "<aqua>a <dark_aqua>Master Builder<reset>", "Master Builder", "<dark_gray>[<dark_aqua>Master Builder<dark_gray>]", NamedTextColor.DARK_AQUA),
DEV(1, "<aqua>a <dark_purple>Developer<reset>", "Developer", "<dark_gray>[<dark_purple>Developer<dark_gray>]", NamedTextColor.DARK_PURPLE),
OWNER(2, "<aqua>an <blue>Owner<reset>", "Owner", "<dark_gray>[<blue>Owner<dark_gray>]", NamedTextColor.BLUE);
private final int level;
@ -25,17 +25,21 @@ public enum Title
@Setter
private String prefix;
Title(int level, String loginMessage, String readable, String prefix)
@Getter
private NamedTextColor color;
Title(int level, String loginMessage, String readable, String prefix, NamedTextColor color)
{
this.level = level;
this.loginMessage = loginMessage;
this.readable = readable;
this.prefix = prefix;
this.color = color;
}
public String getPrefix()
public Component getPrefix()
{
return MiniMessage.miniMessage().serialize(LegacyComponentSerializer.legacyAmpersand().deserialize(this.prefix));
return MiniMessage.miniMessage().deserialize(this.prefix);
}
public JSONObject toJSON()

View File

@ -1,25 +1,31 @@
package dev.plex.services;
import dev.plex.PlexBase;
import lombok.Getter;
import lombok.Setter;
@Getter
public abstract class AbstractService extends PlexBase implements IService
{
private boolean asynchronous;
private boolean repeating;
@Setter
private int taskId;
public AbstractService(boolean repeating, boolean async)
{
this.repeating = repeating;
this.asynchronous = async;
}
public boolean isRepeating()
public void onStart()
{
return repeating;
}
public boolean isAsynchronous()
public void onEnd()
{
return asynchronous;
}
}

View File

@ -2,11 +2,11 @@ package dev.plex.services;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.services.impl.BanService;
import dev.plex.services.impl.GameRuleService;
import dev.plex.services.impl.UpdateCheckerService;
import java.util.List;
import dev.plex.services.impl.*;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import java.util.List;
public class ServiceManager
{
@ -17,25 +17,74 @@ public class ServiceManager
registerService(new BanService());
registerService(new GameRuleService());
registerService(new UpdateCheckerService());
registerService(new AutoWipeService());
registerService(new CommandBlockerService());
}
public void startServices()
{
for (AbstractService service : services)
{
startService(service);
}
}
public void endServices()
{
services.forEach(this::endService);
}
public AbstractService getService(Class<? extends AbstractService> clazz)
{
return services.stream().filter(service -> service.getClass().isAssignableFrom(clazz)).findFirst().orElse(null);
}
public void startService(AbstractService service)
{
if (!service.isRepeating())
{
Bukkit.getScheduler().runTask(Plex.get(), service::run);
int time = service.repeatInSeconds();
BukkitTask task;
if (time == 0)
{
task = Bukkit.getScheduler().runTask(Plex.get(), service::run);
}
else
{
task = Bukkit.getScheduler().runTaskLater(Plex.get(), service::run, time);
}
service.setTaskId(task.getTaskId());
}
else if (service.isRepeating() && service.isAsynchronous())
{
Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
BukkitTask task = Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
service.setTaskId(task.getTaskId());
}
else if (service.isRepeating() && !service.isAsynchronous())
{
Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
BukkitTask task = Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
service.setTaskId(task.getTaskId());
}
if (!services.contains(service))
{
services.add(service);
}
service.onStart();
}
public void endService(AbstractService service, boolean remove)
{
Bukkit.getScheduler().cancelTask(service.getTaskId());
service.onEnd();
if (remove)
{
services.remove(service);
}
}
public void endService(AbstractService service)
{
endService(service, false);
}
private void registerService(AbstractService service)

View File

@ -0,0 +1,44 @@
package dev.plex.services.impl;
import dev.plex.Plex;
import dev.plex.services.AbstractService;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import java.util.List;
public class AutoWipeService extends AbstractService
{
public AutoWipeService()
{
super(true, false);
}
@Override
public void run()
{
if (Plex.get().config.getBoolean("autowipe.enabled"))
{
List<String> entities = plugin.config.getStringList("autowipe.entities");
for (World world : Bukkit.getWorlds())
{
for (Entity entity : world.getEntities())
{
if (entities.stream().anyMatch(entityName -> entityName.equalsIgnoreCase(entity.getType().name())))
{
entity.remove();
}
}
}
}
}
@Override
public int repeatInSeconds()
{
return Math.max(1, plugin.config.getInt("autowipe.interval"));
}
}

View File

@ -1,7 +1,6 @@
package dev.plex.services.impl;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.services.AbstractService;
import java.time.LocalDateTime;
import net.kyori.adventure.text.Component;
@ -17,14 +16,17 @@ public class BanService extends AbstractService
@Override
public void run()
{
for (Punishment punishment : Plex.get().getPunishmentManager().getActiveBans())
Plex.get().getPunishmentManager().getActiveBans().whenComplete((punishments, throwable) ->
{
punishments.forEach(punishment ->
{
if (LocalDateTime.now().isAfter(punishment.getEndDate()))
{
Plex.get().getPunishmentManager().unban(punishment);
Bukkit.broadcast(Component.text("Plex - Unbanned " + Bukkit.getOfflinePlayer(punishment.getPunished()).getName()));
}
}
});
});
}
@Override

View File

@ -0,0 +1,25 @@
package dev.plex.services.impl;
import dev.plex.services.AbstractService;
import dev.plex.util.PlexLog;
public class CommandBlockerService extends AbstractService
{
public CommandBlockerService()
{
super(false, true);
}
@Override
public void run()
{
plugin.getCommandBlockerManager().syncCommands();
PlexLog.log("Command Blocker commands loaded");
}
@Override
public int repeatInSeconds()
{
return 0;
}
}

View File

@ -3,6 +3,7 @@ package dev.plex.services.impl;
import dev.plex.services.AbstractService;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Locale;
import org.bukkit.Bukkit;
import org.bukkit.World;
@ -18,8 +19,17 @@ public class GameRuleService extends AbstractService
{
for (World world : Bukkit.getWorlds())
{
PlexUtils.commitGameRules(world);
PlexLog.debug("Set gamerules for world: " + world.getName());
PlexUtils.commitGlobalGameRules(world);
PlexLog.log("Set global gamerules for world: " + world.getName());
}
for (String world : plugin.config.getConfigurationSection("worlds").getKeys(false))
{
World bukkitWorld = Bukkit.getWorld(world);
if (bukkitWorld != null)
{
PlexUtils.commitSpecificGameRules(bukkitWorld);
PlexLog.log("Set specific gamerules for world: " + world.toLowerCase(Locale.ROOT));
}
}
}

View File

@ -1,22 +1,23 @@
package dev.plex.services.impl;
import dev.plex.services.AbstractService;
import org.bukkit.Bukkit;
public class UpdateCheckerService extends AbstractService
{
private boolean newVersion = false;
public UpdateCheckerService()
{
super(true, true);
}
private boolean newVersion = false;
@Override
public void run()
{
if (!newVersion)
{
if (plugin.getUpdateChecker().check())
if (plugin.getUpdateChecker().getUpdateStatusMessage(Bukkit.getConsoleSender(), false, 1))
{
newVersion = true;
}

View File

@ -1,13 +1,14 @@
package dev.plex.storage;
import com.mongodb.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.mapping.MapperOptions;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexLog;
public class MongoConnection extends PlexBase
{
@ -25,9 +26,22 @@ public class MongoConnection extends PlexBase
String password = plugin.config.getString("data.central.password");
String database = plugin.config.getString("data.central.db");
String connectionString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/?authSource=" + database;
String connectionString;
if (username != null && password != null && !username.isEmpty() && !password.isEmpty())
{
if (database != null && !database.isEmpty())
{
connectionString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/?authSource=" + database;
} else {
connectionString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/";
}
} else {
connectionString = "mongodb://" + host + ":" + port + "/";
}
connectionString += "?uuidRepresentation=STANDARD";
PlexLog.debug("Using mongo connection string: " + connectionString);
MongoClient client = MongoClients.create(connectionString);
Datastore datastore = Morphia.createDatastore(client, database, MapperOptions.DEFAULT);
Datastore datastore = Morphia.createDatastore(client, database == null ? "admin" : database, MapperOptions.DEFAULT);
datastore.getMapper().map(PlexPlayer.class);
datastore.ensureIndexes();
plugin.setStorageType(StorageType.MONGODB);

View File

@ -2,9 +2,8 @@ package dev.plex.storage;
import dev.plex.PlexBase;
import dev.plex.util.PlexLog;
import redis.clients.jedis.Jedis;
import java.util.function.Consumer;
import redis.clients.jedis.Jedis;
public class RedisConnection extends PlexBase
{
@ -32,7 +31,8 @@ public class RedisConnection extends PlexBase
public void runAsync(Consumer<Jedis> jedisConsumer)
{
new Thread(() -> {
new Thread(() ->
{
try (Jedis jedis = getJedis())
{
jedisConsumer.accept(jedis);

View File

@ -1,73 +1,114 @@
package dev.plex.storage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import dev.plex.Plex;
import dev.plex.PlexBase;
import lombok.Getter;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@Getter
public class SQLConnection extends PlexBase
{
private Connection connection;
private HikariDataSource dataSource;
public Connection getCon()
public SQLConnection()
{
if (!plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite") && !plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
{
return;
}
String host = plugin.config.getString("data.central.hostname");
int port = plugin.config.getInt("data.central.port");
String username = plugin.config.getString("data.central.user");
String password = plugin.config.getString("data.central.password");
String database = plugin.config.getString("data.central.db");
HikariConfig config = new HikariConfig();
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
this.dataSource = new HikariDataSource();
dataSource.setMaxLifetime(15000);
dataSource.setIdleTimeout(15000 * 2);
dataSource.setConnectionTimeout(15000 * 4);
dataSource.setMinimumIdle(2);
dataSource.setMaximumPoolSize(10);
try
{
if (plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite"))
{
connection = DriverManager.getConnection("jdbc:sqlite:" + new File(plugin.getDataFolder(), "database.db").getAbsolutePath());
dataSource.setJdbcUrl("jdbc:sqlite:" + new File(plugin.getDataFolder(), "database.db").getAbsolutePath());
plugin.setStorageType(StorageType.SQLITE);
}
else if (plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
} else if (plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
{
Class.forName("org.mariadb.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mariadb://" + host + ":" + port + "/" + database, username, password);
dataSource.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + database);
dataSource.setUsername(username);
dataSource.setPassword(password);
Plex.get().setStorageType(StorageType.MARIADB);
}
}
catch (SQLException | ClassNotFoundException throwables)
} catch (ClassNotFoundException throwables)
{
throwables.printStackTrace();
}
try
try (Connection con = getCon())
{
if (connection != null)
{
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
con.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
"`uuid` VARCHAR(46) NOT NULL, " +
"`name` VARCHAR(18), " +
"`login_msg` VARCHAR(70), " +
"`prefix` VARCHAR(45), " +
"`login_msg` VARCHAR(2000), " +
"`prefix` VARCHAR(2000), " +
"`rank` VARCHAR(20), " +
"`adminActive` BOOLEAN," +
"`ips` VARCHAR(2000), " +
"`coins` BIGINT, " +
"`vanished` BOOLEAN, " +
"`commandspy` BOOLEAN, " +
"PRIMARY KEY (`uuid`));").execute();
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `bans` (" +
"`banID` VARCHAR(46), " +
"`uuid` VARCHAR(46) NOT NULL, " +
"`banner` VARCHAR(46), " +
con.prepareStatement("CREATE TABLE IF NOT EXISTS `punishments` (" +
"`punished` VARCHAR(46) NOT NULL, " +
"`punisher` VARCHAR(46), " +
"`punishedUsername` VARCHAR(16), " +
"`ip` VARCHAR(2000), " +
"`reason` VARCHAR(256), " +
"`enddate` BIGINT, " +
"`type` VARCHAR(30), " +
"`reason` VARCHAR(2000), " +
"`customTime` BOOLEAN, " +
"`active` BOOLEAN, " +
"PRIMARY KEY (`banID`)" +
"`endDate` BIGINT" +
");").execute();
}
}
catch (SQLException throwables)
con.prepareStatement("CREATE TABLE IF NOT EXISTS `notes` (" +
"`id` INT NOT NULL, " +
"`uuid` VARCHAR(46) NOT NULL, " +
"`written_by` VARCHAR(46), " +
"`note` VARCHAR(2000), " +
"`timestamp` BIGINT" +
");").execute();
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
return connection;
}
public Connection getCon()
{
if (this.dataSource == null)
{
return null;
}
try
{
return dataSource.getConnection();
} catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
}

View File

@ -1,13 +1,13 @@
package dev.plex.util;
import dev.plex.PlexBase;
import dev.plex.Plex;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
public class PlexLog extends PlexBase
public class PlexLog
{
private static final boolean debugEnabled = plugin.config.getBoolean("debug");
public static void log(String message, Object... strings)
{
for (int i = 0; i < strings.length; i++)
@ -20,6 +20,11 @@ public class PlexLog extends PlexBase
Bukkit.getConsoleSender().sendMessage(String.format(ChatColor.YELLOW + "[Plex] " + ChatColor.GRAY + "%s", message));
}
public static void log(Component component)
{
Bukkit.getConsoleSender().sendMessage(Component.text("[Plex] ").color(NamedTextColor.YELLOW).append(component).colorIfAbsent(NamedTextColor.GRAY));
}
public static void error(String message, Object... strings)
{
for (int i = 0; i < strings.length; i++)
@ -41,7 +46,7 @@ public class PlexLog extends PlexBase
message = message.replace("{" + i + "}", strings[i].toString());
}
}
if (debugEnabled)
if (Plex.get().config.getBoolean("debug"))
{
Bukkit.getConsoleSender().sendMessage(String.format(ChatColor.DARK_PURPLE + "[Plex Debug] " + ChatColor.GOLD + "%s", message));
}

View File

@ -1,39 +1,16 @@
package dev.plex.util;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.config.Config;
import dev.plex.storage.StorageType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.entity.Player;
@ -42,6 +19,20 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class PlexUtils extends PlexBase
{
private static final Random RANDOM;
@ -59,7 +50,9 @@ public class PlexUtils extends PlexBase
public static List<ChatColor> CHAT_COLOR_POOL;
public static List<String> DEVELOPERS =
Arrays.asList("78408086-1991-4c33-a571-d8fa325465b2", // Telesphoreo
"f5cd54c4-3a24-4213-9a56-c06c49594dff" // Taahh
"f5cd54c4-3a24-4213-9a56-c06c49594dff", // Taahh
"ca83b658-c03b-4106-9edc-72f70a80656d", // ayunami2000
"2e06e049-24c8-42e4-8bcf-d35372af31e6" //Fleek
);
static
@ -73,6 +66,23 @@ public class PlexUtils extends PlexBase
}
}
public static void disabledEffect(Player player, Location location)
{
Particle.CLOUD.builder().location(location).receivers(player).extra(0).offset(0.5, 0.5, 0.5).count(5).spawn();
Particle.FLAME.builder().location(location).receivers(player).extra(0).offset(0.5, 0.5, 0.5).count(3).spawn();
Particle.SOUL_FIRE_FLAME.builder().location(location).receivers(player).offset(0.5, 0.5, 0.5).extra(0).count(2).spawn();
player.playSound(location, org.bukkit.Sound.BLOCK_FIRE_EXTINGUISH, 0.5f, 0.5f);
}
public static void disabledEffectMultiple(Player[] players, Location location)
{
Particle.CLOUD.builder().location(location).receivers(players).extra(0).offset(0.5, 0.5, 0.5).count(5).spawn();
Particle.FLAME.builder().location(location).receivers(players).extra(0).offset(0.5, 0.5, 0.5).count(3).spawn();
Particle.SOUL_FIRE_FLAME.builder().location(location).receivers(players).offset(0.5, 0.5, 0.5).extra(0).count(2).spawn();
// note that the sound is played to everyone who is close enough to hear it
players[0].getWorld().playSound(location, org.bukkit.Sound.BLOCK_FIRE_EXTINGUISH, 0.5f, 0.5f);
}
public static ChatColor randomChatColor()
{
return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size()));
@ -80,7 +90,9 @@ public class PlexUtils extends PlexBase
public static void testConnections()
{
if (Plex.get().getSqlConnection().getCon() != null)
if (Plex.get().getSqlConnection().getDataSource() != null)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
if (Plex.get().getStorageType() == StorageType.MARIADB)
{
@ -90,19 +102,23 @@ public class PlexUtils extends PlexBase
{
PlexLog.log("Successfully enabled SQLite!");
}
try
}
catch (SQLException e)
{
Plex.get().getSqlConnection().getCon().close();
}
catch (SQLException ignored)
{
}
}
else if (Plex.get().getMongoConnection().getDatastore() != null)
if (Plex.get().getMongoConnection().getDatastore() != null)
{
PlexLog.log("Successfully enabled MongoDB!");
}
}
}
else
{
if (Plex.get().getMongoConnection().getDatastore() != null)
{
PlexLog.log("Successfully enabled MongoDB!");
}
}
}
public static boolean isPluginCMD(String cmd, String pluginName)
{
@ -131,7 +147,7 @@ public class PlexUtils extends PlexBase
public static Component messageComponent(String entry, Object... objects)
{
return MiniMessage.miniMessage().parse(LegacyComponentSerializer.legacySection().serialize(LegacyComponentSerializer.legacyAmpersand().deserialize(messageString(entry, objects))));
return MiniMessage.miniMessage().deserialize(messageString(entry, objects));
}
public static String messageString(String entry, Object... objects)
@ -141,9 +157,9 @@ public class PlexUtils extends PlexBase
{
throw new NullPointerException();
}
for (Object object : objects)
for (int i = 0; i < objects.length; i++)
{
f = f.replaceFirst("<v>", String.valueOf(object));
f = f.replace("{" + i + "}", String.valueOf(objects[i]));
}
return f;
}
@ -234,9 +250,23 @@ public class PlexUtils extends PlexBase
}
}
public static <T> void commitGameRules(World world)
public static <T> void commitGlobalGameRules(World world)
{
for (String s : Plex.get().config.getStringList("global_gamerules"))
{
readGameRules(world, s);
}
}
public static <T> void commitSpecificGameRules(World world)
{
for (String s : Plex.get().config.getStringList("worlds." + world.getName().toLowerCase(Locale.ROOT) + ".gameRules"))
{
readGameRules(world, s);
}
}
private static <T> void readGameRules(World world, String s)
{
String gameRule = s.split(";")[0];
T value = (T)s.split(";")[1];
@ -251,11 +281,9 @@ public class PlexUtils extends PlexBase
PlexLog.error(String.format("Failed to set game rule %s for world %s with value %s!", gameRule, world.getName().toLowerCase(Locale.ROOT), value));
}
}
}
public static <T> Object check(T value)
{
if (value.toString().equalsIgnoreCase("true") || value.toString().equalsIgnoreCase("false"))
{
return Boolean.parseBoolean(value.toString());
@ -320,6 +348,55 @@ public class PlexUtils extends PlexBase
return UUID.fromString(uuidString);
}
@SuppressWarnings("UnstableApiUsage")
public static Set<Class<?>> getClassesFrom(String packageName)
{
Set<Class<?>> classes = new HashSet<>();
try
{
ClassPath path = ClassPath.from(Plex.class.getClassLoader());
ImmutableSet<ClassPath.ClassInfo> infoSet = path.getTopLevelClasses(packageName);
infoSet.forEach(info ->
{
try
{
Class<?> clazz = Class.forName(info.getName());
classes.add(clazz);
}
catch (ClassNotFoundException ex)
{
PlexLog.error("Unable to find class " + info.getName() + " in " + packageName);
}
});
}
catch (IOException ex)
{
PlexLog.error("Something went wrong while fetching classes from " + packageName);
throw new RuntimeException(ex);
}
return Collections.unmodifiableSet(classes);
}
@SuppressWarnings("unchecked")
public static <T> Set<Class<? extends T>> getClassesBySubType(String packageName, Class<T> subType)
{
Set<Class<?>> loadedClasses = getClassesFrom(packageName);
Set<Class<? extends T>> classes = new HashSet<>();
loadedClasses.forEach(clazz ->
{
if (clazz.getSuperclass() == subType || Arrays.asList(clazz.getInterfaces()).contains(subType))
{
classes.add((Class<? extends T>)clazz);
}
});
return Collections.unmodifiableSet(classes);
}
public static boolean randomBoolean()
{
return ThreadLocalRandom.current().nextBoolean();
}
public static int randomNum()
{
return ThreadLocalRandom.current().nextInt();

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