388 Commits
1.0 ... 1.4

Author SHA1 Message Date
5a1436afae Release Plex v1.4 2024-06-14 20:29:08 -05:00
e066d9b3a1 Implemented the ability to toggle pvp (#97)
* Implemented the ability to toggle pvp

* Changed listener to  PrePlayerAttackEntityEvent

* ... Updated the formatting so I don't get screamed at !

* _
2024-06-04 10:30:34 -05:00
9e974ae737 Add a /tempmute command (#96)
* Update WhoHasCMD.java

Added functionality that clears all players with a specified item

* Added functionality that clears all players with a specified item

* Altered tab completion to include "clear" argument

* Update WhoHasCMD.java

* Implemented a mob limiter that can be configured via a command

* Fixed some imports

* Refined tab complete

* Implemented reviewed changes

* Added a /tempmute command

* Removed unnecessary imports & simplified the reason assignment

* Fixed the usage for the moblimit command

---------

Co-authored-by: Telesphoreo <me@telesphoreo.me>
2024-06-04 09:23:51 -05:00
23611e218b Implemented a moblimiter (#95)
* Update WhoHasCMD.java

Added functionality that clears all players with a specified item

* Added functionality that clears all players with a specified item

* Altered tab completion to include "clear" argument

* Update WhoHasCMD.java

* Implemented a mob limiter that can be configured via a command

* Fixed some imports

* Refined tab complete

* Implemented reviewed changes

---------

Co-authored-by: Telesphoreo <me@telesphoreo.me>
2024-05-31 15:41:14 -05:00
5f12a1532f Add vanish filtering to list 2024-05-31 15:38:56 -05:00
fff35ad34c fix -rb showing in ban message 2024-05-26 13:35:35 -05:00
83ec997125 Merge pull request #90 from Deauthorized/messagesincursion
Move most hard coded messages to messages.yml to allow customization.
2024-05-09 17:09:37 -06:00
2ed88da151 Merge branch 'master' into messagesincursion 2024-05-09 17:06:13 -06:00
c5b356e45a fix merge conflict for hopefully the last time 2024-05-06 15:51:04 -04:00
58fe304118 oops oops oops 2024-05-06 12:40:29 -07:00
50d969975c fix merge conflict 2024-05-06 15:37:56 -04:00
52cc738d4d fix merge conflict 2024-05-06 15:34:18 -04:00
fd19d8417c add banlist to plex instead of having it in tfm extras 2024-05-06 12:31:07 -07:00
efcb9b45df oh update usage too 2024-05-06 12:29:30 -07:00
a5d77036a9 closes #91
add rollback only if -rb is specified
2024-05-06 12:26:21 -07:00
5c609b3d8f Since this'll be a problem for some reason I'm restoring the original message 2024-05-04 05:19:41 -04:00
7383e0d9bb Update BanService.java 2024-05-04 02:46:07 -04:00
f1680174ae Update DebugCMD.java 2024-05-04 02:45:39 -04:00
c0966a0f5e Update messages.yml 2024-05-04 02:44:53 -04:00
fa1a8a91ba add jenkins webhook for tf 2024-05-03 14:54:04 -07:00
129ef7b6bf Remind me to read the documentation next time... coreprotect is supposed to be called asynchronously lol 2024-05-03 14:41:12 -07:00
d7ad94d270 overrwrote the wrong file :( 2024-05-02 17:43:06 -04:00
a0471e63f6 Update WorldListener.java 2024-05-02 17:42:33 -04:00
e2b3488aa7 Update ServerListener.java 2024-05-02 17:31:33 -04:00
5b3a37835a Update PlayerListener.java 2024-05-02 17:30:22 -04:00
344df2b225 Update AntiSpamListener.java 2024-05-02 17:29:38 -04:00
6e5f0d7beb Update AntiNukerListener.java 2024-05-02 17:29:24 -04:00
0c7b280aef Update TempbanCMD.java 2024-05-02 17:28:34 -04:00
647f17b5bd Update SmiteCMD.java 2024-05-02 17:27:47 -04:00
773f320cb6 Update NotesCMD.java 2024-05-02 17:27:17 -04:00
8f55be369f Update ListCMD.java 2024-05-02 17:26:20 -04:00
5a7a2c1835 Update KickCMD.java 2024-05-02 17:25:49 -04:00
bc163aa51a Update EntityWipeCMD.java 2024-05-02 17:25:26 -04:00
5040c76dc6 Update BcastLoginMessageCMD.java 2024-05-02 17:24:49 -04:00
7d94717de5 Update BanCMD.java 2024-05-02 17:23:37 -04:00
0add60322e Update messages.yml 2024-05-02 17:22:05 -04:00
068dd28fd4 Temporary fix for displaying login messages on join 2024-04-28 12:52:21 -05:00
357683a0f6 Add a toggle option for toggling chat (#89)
* Add moderated mode toggle option

* Add new messages to messages.yml for modmode toggle

* Add block_on_modmode list for commands to block, should be separate from block_on_mute so pms can still work

* Implement the restricted chat toggle

* Add the restricted chat toggle to the toggle gui

* Add the restricted chat toggle to the consoles version of the command as well

* Update toggles.yml / requested changes

* Update messages.yml / requested changes

* Update commands.yml / requested changes

* Update ToggleMenu.java / requested changes

* Update TogglesListener.java / requested changes

* Update ToggleCMD.java / requested changes

* Update messages.yml / requested changes

* Update ToggleMenu.java / requested changes

* Update ToggleCMD.java / requested changes
2024-04-28 12:04:18 -05:00
315e16488b adds support for vanish plugins 2024-04-27 22:24:03 -05:00
85605774cf fix mute & freeze not staying after relog
add configurable timers for mute and freeze
2024-03-23 08:14:36 -07:00
54015f668a Fixes NPE if Prism or CoreProtect are not installed (#87) 2024-03-02 15:38:49 -06:00
532e82472b Added functionality that clears all players with a specified item (#82)
* Update WhoHasCMD.java

Added functionality that clears all players with a specified item

* Added functionality that clears all players with a specified item

* Altered tab completion to include "clear" argument

* Update WhoHasCMD.java

---------

Co-authored-by: Telesphoreo <me@telesphoreo.me>
2024-02-04 13:35:11 -06:00
6ce4843829 Minor fix 2024-01-27 15:56:40 -06:00
7298c8669a Attempt to fix bans not working 2024-01-27 15:48:21 -06:00
6b7c076c41 Revert "Add BroadcastEvent"
This reverts commit aab5083f78.
2024-01-26 17:13:11 -06:00
7b56bd70e9 Revert "attempt to add discordsrv"
This reverts commit 912dff0ec9.
2024-01-26 17:13:08 -06:00
fbd36161d4 Better legacy component support, removes SignListener (#81)
* Better legacy component support, removes SignListener

* Removes unused imports
2024-01-26 17:12:17 -06:00
912dff0ec9 attempt to add discordsrv 2024-01-25 17:44:47 -06:00
aab5083f78 Add BroadcastEvent 2024-01-25 17:00:59 -06:00
adb0d070a4 Update Jetty 2024-01-25 15:56:45 -06:00
e22f079062 Tab completion improvements to ban command 2024-01-23 19:58:15 -06:00
8f713fd30c uncomment prism support 2024-01-23 19:52:03 -06:00
72467de5ce Tab completer improvements (#80)
* Attempt to improve the tab completion for Plex

* i give up for the night

* steven is a god

* Fix permission node
2024-01-20 11:32:24 -06:00
c9d954d1c0 reformat 2024-01-19 22:30:26 -06:00
b168029df1 Fixed /mp and it now has the ability to purge one or all mobs + tab completion. (#79)
* Added a tab completion to /mp because our genius Plex devs forgot to. Its shitty but works lmao

* Rewrote /mp to actually work with or without args so now specific or all mobs can be purged, instead of just all mobs being purged. Why the REAL plex developers didn't include this (yet they did for /rd) defies any sort of logic.

* Tweaked the command a bit. It works as it should now.

* Tweaked the command a bit. It works as it should now.
2024-01-19 22:29:00 -06:00
f34df4f296 Add IP Banning by getting every IP punishment through SQL and checking if it's the same IP, if it's a ban / tempban, and if it's active
Make the ban command add the most recent IP used by a PlexPlayer if the player being banned is not online, else use online player's IP
2024-01-16 22:23:31 -08:00
79206d9354 (broken) ip bans 2024-01-16 21:03:50 -06:00
7bca348587 Show the same treatment for tempbans 2024-01-15 15:45:00 -08:00
b35bf63ba4 Add coreprotect support, start on prism but commented out until they figure out a maven repository for their API 2024-01-15 15:39:57 -08:00
8c5c058292 Allow Prism to work with Plex 2024-01-15 13:18:24 -06:00
3d70100119 Yes, there is 2023-12-02 01:17:27 -06:00
6a8228947b Switch to indra git 2023-12-01 23:52:07 -06:00
187226ff45 Add build number back for local builds
I couldn't find a more efficient way to do this
2023-12-01 23:43:27 -06:00
6d80d5f4e3 Revamp the build system 2023-12-01 21:46:20 -06:00
d4710f1808 Make this more friendly 2023-11-29 15:32:03 -06:00
bee4268d51 Revert radius to distanceSquared 2023-11-27 20:38:39 +11:00
7254097ae4 Update naming convention 2023-11-26 00:31:13 -06:00
20765403f4 Update dependencies 2023-11-26 00:04:40 -06:00
9650685796 you saw NOTHING 2023-11-25 23:47:01 -06:00
1cf262ff91 Add radius to entitywipe command (#74)
* currently bugged

* Fixed radius not working

---------

Co-authored-by: Focusvity <nathan.curran10012@gmail.com>
2023-11-25 23:43:27 -06:00
4de796781d Fixed tab colors not working 2023-11-22 20:39:56 -06:00
b82747b0bf Change it for books too just in case 2023-11-20 16:59:32 -06:00
029cd40124 Fixes #73 2023-11-20 16:28:06 -06:00
360775bac3 Fixes /punishments [player] not actually working 2023-11-07 04:39:54 -07:00
37ac71b6ee Fixes spawn egg bypass
Literally a one-line fix. Bruh
2023-11-07 03:41:24 -07:00
88f10ef9cc Fix more SQL 2023-10-29 23:07:36 -05:00
3608e8e825 [Breaking] Remove rank stuff from database 2023-10-29 23:00:12 -05:00
3e9be76aa2 Move these to the top 2023-09-02 10:15:34 -07:00
2364ab33ff Overhaul menu system and simplify it heavily, separating Pageable Menus and regular Menus into two different implementations 2023-09-02 10:14:10 -07:00
28c57f3a52 this is quite literally the most awful thing i have ever done 2023-08-31 20:20:18 -05:00
5929fd9ddc Bugfixes with the punishments menu 2023-08-31 04:02:01 -06:00
14d859ef75 Merge remote-tracking branch 'origin/master' 2023-08-31 02:48:15 -07:00
bc8c89449e Remove WebUtils, MojangUtils, and ashcon and replace references of WebUtils with DataUtils#getPlayer(String username) 2023-08-31 02:48:02 -07:00
709ed50748 Merge pull request #67 from plexusorg/whohas-command
Adds /whohas command
2023-08-31 02:32:15 -07:00
cc9967f9c2 make bans and kicks not take too long 2023-08-31 02:18:11 -07:00
b0c19a14ab Removed unused import 2023-08-31 02:11:12 -06:00
475169b36a Adds /whohas command 2023-08-31 02:09:07 -06:00
bb019abd89 Merge pull request #65 from plexusorg/no-nh
Removes /namehistory
2023-08-30 18:13:13 -07:00
a7ed86549d fix prefix for developers 2023-08-30 18:12:15 -07:00
ba23129b15 Removes /nh 2023-08-30 13:11:35 -06:00
c51d8da5b7 fix prefixes 2023-08-29 20:41:15 -07:00
2a2152603b Attempt to add prefixes to adminchat 2023-08-29 16:06:16 -05:00
2c7440804c Change URL 2023-08-29 15:46:35 -05:00
b7db18284a Remove rank references 2023-08-29 15:46:21 -05:00
91e09d982d Merge pull request #64 from plexusorg/nomongo
mongo changes
2023-08-28 18:51:13 -05:00
15b12e6299 make our chat handler come first 2023-08-28 04:35:32 -07:00
4b37497a14 Merge branch 'nomongo' of https://github.com/plexusorg/plex 2023-08-26 06:59:46 -07:00
b0a8b463cb Add SQL Generators
Add cache for table strings generated
Add legacy support for Tags and login messages by converting legacy color codes to minimessage tags
2023-08-26 06:59:29 -07:00
1f48dc1e60 Merge remote-tracking branch 'origin/master' 2023-08-26 06:19:30 -07:00
95c4da338e Merge pull request #63 from plexusorg/fix/use-legacy-colour-codes-in-signs
Use legacy colour codes in signs
2023-08-26 06:19:24 -07:00
cea84884fc Merge remote-tracking branch 'origin/master' 2023-08-26 06:18:54 -07:00
Eva
2331cb9f80 Fix string sanitising (#62) 2023-08-25 17:21:55 -05:00
e4f18a24cc Properly cancel block explosions (#59) 2023-08-25 17:21:55 -05:00
Eva
668460f486 Fix string sanitising (#62) 2023-08-25 23:03:37 +01:00
7336cc8feb Use legacy colour codes in signs 2023-08-25 22:48:33 +01:00
bc5d0476ee Properly cancel block explosions (#59) 2023-08-25 10:23:24 -05:00
7ff6bdb171 Remove rank system entirely and move developer title to being hardcoded 2023-08-25 04:07:56 -07:00
175c7db23d Bump the version to 1.4-SNAPSHOT
Remove every trace of MongoDB
Fix issue where notes were not being notified on a permissions based system
2023-08-25 01:30:41 -07:00
f97411ce09 Cache whether the server is on a proxy or not
Fix kick where ban message was displayed instead of kick message
2023-08-24 22:36:14 -07:00
b0240ef46e Remove extra space from prefixes 2023-08-24 21:24:14 -07:00
4887960463 This is supposed to be if it is not empty 2023-08-24 19:08:30 -07:00
295e16b6c5 This is supposed to be empty by default not null 2023-08-24 15:36:49 -07:00
72d9e0817c Merge remote-tracking branch 'origin/master' 2023-08-24 15:36:07 -07:00
28ec8e1d2d Add support for reasons 2023-08-24 15:35:59 -07:00
9d0e7bf6d6 Fix compile error 2023-08-24 15:52:51 -05:00
96b0c81fed Back to snapshot 2023-08-24 15:50:12 -05:00
7dea0bcb72 Make sure the TNT is removed 2023-08-24 02:41:57 -07:00
8344e3596e Remove checkTab and replace with silentCheckRank
add isCancelled checks for MobListener
Modify the plugin's YAML file to load before essentials
Modify the world command to support the TFM Extras module
Add more checks in WorldListener to prevent spawning entities and interacting with anything except openable things (doors, trapdoors, gates)
2023-08-24 02:40:52 -07:00
37a649fa7a This should teleport players to the world spawn 2023-08-23 19:44:27 -07:00
d7df923e5c Allow someone to modify the event before the renderer is set. This allows someone to edit the message before processing 2023-08-23 19:34:01 -07:00
d54325304e Fixes vulnerability related to command blocking in rank-based systems (#58)
Video contributing to Plex finally???
2023-08-23 15:23:30 -05:00
bc6dbb1052 Add bypass for command blocking and definite bans 2023-08-22 14:37:45 -07:00
ecbd9c02da Release Plex v1.3 2023-07-22 20:00:25 -05:00
77dc95ae29 Add Folia support minus world generation 2023-07-21 20:01:59 -05:00
91a1b1cfff Remove publishing block 2023-07-10 22:58:51 -05:00
0c6091f06a Convert Plex to a paper plugin 2023-07-10 21:43:21 -05:00
ffbad7928a Update dependencies 2023-06-08 15:25:25 -05:00
7caa89539d Update Gradle and dependencies 2023-04-29 15:06:46 -05:00
ceb9a83eda Update Gradle and dependencies 2023-03-15 21:45:34 -05:00
a62bdef5b4 Add response HTTP status code check to update checker to improve efficiency 2023-03-09 17:16:14 +11:00
37649f1fdc Closes #55 2023-03-08 19:29:30 -06:00
ea512487ac Reformat 2023-03-08 14:26:10 -06:00
41b0076f8f Make the list command work with the permission system 2023-03-08 14:23:10 -06:00
00b6473e4d Let's actually remove these files 2023-03-08 22:48:51 +11:00
77be23faf0 Minor clean up 2023-03-08 22:45:47 +11:00
e39f882ea7 Fix out of bounds exception - closes #54 2023-03-08 21:46:27 +11:00
344d890877 Block translate tag 2023-03-08 00:45:41 -06:00
2c8c6353c1 Update build.gradle 2023-03-08 00:29:14 -06:00
8fa05e3838 Update dependencies and Gradle 2023-03-02 23:06:37 -06:00
158ce52320 Fix links 2022-12-26 23:39:47 -06:00
1cc431621b Update README.md 2022-12-26 23:34:26 -06:00
b9c873beb3 Update dependencies 2022-11-27 22:14:27 -06:00
6e1fa15a6c Remove redundant <red> 2022-11-27 16:40:55 -06:00
c216bdc5a4 Add permission check for the -o flag on the login message commands 2022-11-26 04:31:43 -06:00
ed638679b2 Use cache for toggling commandspy 2022-11-26 04:24:52 -06:00
76952e33b8 Use PlexCommand instead of PlexUtils 2022-11-26 04:24:38 -06:00
f3f7daaafb Add customizable login messages 2022-11-26 04:24:12 -06:00
dbbaf4ab70 Update Gradle 2022-11-26 02:25:05 -06:00
1a10fdd481 Update Gradle 2022-09-13 02:08:35 -05:00
7565bb6fcf Back to snapshot 2022-08-25 21:18:53 -05:00
22199be335 Plex v1.2 2022-08-25 20:28:13 -05:00
2e077c40d2 lets see if its fixed 2022-08-25 19:06:18 -05:00
517b829420 Merge remote-tracking branch 'origin/master' 2022-08-02 17:03:24 -07:00
7fa26f9a64 add admin chat redis support 2022-08-02 17:03:04 -07:00
09846f1d33 Switch to Component for CommandSpy 2022-08-02 18:57:12 -05:00
ed70a0ec8b Remove debug line 2022-08-02 17:29:39 -05:00
16e29b80a7 make getPlayer a function because mongo doesnt call constructors 2022-08-02 15:23:54 -07:00
829bb88959 Fix CI 2022-08-02 12:13:57 -05:00
d6b44863aa Remove the API component - closes #51 2022-08-02 22:08:52 +10:00
f806470fd5 Actually fix colors in nicknames
Co-Authored-By: Taahh <9047036+Taahh@users.noreply.github.com>
2022-08-01 23:38:18 -05:00
3611148b4c Remove non-ASCII characters from tags & chat messages (closes #48) 2022-08-02 03:23:08 +01:00
262af44193 Add run/ to .gitignore 2022-08-02 02:49:54 +01:00
a014a38e2f Check if array is empty in disabled effect (closes #50) 2022-08-02 02:48:25 +01:00
d896179f47 Block more tags 2022-08-01 19:36:43 -05:00
9dac0e799e Fix display name always being set in the config
Also, fix an unintentional double space
2022-08-01 19:23:57 -05:00
5c27fb00e7 Roll back to 7.4.2 2022-08-01 17:05:49 -05:00
679d8bcbc0 Attempt to update gradle again 2022-08-01 16:55:15 -05:00
46de6dba84 Update Gradle and plugins 2022-08-01 16:45:41 -05:00
d2649508b3 *sigh* 2022-07-30 19:26:26 -05:00
dd8e22b676 Ok 2022-07-27 23:22:45 -05:00
b26e489e83 Fix whitespace bypassing command blocker 2022-07-24 03:44:54 +01:00
5f64e02cae Fix NPE in PlexCommand 2022-07-24 01:12:30 +01:00
4a14f94158 Use ComponentLogger + update dependencies 2022-06-29 18:11:03 -05:00
6763e12d81 Back to snapshot 2022-06-14 00:17:19 -05:00
1d0fb85fa1 Remove maven local 2022-06-13 23:19:24 -05:00
665a2f4e72 Merge branch '1.19' 2022-06-13 23:18:39 -05:00
9c67911c1b Plex v1.1.1 2022-06-13 23:17:10 -05:00
f1ebbc3664 Fix incorrect permission 2022-06-09 21:12:19 -05:00
4aa3ae7c50 Update Blossom
(cherry picked from commit 08e2f31eae)
2022-06-08 17:21:35 -05:00
08e2f31eae Update Blossom 2022-06-08 17:20:44 -05:00
a1c009909d Lang to lang3 2022-06-08 15:09:42 -05:00
7d2c44975d Update for 1.19 2022-06-08 14:37:16 -05:00
b2faec70a9 oops 2022-06-08 14:33:04 -05:00
a0cca2aea5 Update codeql-analysis.yml 2022-06-08 14:32:09 -05:00
337334d403 Update gradle.yml 2022-06-08 14:30:23 -05:00
2e8fe8767e Update codeql-analysis.yml 2022-06-08 14:28:25 -05:00
dbdf720a9e Update workflow 2022-06-08 14:22:14 -05:00
5a9d6dd60d fix messages 2022-06-05 22:55:11 -05:00
84a9535123 ok so apparently this matters 2022-06-05 22:39:41 -05:00
41aff575d0 big think, it should be public 2022-06-05 22:34:16 -05:00
65b8188b37 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-06-05 22:27:25 -05:00
c8a35c8e0e Add the ability to add messages into Plex
Code originally from TFMExtras by taah
2022-06-05 22:27:24 -05:00
13acf7ba9d Properly disable explosions (#45)
* Remove unused import

* Properly disable explosions
2022-06-05 15:29:49 -05:00
5fe48cfd7f Allow toggling redstone 2022-06-04 22:48:18 -05:00
abf2aca0f2 Resolves #12 (major config changes)
Also allows more customization within the updater
2022-06-04 22:08:13 -05:00
dc4ac39fe4 Switch legacy to MiniMessage 2022-06-04 21:31:36 -05:00
1ae8e779b1 Merge pull request #44 from plexusorg/codeql-readme
Add CodeQL to the README.md
2022-06-01 01:56:58 -07:00
658f4a4b05 Add CodeQL to the README.md 2022-06-01 09:55:40 +01:00
7ccfb2ad27 Back to snapshot 2022-05-28 22:55:48 -05:00
942794b56c Version 1.1 2022-05-28 21:47:54 -05:00
7dc3ab1d6b Fix failing javadoc task 2022-05-28 21:17:53 -05:00
9f19bd14ca fix NPE and codec issues 2022-05-28 19:12:18 -07:00
d0b1d09f38 Minor improvements
- Add /toggles as an alias for /toggle
- We now use docs.plex.us.org again
2022-05-26 00:31:37 -05:00
53cd4b1306 Be more specific with the command blocker 2022-05-25 23:10:20 -05:00
d785ef31c8 CommandSpy now works with permissions 2022-05-25 22:16:31 -05:00
97117c0e97 Update repo 2022-05-21 20:49:34 -05:00
885f6196e8 Reformat and reduce complexity 2022-05-20 15:44:25 -05:00
9b0f928386 Fix (some) MongoDB errors
Co-Authored-By: taahanis <6778012+taahanis@users.noreply.github.com>
2022-05-19 22:22:31 -05:00
0bbe2d06f6 Fix mute not having a permissions check 2022-05-19 21:12:52 -05:00
ff16347981 Some improvements to the messages 2022-05-19 21:07:38 -05:00
b39ba8ed86 Resolves #33 2022-05-19 20:34:43 -05:00
f97649083a Fix errors 2022-05-19 16:32:31 -05:00
4d77d514fd Begin work on toggles 2022-05-19 16:11:45 -05:00
92c07f89fe i prefer this 2022-05-19 13:59:16 -05:00
a775d258e9 Make sure playerCache variable is initalised on enable 2022-05-18 20:40:29 +10:00
7efa151157 A bit more work on the API 2022-05-18 20:31:15 +10:00
7fe28ae8cb Update CONTRIBUTING.md 2022-05-17 14:36:01 -05:00
ce9b70bc98 Make getNonNullPlayer work with UUIDs too (#43)
* Make getNonNullPlayer work with UUIDs too

* allman
2022-05-17 12:24:58 -05:00
079ea1050e Set correct version for Velocity 2022-05-16 22:52:52 -05:00
1190c612b3 Allow console to run plex update 2022-05-13 17:43:42 -05:00
f8e019dd69 Update Jenkinsfile 2022-05-12 22:53:21 -05:00
8ab337d0a6 Allow server owners to use plex update 2022-05-12 22:45:17 -05:00
ebfba89994 check if rsp is null 2022-05-10 23:06:56 -07:00
b78f71c238 make vault optional and automatically enable if a server is using vault 2022-05-10 22:48:47 -07:00
bb8c34e0cd Format 2022-05-10 00:08:45 -05:00
770fe65f98 Reduce code duplication 2022-05-10 00:00:48 -05:00
9284ec3409 add plugin messaging to proxies for kicking players 2022-05-09 18:05:31 -07:00
7d709319c6 oops 2022-05-08 17:59:01 -07:00
0f76222f90 add option to load extra data when retrieving by username 2022-05-08 17:56:06 -07:00
9557737915 add messageComponent that takes a component parameter 2022-05-07 17:37:47 -07:00
5e1475dfb5 add messageComponent that takes a component parameter 2022-05-07 17:34:41 -07:00
884a4ed1ec remove missing javadoc parameter 2022-05-07 17:23:23 -07:00
ae098410c1 Merge remote-tracking branch 'origin/master' 2022-05-07 17:13:17 -07:00
abaf3ff980 remove missing javadoc parameter 2022-05-07 17:13:03 -07:00
b65c1ccd6d Don't allow events in books 2022-05-08 01:12:47 +01:00
4450427d4e add the ability to override the chat
safe serialize minimessage methods
2022-05-07 17:11:19 -07:00
6c4903c3fe Adds a connection listener to proxy module 2022-05-07 01:25:23 -05:00
fd50589331 Allow not setting permissions 2022-05-06 16:58:56 -05:00
74faaf2d74 Add Darthfish command. (#40)
* Add Darthfish command.

* You can't simpy do that.

You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that. You can't simpy do that.

* It's not about credit or discredit

It's about copyright of TFM.

Co-authored-by: Business Goose <arclicious@vivaldi.net>
Co-authored-by: Allink <44676012+allinkdev@users.noreply.github.com>
2022-05-06 14:25:36 -05:00
38b18e5867 add the ability to overide the chat 2022-05-05 21:27:32 -07:00
048518dc49 properly unregister module cmds 2022-05-05 19:13:47 -07:00
8fc2f74275 optionally register command 2022-05-05 18:54:08 -07:00
c9da0177ad add option to enable extra data such as punishments (default is yes) 2022-05-05 18:41:11 -07:00
b23b7c0c1b have modules enable last in onEnable 2022-05-05 17:30:37 -07:00
842f96678d Fix gradle file 2022-05-05 15:28:05 -05:00
24e031acae add gson serializedname support for toml 2022-05-05 01:12:24 -07:00
f52c8462ae actually indent array types in toml
add a default config file instead of generation for commenting purposes
add a random gradient placeholder and a converter for legacy colorcodes
2022-05-05 00:49:03 -07:00
4e9984f251 push gradle oops 2022-05-04 23:38:23 -07:00
457b6f4124 Resolves #17 2022-05-04 18:23:04 -05:00
9d5794dcfd Merge pull request #38 from plexusorg/player-mm
More Player MiniMessage & prefix handling improvement
2022-05-04 12:45:31 -05:00
0e3eeaeac3 Allow books and signs to use SafeMiniMessage 2022-05-04 17:40:58 +01:00
45b338fd9b Make a safe mini message class with a custom tag resolver 2022-05-04 17:08:35 +01:00
3604add18a Add getting text from component to PlexUtils 2022-05-04 16:30:37 +01:00
d716f77ac0 Use a variable for the chat component & if they have a prefix, append the prefix to that variable instead of using else if 2022-05-04 16:08:52 +01:00
cbbdb0248f Allow players to use MiniMessage 2022-05-04 16:04:52 +01:00
84edae26f5 Disable proxy from building from the root project since it's incomplete 2022-05-04 15:52:27 +01:00
8592978be2 Use PlexUtils.mmDeserialize instead of MiniMessage.miniMessage().deserialize in ChatListener 2022-05-04 15:50:37 +01:00
7d0f3618c9 move this back 2022-05-04 05:20:29 -07:00
a24aa6a962 move this back 2022-05-04 05:19:34 -07:00
de13860741 Merge remote-tracking branch 'origin/master' 2022-05-04 05:18:50 -07:00
b072e49d85 modify toml4j fork to automatically add new fields without overwriting previous ones and setup motd 2022-05-04 05:18:07 -07:00
c80b6c9ff9 Merge pull request #37 from plexusorg/give-me-dev
Add me to dev list (I am epic)
2022-05-04 01:17:28 -05:00
303f81d5cd Add me to dev list (I am epic) 2022-05-04 07:13:43 +01:00
6756f2db76 Merge pull request #36 from allinkdev/bugs
Fix bugs
2022-05-02 12:58:37 -05:00
0af3603354 Spawn dispenser mobs the same way Bukkit does, closes #18 2022-05-02 08:38:11 +01:00
63fcd3a2b1 Use replaceText to replace URLs with correct components for them (closes #34) 2022-05-02 07:35:22 +01:00
e484130d84 Cancel PlayerTeleportEvent for frozen players (closes #31) 2022-05-02 06:08:30 +01:00
d55de3b4a8 Update dependencies 2022-04-25 19:07:55 -05:00
2bc943b4c8 make chat listener not parse events 2022-04-24 16:31:26 -07:00
bc3893e2db add this back 2022-04-24 15:35:48 -05:00
6352975825 Oops 2022-04-24 13:10:46 -05:00
c665524078 Fix lockup 2022-04-24 01:21:19 -05:00
dd661a7304 Fix commandspy 2022-04-24 01:12:24 -05:00
d699f6de02 i hate essentials 2022-04-24 01:05:21 -05:00
07bc28fc48 override essentials 2022-04-24 00:58:36 -05:00
bfdce97271 just so i dont have to update the documentation lol 2022-04-24 00:43:54 -05:00
5fd22ba582 Fix publishing 2022-04-24 00:01:19 -05:00
ead38212d5 publish both artifacts 2022-04-23 23:42:01 -05:00
36877ae2f2 Give the JARs nicer names 2022-04-23 23:35:37 -05:00
fbd3983c0b Update Jenkinsfile 2022-04-23 23:29:15 -05:00
44b07ec34f I hope this works 2022-04-23 23:25:38 -05:00
a9a8f80ee2 Actually push the gitignore change 2022-04-24 14:24:22 +10:00
c27ddc19a6 Remove build and actually add the folders to gitignore 2022-04-24 14:20:55 +10:00
2526e1750a Revert the codestyle back to original state 2022-04-24 14:16:58 +10:00
f9a577035b Move Plex to API-driven plugin and fix NoClassDefFoundError on startup 2022-04-24 14:16:14 +10:00
edeecb51f4 Add a proper gamemode command 2022-04-23 16:37:00 -05:00
8126caf184 ok it works 2022-04-23 13:39:44 -05:00
faab60a07e Test 2022-04-23 13:38:25 -05:00
922c3def81 Allow getting notes of offline players 2022-04-21 21:38:54 -05:00
ea834da575 Add customizable messages to notes
Also allows updating modules
2022-04-21 21:26:51 -05:00
6e4e634f59 Back to snapshot (again) 2022-04-21 17:20:39 -05:00
2cde4a430c Plex 1.0.3 2022-04-21 17:17:05 -05:00
c3a426d6db Back to snapshot 2022-04-20 22:07:31 -05:00
e662491198 Release 1.0.2 2022-04-20 21:34:53 -05:00
ec7e370a01 Fix it this time 2022-04-20 21:26:39 -05:00
ef957467ce set it back to 0 2022-04-20 20:40:28 -05:00
1a94c3e39f Not sure we need a nuker, paper is blocking it before Plex 2022-04-20 20:34:31 -05:00
b1fcf5e348 adds anti spam
likely needs tweaking
2022-04-20 19:46:06 -05:00
7c27c03d98 Resolves #20 2022-04-20 18:48:23 -05:00
cbf4004169 Add some defaults 2022-04-20 16:47:50 -05:00
57eab45b43 this is wip 2022-04-20 16:37:15 -05:00
4eeaf051ad i forgot supers username 💀 2022-04-19 21:16:19 -05:00
285514b04a Update RandomUtil.java 2022-04-19 17:39:40 -05:00
a00c6926c4 add tempban punishment type and swap localdatetime zoneddatetime, as well as reload timezone on /plex reload 2022-04-19 14:49:45 -07:00
bae1e49c5e Actually fix it 2022-04-19 15:58:38 -05:00
730f7c5ea0 it doesnt work 2022-04-19 15:49:21 -05:00
67a382695a Merge remote-tracking branch 'origin/master' 2022-04-19 13:34:15 -07:00
9600f2d5d9 add warning for querying plex players by ip when using sqlite 2022-04-19 13:33:58 -07:00
81200f73d1 Get rid of more ChatColor usage 2022-04-19 15:31:34 -05:00
ee18ae324d git 2022-04-19 15:20:39 -05:00
7d2a25668a Organize the util classes 2022-04-19 15:19:55 -05:00
98c487c639 add tempban punishment system and redo the way tempbans parse duration 2022-04-19 13:16:07 -07:00
953f1813d3 Add version back to jar 2022-04-18 17:11:24 -05:00
df02ad6771 broh 2022-04-17 00:27:04 -05:00
299aeae38e Update codeql-analysis.yml 2022-04-14 00:10:34 -05:00
f622e6c295 just wanna test this 2022-04-14 00:05:38 -05:00
5f93b7e1e5 Make it more clear 2022-04-13 23:20:11 -05:00
b41015bfd8 try this 2022-04-13 23:12:24 -05:00
14cd376f7e Create CONTRIBUTING.md 2022-04-13 20:03:22 -05:00
ce3758730f Back to snapshot 2022-04-12 21:46:06 -05:00
eb788f02dd Plex v1.0.1 2022-04-12 21:22:50 -05:00
096bb1bb24 Reformat 2022-04-12 21:22:17 -05:00
223eaf30b3 Code review 2022-04-12 21:20:56 -05:00
6763878d74 Readd code style 2022-04-12 21:10:41 -05:00
81c656c86e Tell admins if a player has notes 2022-04-12 21:08:12 -05:00
6c09905a8d Update build.gradle 2022-04-12 16:38:19 -05:00
f0c646688e Speed things up 2022-04-11 21:51:17 -05:00
336f17b1cf refactor packages and rename + add sql permission system + mongodb 2022-04-11 10:56:26 -07:00
583f502cee Merge remote-tracking branch 'origin/master' 2022-04-11 00:53:49 -07:00
c071195aaf fix punishments not being retrieved from sql 2022-04-11 00:53:09 -07:00
f62b084bbc Update settings.gradle 2022-04-11 00:17:13 -05:00
c92a4bbdb9 add jitpack for vault 2022-04-10 17:27:03 -07:00
9b0b7537c2 fix build.gradle publishing wrong artifact 2022-04-10 17:22:22 -07:00
f8d25491d5 add library dependencies to pom 2022-04-10 16:36:37 -07:00
1dc0e05715 Closes #26 2022-04-10 18:30:21 -05:00
ffe8993ee1 use packs's repository for plugin-yml 2022-04-10 15:39:58 -07:00
90ef0a2121 Merge branch 'master' of https://github.com/plexusorg/plex into taah-cmd-blocker 2022-04-10 15:30:23 -07:00
7457e9e454 wack 2022-04-10 17:27:46 -05:00
dc65187381 add /csay
make /say and /csay not parse minimessage messages
add a strip color function to strip a message of minimessage strings
2022-04-10 15:27:25 -07:00
b449d732b0 Merge branch 'master' of https://github.com/plexusorg/plex into taah-cmd-blocker
 Conflicts:
	src/main/java/dev/plex/command/blocker/CommandBlockerManager.java
	src/main/java/dev/plex/listener/impl/CommandListener.java
	src/main/resources/commands.yml
2022-04-10 15:03:32 -07:00
8dfaaf7a8c fix /tag
fix /notes
fix /rank
switch /admin to a datautils check instead of using ashcon api
2022-04-10 15:02:50 -07:00
6b7bfacbfd Update EntityWipeCMD.java 2022-04-10 17:01:02 -05:00
16186bdfbb Merge pull request #27 from ayunami2000/master
fix entitywipe not actually wiping entities
2022-04-10 17:00:18 -05:00
4bbb73d1ff Merge branch 'plexusorg:master' into master 2022-04-10 17:57:13 -04:00
aa9f306586 fix entitywipe not actually wiping entities 2022-04-10 17:56:15 -04:00
08a004d65f Merge pull request #22 from ayunami2000/master
cleanup & fix
2022-04-10 16:16:23 -05:00
d798904394 Update Plex.java 2022-04-10 13:33:49 -05:00
f78edc55d4 re remove debug logging
lmao
2022-04-10 14:23:34 -04:00
8866f44aa2 fix issue where matcher would match partial commands 2022-04-10 14:21:34 -04:00
0fc2aa68b0 remove separated color 2022-04-10 14:10:15 -04:00
391677596a i forgor 💀 2022-04-10 13:45:52 -04:00
5988eba06b cleanup & fix 2022-04-10 13:44:36 -04:00
81d3cc8dde add additional conditions for telnet users 2022-04-10 02:31:07 -07:00
7b13ca0248 update to gradle 7.4.2 and host a custom fork of the mincrell plugin for now 2022-04-10 01:32:33 -07:00
06fcf531af instead of checking if a command starts with the message, check if each argument of the command is equal to the message until you can't check anymore 2022-04-10 00:42:53 -07:00
9f7ac310d9 merge master branch and add ayunami's delimiter code, with of course, credit to him added in the code, and fix a bug 2022-04-10 00:25:14 -07:00
09bc47f3fb Merge branch 'master' into taah-cmd-blocker
# Conflicts:
#	src/main/java/dev/plex/Plex.java
#	src/main/java/dev/plex/listener/impl/CommandListener.java
#	src/main/java/dev/plex/services/impl/CommandBlockerService.java
#	src/main/resources/commands.yml
2022-04-10 00:04:06 -07:00
8544775be2 Delete build.properties 2022-04-10 01:56:05 -05:00
c8c8fc9c59 WTF 2022-04-10 01:55:20 -05:00
14095fdebb jkn 2022-04-10 01:54:55 -05:00
dcecebdc8d Revert API 2022-04-10 01:47:33 -05:00
f73c63f1e7 test 2022-04-10 00:46:17 -05:00
067094130f Lets try this again 2022-04-10 00:12:44 -05:00
d16aa6de4c Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Plex-Core/src/main/java/dev/plex/command/impl/SayCMD.java
2022-04-09 22:11:06 -07:00
6086f761eb add /say
fix /tag
2022-04-09 22:10:35 -07:00
b2f1f7e055 Remove ignored files 2022-04-10 00:01:46 -05:00
3c20213c0d oh boy 2022-04-10 00:01:15 -05:00
3500cae2da Oops lol 2022-04-09 23:58:03 -05:00
c4be024619 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-09 23:51:29 -05:00
9849003ecc API 👀 2022-04-09 23:51:27 -05:00
f274e20f84 sanitize minimessage + strip legacy colors 2022-04-09 23:24:44 -04:00
f180eec44a "OOPS!!" 2022-04-09 21:54:34 -04:00
b1ef89dae9 fix bug 2022-04-09 21:53:27 -04:00
de20747d45 Merge branch 'master' of https://github.com/plexusorg/Plex 2022-04-09 17:14:26 -04:00
c801feed6f fix special cases such as worldedit
all my homies hate worldedit
2022-04-09 17:13:47 -04:00
5fdc5826b7 Update README.md 2022-04-09 16:08:20 -05:00
a87a9241af optimize command blocker 2022-04-09 15:31:55 -04:00
8fb64b8499 :broh: 2022-04-09 00:27:49 -05:00
10dd546c09 Quick fix 2022-04-09 00:26:34 -05:00
5a352b2ca0 Set the jar name just to "Plex" 2022-04-09 00:14:36 -05:00
333f38fb64 Don't send empty line for list if there are no players 2022-04-09 00:09:54 -05:00
d55eaf0d3d A few more 2022-04-09 00:08:18 -05:00
e35d70bc3c Change config entries 2022-04-09 00:08:03 -05:00
e421867f63 Bump to snapshot 2022-04-09 00:05:06 -05:00
ec7d814467 Merge branch 'master' of https://github.com/plexusorg/Plex into taah-cmd-blocker 2022-04-08 18:56:57 -05:00
9c5a557316 switch statements look cleaner here 2022-04-08 00:32:53 -07:00
38e79fd917 add case insensitivity 2022-04-08 00:24:46 -07:00
10e63f5e86 - taah command blocker 2022-04-08 00:20:17 -07:00
286 changed files with 12382 additions and 6359 deletions

47
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,47 @@
name: "CodeQL"
on:
push:
branches: [ master, server ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '30 4 * * *'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
java: [ 17 ]
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: ${{ matrix.java }}
cache: gradle
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

View File

@ -1,18 +1,26 @@
name: Gradle
on: [ push ]
# Adapted from Paper's build script
name: Build
on: [ push, pull_request ]
jobs:
build:
# Only run on PRs if the source branch is on someone else's repo
if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}
runs-on: ubuntu-latest
strategy:
matrix:
java: [ 17 ]
fail-fast: true
steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v2
- uses: actions/checkout@v3
- name: JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 17
cache: gradle
- name: Build with Gradle
run: chmod a+x gradlew && ./gradlew build --no-daemon
java-version: ${{ matrix.java }}
cache: 'gradle'
distribution: 'temurin'
- name: Build
run: |
git config --global user.email "no-reply@github.com"
git config --global user.name "Github Actions"
./gradlew build --stacktrace

7
.gitignore vendored
View File

@ -1,8 +1,7 @@
/.idea/
/.idea/codeStyles/codeStyleConfig.xml
*.iml
/target/
/src/main/resources/build.properties
server/src/main/resources/build.properties
# OS
.DS_Store
@ -14,4 +13,8 @@ Thumbs.db
# Gradle
/build/
/*/build/
/.gradle/
# Common working directory
run/

20
.idea/codeStyles/Plexus_Code_Style.xml generated Normal file
View File

@ -0,0 +1,20 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Plexus Code Style" version="173">
<codeStyleSettings language="JAVA">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
<option name="BRACE_STYLE" value="2" />
<option name="CLASS_BRACE_STYLE" value="2" />
<option name="METHOD_BRACE_STYLE" value="2" />
<option name="LAMBDA_BRACE_STYLE" value="2" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="IF_BRACE_FORCE" value="3" />
<option name="DOWHILE_BRACE_FORCE" value="3" />
<option name="WHILE_BRACE_FORCE" value="3" />
<option name="FOR_BRACE_FORCE" value="3" />
</codeStyleSettings>
</code_scheme>
</component>

View File

@ -1,46 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="20" />
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="" withSubpackages="true" static="false" />
<package name="" withSubpackages="true" static="true" />
</value>
</option>
</JavaCodeStyleSettings>
<JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value>
<package name="java.util" alias="false" withSubpackages="false" />
<package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" />
<package name="io.ktor" alias="false" withSubpackages="true" />
</value>
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value>
<package name="" alias="false" withSubpackages="true" />
<package name="java" alias="false" withSubpackages="true" />
<package name="javax" alias="false" withSubpackages="true" />
<package name="kotlin" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value>
</option>
</JetCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="BRACE_STYLE" value="2" />
<option name="CLASS_BRACE_STYLE" value="2" />
<option name="METHOD_BRACE_STYLE" value="2" />
<option name="LAMBDA_BRACE_STYLE" value="2" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="SPACE_AFTER_TYPE_CAST" value="false" />
<option name="IF_BRACE_FORCE" value="3" />
<option name="DOWHILE_BRACE_FORCE" value="3" />
<option name="WHILE_BRACE_FORCE" value="3" />
<option name="FOR_BRACE_FORCE" value="3" />
</codeStyleSettings>
</code_scheme>
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Plexus Code Style" />
</state>
</component>

37
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,37 @@
For those who are wanting to contribute, we fully encourage doing so. There are a few rules we require following when
contributing.
## Steps
1. Make an issue and get feedback. It's important to know if your idea will be accepted before writing any code.
- If it is a feature request, describe the feature and be extremely specific.
- If it is a bug report, ensure you include how to reproduce the bug and the expected outcome
- If it is an enhancement, describe your proposed changes. Ensure you are extremely specific.
2. Fork this project
3. Create a new branch that describes the new feature, enhancement, or bug fix. For example, this is
good: `feature/add-xyz`. This is bad: `fix-this-lol`.
4. Write the code that addresses your change.
- Keep in mind that it **must** be formatted correctly. If you are using IntelliJ, there is a `codeStyle.xml` file that
tells IntelliJ how to format your code. Check this link for information on how to use the
file: https://www.jetbrains.com/help/idea/configuring-code-style.html#import-export-schemes
- If you are not using IntelliJ, that is fine. We use the Plexus Code Style (which is almost the same as Allman) so
please format your code accordingly.
6. Push your changes to your new branch and make a PR based off of that branch.
## Requirements for a PR
- The issue must be marked as approved
- It must only address each specific issue. Don't make one PR for multiple issues.
- Your PR must compile and work. If it does not compile or work, your PR will most likely be rejected.
## Code requirements
- Most importantly, your code must be efficient. Your pull request may be rejected if your code is deemed inefficient or
sloppy.
- Do not repeat yourself. Create functions as needed if you're using large blocks of code over and over again.
- Do not use an excessive amount of commits when making your PR. It makes the master branch look messy.
- Your code must be consistent with Plex's codebase. If a function already exists, use it.

17
Jenkinsfile vendored
View File

@ -8,24 +8,13 @@ pipeline {
}
}
}
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
javadoc javadocDir: "server/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.WEBHOOK_URL
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.TF_WEBHOOK_URL
cleanWs()
}
}

View File

@ -1,16 +1,16 @@
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.
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
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
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
@ -19,35 +19,35 @@ 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
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
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
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:
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
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
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
@ -58,49 +58,49 @@ 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.
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
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
"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
"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
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
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
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
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"
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
@ -109,18 +109,18 @@ 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.
1. Source Code.
The "source code" for a work means the preferred form of the work
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
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
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
@ -131,7 +131,7 @@ implementation is available to the public in source code form. A
(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 "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
@ -144,16 +144,16 @@ 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
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
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
2. Basic Permissions.
All rights granted under this License are granted for the term of
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
@ -161,7 +161,7 @@ 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
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
@ -172,19 +172,19 @@ 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
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.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
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
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
@ -192,9 +192,9 @@ 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.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
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
@ -202,12 +202,12 @@ 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,
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.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
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:
@ -232,7 +232,7 @@ terms of section 4, provided that you also meet all of these conditions:
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
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
@ -242,9 +242,9 @@ 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.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
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:
@ -290,11 +290,11 @@ in one of these ways:
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
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
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,
@ -307,7 +307,7 @@ 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,
"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
@ -315,7 +315,7 @@ 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
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
@ -326,7 +326,7 @@ 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
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
@ -334,15 +334,15 @@ 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,
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.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
"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
@ -351,14 +351,14 @@ 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
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
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:
@ -385,7 +385,7 @@ that material) supplement the terms of this License with terms:
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
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
@ -395,46 +395,46 @@ 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
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
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.
8. Termination.
You may not propagate or modify a covered work except as expressly
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
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
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
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.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
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,
@ -443,14 +443,14 @@ 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.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
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
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
@ -460,7 +460,7 @@ 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
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
@ -468,13 +468,13 @@ rights granted under this License, and you may not initiate litigation
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
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
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,
@ -484,19 +484,19 @@ 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
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
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,
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,
@ -510,7 +510,7 @@ 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
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
@ -518,7 +518,7 @@ 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
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
@ -533,13 +533,13 @@ 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
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.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
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
@ -549,9 +549,9 @@ 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.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
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
@ -560,14 +560,14 @@ 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.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
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
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
@ -576,19 +576,19 @@ 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
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
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.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
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,
@ -597,9 +597,9 @@ 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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
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
@ -609,9 +609,9 @@ 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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
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
@ -622,11 +622,11 @@ copy of the Program in return for a fee.
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
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 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.
@ -649,7 +649,7 @@ the "copyright" line and a pointer to where the full notice is found.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
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>
@ -661,12 +661,12 @@ 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,
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
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

View File

@ -1,3 +1,8 @@
# Plex
# Plex [![Build Status](https://ci.plex.us.org/job/Plex/job/master/badge/icon)](https://ci.plex.us.org/job/Plex/job/master/) [![License](https://img.shields.io/github/license/plexusorg/Plex)](https://github.com/plexusorg/Plex/blob/master/LICENSE.md) [![Discord](https://img.shields.io/discord/927737516864446495)](https://discord.plex.us.org)
A new freedom plugin.
Plex is a new freedom plugin. It is an alternative to TotalFreedomMod. It has many of the features that make a freedom
server unique, but also many features that TotalFreedomMod doesnt have. For example, there is full support for using a
permissions plugin instead of ranks. It is also much more performance oriented. You can use Redis to store indefinite
bans and store player data in MongoDB, MariaDB, or SQLite. Plex is also fully customizable as you can change almost all
of the messages within the plugin. Plex also has a module system which can be used to add additional functionality. Plex
is not a rewrite, "debloat", or related to TotalFreedomMod. Plex is an entirely new experience.

View File

@ -1,146 +0,0 @@
plugins {
id "java"
id "maven-publish"
id "net.minecrell.plugin-yml.bukkit" version "0.5.1"
id "com.github.johnrengelman.shadow" version "7.1.2"
}
repositories {
mavenLocal()
maven {
url = uri("https://papermc.io/repo/repository/maven-public/")
}
maven {
url = uri("https://repository.apache.org/content/repositories/snapshots/")
}
maven {
url = uri("https://repo.maven.apache.org/maven2/")
}
mavenCentral()
}
dependencies {
library "org.projectlombok:lombok:1.18.22"
annotationProcessor "org.projectlombok:lombok:1.18.22"
library "org.json:json:20220320"
library "commons-io:commons-io:2.11.0"
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"
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"
}
group = "dev.plex"
version = "1.0"
description = "Plex"
shadowJar {
archiveClassifier.set("")
relocate "org.bstats", "dev.plex"
}
bukkit {
name = "Plex"
version = rootProject.version
description = "Plex provides a new experience for freedom servers."
main = "dev.plex.Plex"
website = "https://plex.us.org"
authors = ["Telesphoreo", "taahanis", "super"]
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))
}
publishing {
publications {
maven(MavenPublication) {
from(components.java)
}
}
repositories {
maven {
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("plexUser")
password = System.getenv("plexPassword")
}
}
}
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
tasks {
build {
dependsOn(shadowJar)
finalizedBy(buildProperties)
}
javadoc {
options.memberLevel = JavadocMemberLevel.PRIVATE
}
}

91
build.gradle.kts Normal file
View File

@ -0,0 +1,91 @@
plugins {
id("java")
id("maven-publish")
id("org.jetbrains.gradle.plugin.idea-ext") version "1.1.8"
id("net.kyori.blossom") version "2.1.0"
id("io.github.goooler.shadow") version "8.1.7"
}
group = "dev.plex"
version = "1.4"
description = "Plex"
subprojects {
apply(plugin = "java")
apply(plugin = "maven-publish")
apply(plugin = "org.jetbrains.gradle.plugin.idea-ext")
apply(plugin = "net.kyori.blossom")
apply(plugin = "io.github.goooler.shadow")
repositories {
maven {
url = uri("https://repo.papermc.io/repository/maven-public/")
}
maven {
url = uri("https://repository.apache.org/content/repositories/snapshots/")
}
maven {
url = uri("https://repo.maven.apache.org/maven2/")
}
maven {
url = uri("https://jitpack.io")
content {
includeGroup("com.github.MilkBowl")
includeGroup("com.github.LeonMangler")
}
}
mavenCentral()
}
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
}
tasks {
compileJava {
options.encoding = Charsets.UTF_8.name()
}
javadoc {
options.encoding = Charsets.UTF_8.name()
}
processResources {
filteringCharset = Charsets.UTF_8.name()
}
}
publishing {
repositories {
maven {
val releasesRepoUrl = uri("https://nexus.telesphoreo.me/repository/plex-releases/")
val snapshotsRepoUrl = uri("https://nexus.telesphoreo.me/repository/plex-snapshots/")
url = if (rootProject.version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl
credentials {
username = System.getenv("plexUser")
password = System.getenv("plexPassword")
}
}
}
}
}
tasks.clean {
dependsOn(subprojects.map {
it.project.tasks.clean
})
}
tasks.create<Copy>("copyJars") {
dependsOn(tasks.jar)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(subprojects.map {
it.project.tasks.shadowJar
})
from(subprojects.map {
it.project.tasks.jar
})
into(file("build/libs"))
}

Binary file not shown.

View File

@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

41
gradlew vendored
View File

@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@ -80,13 +80,11 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -133,22 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -205,6 +214,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.

15
gradlew.bat vendored
View File

@ -14,7 +14,7 @@
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

47
proxy/build.gradle.kts Normal file
View File

@ -0,0 +1,47 @@
group = rootProject.group
version = rootProject.version
description = "Plex-Velocity"
repositories {
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
}
tasks.getByName<Jar>("jar") {
archiveBaseName.set("Plex-Velocity")
}
tasks {
jar {
finalizedBy(rootProject.tasks["copyJars"])
}
shadowJar {
enabled = false
}
}
sourceSets {
main {
blossom {
javaSources {
property("version", project.version.toString())
}
}
}
}
publishing {
publications {
create<MavenPublication>("maven") {
from(components["java"])
}
}
}
dependencies {
compileOnly("org.projectlombok:lombok:1.18.32")
annotationProcessor("org.projectlombok:lombok:1.18.32")
compileOnly("org.json:json:20240303")
compileOnly("com.velocitypowered:velocity-api:3.2.0-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.2.0-SNAPSHOT")
}

View File

@ -0,0 +1,5 @@
package dev.plex;
class BuildParameters {
public static final String VERSION = "{{ version }}";
}

View File

@ -0,0 +1,82 @@
package dev.plex;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import dev.plex.config.TomlConfig;
import dev.plex.handlers.ListenerHandler;
import dev.plex.settings.ServerSettings;
import dev.plex.util.PlexLog;
import lombok.Getter;
import java.io.File;
import java.nio.file.Path;
import java.util.logging.Logger;
/**
* Credits for TOML library go to https://github.com/mwanji/toml4j
* I was unable to add it back to the package without it glitching, so
* I kept it in a separate package.
* <p>
* Modifications: Properly indent arrays in TOML as well as only append
* missing object fields into the file
*/
@Plugin(
name = "Plex",
id = "plex",
version = BuildParameters.VERSION,
url = "https://plex.us.org",
description = "Plex provides a new experience for freedom servers.",
authors = {"Telesphoreo", "Taah"}
)
@Getter
public class Plex
{
private static Plex plugin;
public final ProxyServer server;
private final Logger logger;
private final File dataFolder;
private TomlConfig config;
@Inject
public Plex(ProxyServer server, Logger logger, @DataDirectory Path folder)
{
plugin = this;
this.server = server;
this.logger = logger;
this.dataFolder = folder.toFile();
if (!dataFolder.exists())
{
dataFolder.mkdir();
}
PlexLog.log("Enabling Plex-Velocity");
}
@Subscribe
public void onStart(ProxyInitializeEvent event)
{
this.config = new TomlConfig("config.toml");
this.config.setOnCreate(toml ->
{
PlexLog.log("Created configuration 'config.toml'");
});
this.config.setOnLoad(toml ->
{
PlexLog.log("Loaded configuration 'config.toml'");
});
this.config.create(true);
this.config.write(new ServerSettings());
new ListenerHandler();
}
public static Plex get()
{
return plugin;
}
}

View File

@ -0,0 +1,103 @@
package dev.plex.command;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.command.SimpleCommand;
import com.velocitypowered.api.proxy.ConsoleCommandSource;
import com.velocitypowered.api.proxy.Player;
import dev.plex.Plex;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
public abstract class PlexCommand implements SimpleCommand
{
/**
* Returns the instance of the plugin
*/
protected static Plex plugin = Plex.get();
/**
* The parameters for the command
*/
private final CommandParameters params;
/**
* The permissions for the command
*/
private final CommandPermissions perms;
/**
* Required command source fetched from the permissions
*/
private final RequiredCommandSource commandSource;
public PlexCommand()
{
this.params = getClass().getAnnotation(CommandParameters.class);
this.perms = getClass().getAnnotation(CommandPermissions.class);
this.commandSource = this.perms.source();
CommandMeta.Builder meta = plugin.getServer().getCommandManager().metaBuilder(this.params.name());
meta.aliases(this.params.aliases());
meta.plugin(Plex.get());
plugin.getServer().getCommandManager().register(meta.build(), this);
}
protected abstract Component execute(@NotNull CommandSource source, @Nullable Player player, @NotNull String[] args);
@Override
public void execute(Invocation invocation)
{
if (!matches(invocation.alias()))
{
return;
}
if (commandSource == RequiredCommandSource.CONSOLE && invocation.source() instanceof Player)
{
// sender.sendMessage(messageComponent("noPermissionInGame"));
return;
}
if (commandSource == RequiredCommandSource.IN_GAME)
{
if (invocation.source() instanceof ConsoleCommandSource)
{
// send(sender, messageComponent("noPermissionConsole"));
return;
}
}
if (!perms.permission().isEmpty())
{
if (!invocation.source().hasPermission(perms.permission()))
{
return;
}
}
Component component = this.execute(invocation.source(), invocation.source() instanceof ConsoleCommandSource ? null : (Player) invocation.source(), invocation.arguments());
if (component != null)
{
send(invocation.source(), component);
}
}
private boolean matches(String label)
{
if (params.name().equalsIgnoreCase(label))
{
return true;
}
return Arrays.stream(params.aliases()).anyMatch(s -> s.equalsIgnoreCase(label));
}
protected void send(Audience audience, Component component)
{
audience.sendMessage(component);
}
}

View File

@ -0,0 +1,39 @@
package dev.plex.command.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Storage for a command's parameters
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandParameters
{
/**
* The name
*
* @return Name of the command
*/
String name();
/**
* The description
*
* @return Description of the command
*/
String description() default "";
/**
* The usage (optional)
*
* @return The usage of the command
*/
String usage() default "/<command>";
/**
* The aliases (optional)
*
* @return The aliases of the command
*/
String[] aliases() default {};
}

View File

@ -1,7 +1,7 @@
package dev.plex.command.annotation;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@ -11,14 +11,6 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandPermissions
{
/**
* Minimum rank required
*
* @return Minimum rank required for the command
* @see Rank
*/
Rank level() default Rank.IMPOSTOR;
/**
* Required command source
*

View File

@ -0,0 +1,100 @@
package dev.plex.config;
import dev.plex.Plex;
import dev.plex.toml.Toml;
import dev.plex.toml.TomlWriter;
import lombok.Getter;
import lombok.Setter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.function.Consumer;
@Getter
public class TomlConfig
{
private final File file;
private Toml toml;
@Setter
private Consumer<Toml> onCreate;
@Setter
private Consumer<Toml> onLoad;
public TomlConfig(String fileName)
{
this.file = new File(Plex.get().getDataFolder(), fileName);
this.toml = new Toml();
}
public void create(boolean loadFromFile)
{
if (!this.file.exists())
{
if (loadFromFile)
{
try
{
Files.copy(Plex.get().getClass().getResourceAsStream("/" + this.file.getName()), this.file.toPath());
this.load();
if (this.onCreate != null)
{
this.onCreate.accept(this.toml);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return;
}
try
{
this.file.createNewFile();
this.load();
if (this.onCreate != null)
{
this.onCreate.accept(this.toml);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return;
}
this.load();
}
public void load()
{
this.toml = new Toml().read(this.file);
if (onLoad != null)
{
this.onLoad.accept(this.toml);
}
}
public <T> T as(Class<T> clazz)
{
return this.toml.to(clazz);
}
public <T> void write(T object)
{
TomlWriter writer = new TomlWriter.Builder()
.indentValuesBy(2)
.build();
try
{
writer.write(object, this.file);
this.load();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,33 @@
package dev.plex.handlers;
import com.google.common.collect.Lists;
import dev.plex.listener.PlexListener;
import dev.plex.util.PlexLog;
import dev.plex.util.ReflectionsUtil;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
public class ListenerHandler
{
public ListenerHandler()
{
Set<Class<? extends PlexListener>> listenerSet = ReflectionsUtil.getClassesBySubType("dev.plex.listener.impl", PlexListener.class);
List<PlexListener> listeners = Lists.newArrayList();
listenerSet.forEach(clazz ->
{
try
{
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,13 @@
package dev.plex.listener;
import dev.plex.Plex;
public class PlexListener
{
protected final Plex plugin = Plex.get();
public PlexListener()
{
Plex.get().getServer().getEventManager().register(Plex.get(), this);
}
}

View File

@ -0,0 +1,45 @@
package dev.plex.listener.impl;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import com.velocitypowered.api.event.player.ServerConnectedEvent;
import dev.plex.Plex;
import dev.plex.listener.PlexListener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
public class ConnectionListener extends PlexListener
{
@Subscribe(order = PostOrder.FIRST)
public void onPlayerJoin(ServerConnectedEvent event)
{
if (event.getPreviousServer().isPresent())
{
Plex.get().server.sendMessage(miniMessage("<dark_gray>[<#ffbf00>o<dark_gray>] <yellow>"
+ event.getPlayer().getUsername() + " switched from " + event.getPreviousServer().get().getServerInfo().getName()
+ " to " + event.getServer().getServerInfo().getName()));
}
else
{
Plex.get().server.sendMessage(miniMessage("<dark_gray>[<green>+<dark_gray>] <yellow>"
+ event.getPlayer().getUsername() + " joined server " + event.getServer().getServerInfo().getName()));
}
}
@Subscribe(order = PostOrder.FIRST)
public void onPlayerLeave(DisconnectEvent event)
{
if (event.getPlayer().getCurrentServer().isPresent())
{
Plex.get().server.sendMessage(miniMessage("<dark_gray>[<red>-<dark_gray>] <yellow>"
+ event.getPlayer().getUsername() + " left server " +
event.getPlayer().getCurrentServer().get().getServerInfo().getName()));
}
}
private Component miniMessage(String message)
{
return MiniMessage.miniMessage().deserialize(message);
}
}

View File

@ -0,0 +1,63 @@
package dev.plex.listener.impl;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
import com.velocitypowered.api.proxy.server.ServerPing;
import dev.plex.listener.PlexListener;
import dev.plex.settings.ServerSettings;
import dev.plex.util.RandomUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ServerListener extends PlexListener
{
@Subscribe(order = PostOrder.FIRST)
public void onPing(ProxyPingEvent event)
{
String baseMotd = plugin.getConfig().as(ServerSettings.class).getServer().getMotd().get(ThreadLocalRandom.current().nextInt(plugin.getConfig().as(ServerSettings.class).getServer().getMotd().size()));
baseMotd = baseMotd.replace("\\n", "\n");
baseMotd = baseMotd.replace("%servername%", plugin.getConfig().as(ServerSettings.class).getServer().getName());
baseMotd = baseMotd.replace("%mcversion%", plugin.getServer().getVersion().getVersion().split(" ")[0]);
baseMotd = baseMotd.replace("%randomgradient%", "<gradient:" + RandomUtil.getRandomColor().toString() + ":" + RandomUtil.getRandomColor().toString() + ">");
ServerPing.Builder builder = event.getPing().asBuilder();
if (plugin.getConfig().as(ServerSettings.class).getServer().isColorizeMotd())
{
AtomicReference<Component> motd = new AtomicReference<>(Component.empty());
for (final String word : baseMotd.split(" "))
{
motd.set(motd.get().append(Component.text(word).color(RandomUtil.getRandomColor())));
motd.set(motd.get().append(Component.space()));
}
builder.description(motd.get());
}
else
{
builder.description(MiniMessage.miniMessage().deserialize(baseMotd));
}
builder.samplePlayers(plugin.getConfig().as(ServerSettings.class).getServer().getSample().stream().map(s -> new ServerPing.SamplePlayer(convertColorCodes(s), UUID.randomUUID())).toArray(ServerPing.SamplePlayer[]::new));
builder.onlinePlayers(plugin.getServer().getPlayerCount() + plugin.getConfig().as(ServerSettings.class).getServer().getAddPlayerCount());
if (plugin.getConfig().as(ServerSettings.class).getServer().isPlusOneMaxPlayer())
{
builder.maximumPlayers(builder.getOnlinePlayers() + 1);
}
event.setPing(builder.build());
}
private String convertColorCodes(String code)
{
Matcher matcher = Pattern.compile("[&][0-9a-fk-or]{1}").matcher(code);
return matcher.replaceAll(matchResult -> "§" + matcher.group().substring(1));
}
}

View File

@ -0,0 +1,28 @@
package dev.plex.settings;
import com.google.common.collect.Lists;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import lombok.Getter;
import java.util.List;
@Getter
public class ServerSettings
{
private final Server server = new Server();
@Data
public static class Server
{
private String name = "Server";
private List<String> motd = Lists.newArrayList("%randomgradient%%servername% - %mcversion%", "Another motd");
private boolean colorizeMotd = false;
private boolean debug = false;
private final List<String> sample = Lists.newArrayList("example", "example");
@SerializedName(value = "add-player-count")
private int addPlayerCount = 0;
@SerializedName(value = "plus-one-max-count")
private boolean plusOneMaxPlayer = true;
}
}

View File

@ -0,0 +1,108 @@
package dev.plex.toml;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class ArrayValueReader implements ValueReader
{
public static final ArrayValueReader ARRAY_VALUE_READER = new ArrayValueReader();
@Override
public boolean canRead(String s)
{
return s.startsWith("[");
}
@Override
public Object read(String s, AtomicInteger index, dev.plex.toml.Context context)
{
AtomicInteger line = context.line;
int startLine = line.get();
int startIndex = index.get();
List<Object> arrayItems = new ArrayList<Object>();
boolean terminated = false;
boolean inComment = false;
dev.plex.toml.Results.Errors errors = new dev.plex.toml.Results.Errors();
for (int i = index.incrementAndGet(); i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
if (c == '#' && !inComment)
{
inComment = true;
}
else if (c == '\n')
{
inComment = false;
line.incrementAndGet();
}
else if (inComment || Character.isWhitespace(c) || c == ',')
{
continue;
}
else if (c == '[')
{
Object converted = read(s, index, context);
if (converted instanceof dev.plex.toml.Results.Errors)
{
errors.add((dev.plex.toml.Results.Errors) converted);
}
else if (!isHomogenousArray(converted, arrayItems))
{
errors.heterogenous(context.identifier.getName(), line.get());
}
else
{
arrayItems.add(converted);
}
continue;
}
else if (c == ']')
{
terminated = true;
break;
}
else
{
Object converted = ValueReaders.VALUE_READERS.convert(s, index, context);
if (converted instanceof dev.plex.toml.Results.Errors)
{
errors.add((dev.plex.toml.Results.Errors) converted);
}
else if (!isHomogenousArray(converted, arrayItems))
{
errors.heterogenous(context.identifier.getName(), line.get());
}
else
{
arrayItems.add(converted);
}
}
}
if (!terminated)
{
errors.unterminated(context.identifier.getName(), s.substring(startIndex), startLine);
}
if (errors.hasErrors())
{
return errors;
}
return arrayItems;
}
private boolean isHomogenousArray(Object o, List<?> values)
{
return values.isEmpty() || values.get(0).getClass().isAssignableFrom(o.getClass()) || o.getClass().isAssignableFrom(values.get(0).getClass());
}
private ArrayValueReader()
{
}
}

View File

@ -0,0 +1,83 @@
package dev.plex.toml;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import static dev.plex.toml.ValueWriters.WRITERS;
public abstract class ArrayValueWriter implements dev.plex.toml.ValueWriter
{
static protected boolean isArrayish(Object value)
{
return value instanceof Collection || value.getClass().isArray();
}
@Override
public boolean isPrimitiveType()
{
return false;
}
static boolean isArrayOfPrimitive(Object array)
{
Object first = peek(array);
if (first != null)
{
dev.plex.toml.ValueWriter valueWriter = WRITERS.findWriterFor(first);
return valueWriter.isPrimitiveType() || isArrayish(first);
}
return true;
}
@SuppressWarnings("unchecked")
protected Collection<?> normalize(Object value)
{
Collection<Object> collection;
if (value.getClass().isArray())
{
// Arrays.asList() interprets an array as a single element,
// so convert it to a list by hand
collection = new ArrayList<Object>(Array.getLength(value));
for (int i = 0; i < Array.getLength(value); i++)
{
Object elem = Array.get(value, i);
collection.add(elem);
}
}
else
{
collection = (Collection<Object>) value;
}
return collection;
}
private static Object peek(Object value)
{
if (value.getClass().isArray())
{
if (Array.getLength(value) > 0)
{
return Array.get(value, 0);
}
else
{
return null;
}
}
else
{
Collection<?> collection = (Collection<?>) value;
if (collection.size() > 0)
{
return collection.iterator().next();
}
}
return null;
}
}

View File

@ -0,0 +1,57 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
class BooleanValueReaderWriter implements ValueReader, ValueWriter
{
static final BooleanValueReaderWriter BOOLEAN_VALUE_READER_WRITER = new BooleanValueReaderWriter();
@Override
public boolean canRead(String s)
{
return s.startsWith("true") || s.startsWith("false");
}
@Override
public Object read(String s, AtomicInteger index, Context context)
{
s = s.substring(index.get());
Boolean b = s.startsWith("true") ? Boolean.TRUE : Boolean.FALSE;
int endIndex = b == Boolean.TRUE ? 4 : 5;
index.addAndGet(endIndex - 1);
return b;
}
@Override
public boolean canWrite(Object value)
{
return value instanceof Boolean;
}
@Override
public void write(Object value, WriterContext context)
{
context.write(value.toString());
}
@Override
public boolean isPrimitiveType()
{
return true;
}
private BooleanValueReaderWriter()
{
}
@Override
public String toString()
{
return "boolean";
}
}

View File

@ -0,0 +1,152 @@
package dev.plex.toml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class Container
{
abstract boolean accepts(String key);
abstract void put(String key, Object value);
abstract Object get(String key);
abstract boolean isImplicit();
static class Table extends Container
{
private final Map<String, Object> values = new HashMap<String, Object>();
final String name;
final boolean implicit;
Table()
{
this(null, false);
}
public Table(String name)
{
this(name, false);
}
public Table(String tableName, boolean implicit)
{
this.name = tableName;
this.implicit = implicit;
}
@Override
boolean accepts(String key)
{
return !values.containsKey(key) || values.get(key) instanceof TableArray;
}
@Override
void put(String key, Object value)
{
values.put(key, value);
}
@Override
Object get(String key)
{
return values.get(key);
}
boolean isImplicit()
{
return implicit;
}
/**
* This modifies the Table's internal data structure, such that it is no longer usable.
* <p>
* Therefore, this method must only be called when all data has been gathered.
*
* @return A Map-and-List-based of the TOML data
*/
Map<String, Object> consume()
{
for (Map.Entry<String, Object> entry : values.entrySet())
{
if (entry.getValue() instanceof Table)
{
entry.setValue(((Table) entry.getValue()).consume());
}
else if (entry.getValue() instanceof TableArray)
{
entry.setValue(((TableArray) entry.getValue()).getValues());
}
}
return values;
}
@Override
public String toString()
{
return values.toString();
}
}
static class TableArray extends Container
{
private final List<Table> values = new ArrayList<Table>();
TableArray()
{
values.add(new Table());
}
@Override
boolean accepts(String key)
{
return getCurrent().accepts(key);
}
@Override
void put(String key, Object value)
{
values.add((Table) value);
}
@Override
Object get(String key)
{
throw new UnsupportedOperationException();
}
boolean isImplicit()
{
return false;
}
List<Map<String, Object>> getValues()
{
ArrayList<Map<String, Object>> unwrappedValues = new ArrayList<Map<String, Object>>();
for (Table table : values)
{
unwrappedValues.add(table.consume());
}
return unwrappedValues;
}
Table getCurrent()
{
return values.get(values.size() - 1);
}
@Override
public String toString()
{
return values.toString();
}
}
private Container()
{
}
}

View File

@ -0,0 +1,22 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
public class Context
{
final dev.plex.toml.Identifier identifier;
final AtomicInteger line;
final Results.Errors errors;
public Context(dev.plex.toml.Identifier identifier, AtomicInteger line, Results.Errors errors)
{
this.identifier = identifier;
this.line = line;
this.errors = errors;
}
public Context with(dev.plex.toml.Identifier identifier)
{
return new Context(identifier, line, errors);
}
}

View File

@ -0,0 +1,26 @@
package dev.plex.toml;
import java.util.TimeZone;
public class DatePolicy
{
private final TimeZone timeZone;
private final boolean showFractionalSeconds;
DatePolicy(TimeZone timeZone, boolean showFractionalSeconds)
{
this.timeZone = timeZone;
this.showFractionalSeconds = showFractionalSeconds;
}
TimeZone getTimeZone()
{
return timeZone;
}
boolean isShowFractionalSeconds()
{
return showFractionalSeconds;
}
}

View File

@ -0,0 +1,204 @@
package dev.plex.toml;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateValueReaderWriter implements ValueReader, ValueWriter
{
static final DateValueReaderWriter DATE_VALUE_READER_WRITER = new DateValueReaderWriter();
static final DateValueReaderWriter DATE_PARSER_JDK_6 = new DateConverterJdk6();
private static final Pattern DATE_REGEX = Pattern.compile("(\\d{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9])(\\.\\d*)?(Z|(?:[+\\-]\\d{2}:\\d{2}))(.*)");
@Override
public boolean canRead(String s)
{
if (s.length() < 5)
{
return false;
}
for (int i = 0; i < 5; i++)
{
char c = s.charAt(i);
if (i < 4)
{
if (!Character.isDigit(c))
{
return false;
}
}
else if (c != '-')
{
return false;
}
}
return true;
}
@Override
public Object read(String original, AtomicInteger index, Context context)
{
StringBuilder sb = new StringBuilder();
for (int i = index.get(); i < original.length(); i = index.incrementAndGet())
{
char c = original.charAt(i);
if (Character.isDigit(c) || c == '-' || c == '+' || c == ':' || c == '.' || c == 'T' || c == 'Z')
{
sb.append(c);
}
else
{
index.decrementAndGet();
break;
}
}
String s = sb.toString();
Matcher matcher = DATE_REGEX.matcher(s);
if (!matcher.matches())
{
Results.Errors errors = new Results.Errors();
errors.invalidValue(context.identifier.getName(), s, context.line.get());
return errors;
}
String dateString = matcher.group(1);
String zone = matcher.group(3);
String fractionalSeconds = matcher.group(2);
String format = "yyyy-MM-dd'T'HH:mm:ss";
if (fractionalSeconds != null && !fractionalSeconds.isEmpty())
{
format += ".SSS";
dateString += fractionalSeconds;
}
format += "Z";
if ("Z".equals(zone))
{
dateString += "+0000";
}
else if (zone.contains(":"))
{
dateString += zone.replace(":", "");
}
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat.parse(dateString);
}
catch (Exception e)
{
Results.Errors errors = new Results.Errors();
errors.invalidValue(context.identifier.getName(), s, context.line.get());
return errors;
}
}
@Override
public boolean canWrite(Object value)
{
return value instanceof Date;
}
@Override
public void write(Object value, WriterContext context)
{
DateFormat formatter = getFormatter(context.getDatePolicy());
context.write(formatter.format(value));
}
@Override
public boolean isPrimitiveType()
{
return true;
}
private DateFormat getFormatter(DatePolicy datePolicy)
{
boolean utc = "UTC".equals(datePolicy.getTimeZone().getID());
String format;
if (utc && datePolicy.isShowFractionalSeconds())
{
format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
}
else if (utc)
{
format = "yyyy-MM-dd'T'HH:mm:ss'Z'";
}
else if (datePolicy.isShowFractionalSeconds())
{
format = getTimeZoneAndFractionalSecondsFormat();
}
else
{
format = getTimeZoneFormat();
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.setTimeZone(datePolicy.getTimeZone());
return formatter;
}
String getTimeZoneFormat()
{
return "yyyy-MM-dd'T'HH:mm:ssXXX";
}
String getTimeZoneAndFractionalSecondsFormat()
{
return "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
}
private DateValueReaderWriter()
{
}
private static class DateConverterJdk6 extends DateValueReaderWriter
{
@Override
public void write(Object value, WriterContext context)
{
DateFormat formatter = super.getFormatter(context.getDatePolicy());
String date = formatter.format(value);
if ("UTC".equals(context.getDatePolicy().getTimeZone().getID()))
{
context.write(date);
}
else
{
int insertionIndex = date.length() - 2;
context.write(date.substring(0, insertionIndex)).write(':').write(date.substring(insertionIndex));
}
}
@Override
String getTimeZoneAndFractionalSecondsFormat()
{
return "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
}
@Override
String getTimeZoneFormat()
{
return "yyyy-MM-dd'T'HH:mm:ssZ";
}
}
@Override
public String toString()
{
return "datetime";
}
}

View File

@ -0,0 +1,341 @@
package dev.plex.toml;
public class Identifier
{
static final Identifier INVALID = new Identifier("", null);
private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-";
private final String name;
private final Type type;
static Identifier from(String name, Context context)
{
Type type;
boolean valid;
name = name.trim();
if (name.startsWith("[["))
{
type = Type.TABLE_ARRAY;
valid = isValidTableArray(name, context);
}
else if (name.startsWith("["))
{
type = Type.TABLE;
valid = isValidTable(name, context);
}
else
{
type = Type.KEY;
valid = isValidKey(name, context);
}
if (!valid)
{
return Identifier.INVALID;
}
return new Identifier(extractName(name), type);
}
private Identifier(String name, Type type)
{
this.name = name;
this.type = type;
}
String getName()
{
return name;
}
String getBareName()
{
if (isKey())
{
return name;
}
if (isTable())
{
return name.substring(1, name.length() - 1);
}
return name.substring(2, name.length() - 2);
}
boolean isKey()
{
return type == Type.KEY;
}
boolean isTable()
{
return type == Type.TABLE;
}
boolean isTableArray()
{
return type == Type.TABLE_ARRAY;
}
private enum Type
{
KEY, TABLE, TABLE_ARRAY
}
private static String extractName(String raw)
{
boolean quoted = false;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < raw.length(); i++)
{
char c = raw.charAt(i);
if (c == '"' && (i == 0 || raw.charAt(i - 1) != '\\'))
{
quoted = !quoted;
sb.append('"');
}
else if (quoted || !Character.isWhitespace(c))
{
sb.append(c);
}
}
return StringValueReaderWriter.STRING_VALUE_READER_WRITER.replaceUnicodeCharacters(sb.toString());
}
private static boolean isValidKey(String name, Context context)
{
if (name.trim().isEmpty())
{
context.errors.invalidKey(name, context.line.get());
return false;
}
boolean quoted = false;
for (int i = 0; i < name.length(); i++)
{
char c = name.charAt(i);
if (c == '"' && (i == 0 || name.charAt(i - 1) != '\\'))
{
if (!quoted && i > 0 && name.charAt(i - 1) != '.')
{
context.errors.invalidKey(name, context.line.get());
return false;
}
quoted = !quoted;
}
else if (!quoted && (ALLOWED_CHARS.indexOf(c) == -1))
{
context.errors.invalidKey(name, context.line.get());
return false;
}
}
return true;
}
private static boolean isValidTable(String name, Context context)
{
boolean valid = name.endsWith("]");
String trimmed = name.substring(1, name.length() - 1).trim();
if (trimmed.isEmpty() || trimmed.charAt(0) == '.' || trimmed.endsWith("."))
{
valid = false;
}
if (!valid)
{
context.errors.invalidTable(name, context.line.get());
return false;
}
boolean quoted = false;
boolean dotAllowed = false;
boolean quoteAllowed = true;
boolean charAllowed = true;
for (int i = 0; i < trimmed.length(); i++)
{
char c = trimmed.charAt(i);
if (!valid)
{
break;
}
if (Keys.isQuote(c))
{
if (!quoteAllowed)
{
valid = false;
}
else if (quoted && trimmed.charAt(i - 1) != '\\')
{
charAllowed = false;
dotAllowed = true;
quoteAllowed = false;
}
else if (!quoted)
{
quoted = true;
quoteAllowed = true;
}
}
else if (quoted)
{
continue;
}
else if (c == '.')
{
if (dotAllowed)
{
charAllowed = true;
dotAllowed = false;
quoteAllowed = true;
}
else
{
context.errors.emptyImplicitTable(name, context.line.get());
return false;
}
}
else if (Character.isWhitespace(c))
{
char prev = trimmed.charAt(i - 1);
if (!Character.isWhitespace(prev) && prev != '.')
{
charAllowed = false;
dotAllowed = true;
quoteAllowed = true;
}
}
else
{
if (charAllowed && ALLOWED_CHARS.indexOf(c) > -1)
{
charAllowed = true;
dotAllowed = true;
quoteAllowed = false;
}
else
{
valid = false;
}
}
}
if (!valid)
{
context.errors.invalidTable(name, context.line.get());
return false;
}
return true;
}
private static boolean isValidTableArray(String line, Context context)
{
boolean valid = line.endsWith("]]");
String trimmed = line.substring(2, line.length() - 2).trim();
if (trimmed.isEmpty() || trimmed.charAt(0) == '.' || trimmed.endsWith("."))
{
valid = false;
}
if (!valid)
{
context.errors.invalidTableArray(line, context.line.get());
return false;
}
boolean quoted = false;
boolean dotAllowed = false;
boolean quoteAllowed = true;
boolean charAllowed = true;
for (int i = 0; i < trimmed.length(); i++)
{
char c = trimmed.charAt(i);
if (!valid)
{
break;
}
if (c == '"')
{
if (!quoteAllowed)
{
valid = false;
}
else if (quoted && trimmed.charAt(i - 1) != '\\')
{
charAllowed = false;
dotAllowed = true;
quoteAllowed = false;
}
else if (!quoted)
{
quoted = true;
quoteAllowed = true;
}
}
else if (quoted)
{
continue;
}
else if (c == '.')
{
if (dotAllowed)
{
charAllowed = true;
dotAllowed = false;
quoteAllowed = true;
}
else
{
context.errors.emptyImplicitTable(line, context.line.get());
return false;
}
}
else if (Character.isWhitespace(c))
{
char prev = trimmed.charAt(i - 1);
if (!Character.isWhitespace(prev) && prev != '.' && prev != '"')
{
charAllowed = false;
dotAllowed = true;
quoteAllowed = true;
}
}
else
{
if (charAllowed && ALLOWED_CHARS.indexOf(c) > -1)
{
charAllowed = true;
dotAllowed = true;
quoteAllowed = false;
}
else
{
valid = false;
}
}
}
if (!valid)
{
context.errors.invalidTableArray(line, context.line.get());
return false;
}
return true;
}
}

View File

@ -0,0 +1,88 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
public class IdentifierConverter
{
static final IdentifierConverter IDENTIFIER_CONVERTER = new IdentifierConverter();
Identifier convert(String s, AtomicInteger index, Context context)
{
boolean quoted = false;
StringBuilder name = new StringBuilder();
boolean terminated = false;
boolean isKey = s.charAt(index.get()) != '[';
boolean isTableArray = !isKey && s.length() > index.get() + 1 && s.charAt(index.get() + 1) == '[';
boolean inComment = false;
for (int i = index.get(); i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
if (Keys.isQuote(c) && (i == 0 || s.charAt(i - 1) != '\\'))
{
quoted = !quoted;
name.append(c);
}
else if (c == '\n')
{
index.decrementAndGet();
break;
}
else if (quoted)
{
name.append(c);
}
else if (c == '=' && isKey)
{
terminated = true;
break;
}
else if (c == ']' && !isKey)
{
if (!isTableArray || s.length() > index.get() + 1 && s.charAt(index.get() + 1) == ']')
{
terminated = true;
name.append(']');
if (isTableArray)
{
name.append(']');
}
}
}
else if (terminated && c == '#')
{
inComment = true;
}
else if (terminated && !Character.isWhitespace(c) && !inComment)
{
terminated = false;
break;
}
else if (!terminated)
{
name.append(c);
}
}
if (!terminated)
{
if (isKey)
{
context.errors.unterminatedKey(name.toString(), context.line.get());
}
else
{
context.errors.invalidKey(name.toString(), context.line.get());
}
return Identifier.INVALID;
}
return Identifier.from(name.toString(), context);
}
private IdentifierConverter()
{
}
}

View File

@ -0,0 +1,35 @@
package dev.plex.toml;
/**
* Controls how a {@link TomlWriter} indents tables and key/value pairs.
* <p>
* The default policy is to not indent.
*/
public class IndentationPolicy
{
private final int tableIndent;
private final int keyValueIndent;
private final int arrayDelimiterPadding;
IndentationPolicy(int keyIndentation, int tableIndentation, int arrayDelimiterPadding)
{
this.keyValueIndent = keyIndentation;
this.tableIndent = tableIndentation;
this.arrayDelimiterPadding = arrayDelimiterPadding;
}
int getTableIndent()
{
return tableIndent;
}
int getKeyValueIndent()
{
return keyValueIndent;
}
int getArrayDelimiterPadding()
{
return arrayDelimiterPadding;
}
}

View File

@ -0,0 +1,94 @@
package dev.plex.toml;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
class InlineTableValueReader implements dev.plex.toml.ValueReader
{
static final InlineTableValueReader INLINE_TABLE_VALUE_READER = new InlineTableValueReader();
@Override
public boolean canRead(String s)
{
return s.startsWith("{");
}
@Override
public Object read(String s, AtomicInteger sharedIndex, dev.plex.toml.Context context)
{
AtomicInteger line = context.line;
int startLine = line.get();
int startIndex = sharedIndex.get();
boolean inKey = true;
boolean inValue = false;
boolean terminated = false;
StringBuilder currentKey = new StringBuilder();
HashMap<String, Object> results = new HashMap<String, Object>();
dev.plex.toml.Results.Errors errors = new dev.plex.toml.Results.Errors();
for (int i = sharedIndex.incrementAndGet(); sharedIndex.get() < s.length(); i = sharedIndex.incrementAndGet())
{
char c = s.charAt(i);
if (inValue && !Character.isWhitespace(c))
{
Object converted = dev.plex.toml.ValueReaders.VALUE_READERS.convert(s, sharedIndex, context.with(dev.plex.toml.Identifier.from(currentKey.toString(), context)));
if (converted instanceof dev.plex.toml.Results.Errors)
{
errors.add((dev.plex.toml.Results.Errors) converted);
return errors;
}
String currentKeyTrimmed = currentKey.toString().trim();
Object previous = results.put(currentKeyTrimmed, converted);
if (previous != null)
{
errors.duplicateKey(currentKeyTrimmed, context.line.get());
return errors;
}
currentKey = new StringBuilder();
inValue = false;
}
else if (c == ',')
{
inKey = true;
inValue = false;
currentKey = new StringBuilder();
}
else if (c == '=')
{
inKey = false;
inValue = true;
}
else if (c == '}')
{
terminated = true;
break;
}
else if (inKey)
{
currentKey.append(c);
}
}
if (!terminated)
{
errors.unterminated(context.identifier.getName(), s.substring(startIndex), startLine);
}
if (errors.hasErrors())
{
return errors;
}
return results;
}
private InlineTableValueReader()
{
}
}

View File

@ -0,0 +1,86 @@
package dev.plex.toml;
import java.util.ArrayList;
import java.util.List;
class Keys
{
static class Key
{
final String name;
final int index;
final String path;
Key(String name, int index, Key next)
{
this.name = name;
this.index = index;
if (next != null)
{
this.path = name + "." + next.path;
}
else
{
this.path = name;
}
}
}
static Key[] split(String key)
{
List<Key> splitKey = new ArrayList<Key>();
StringBuilder current = new StringBuilder();
boolean quoted = false;
boolean indexable = true;
boolean inIndex = false;
int index = -1;
for (int i = key.length() - 1; i > -1; i--)
{
char c = key.charAt(i);
if (c == ']' && indexable)
{
inIndex = true;
continue;
}
indexable = false;
if (c == '[' && inIndex)
{
inIndex = false;
index = Integer.parseInt(current.toString());
current = new StringBuilder();
continue;
}
if (isQuote(c) && (i == 0 || key.charAt(i - 1) != '\\'))
{
quoted = !quoted;
indexable = false;
}
if (c != '.' || quoted)
{
current.insert(0, c);
}
else
{
splitKey.add(0, new Key(current.toString(), index, !splitKey.isEmpty() ? splitKey.get(0) : null));
indexable = true;
index = -1;
current = new StringBuilder();
}
}
splitKey.add(0, new Key(current.toString(), index, !splitKey.isEmpty() ? splitKey.get(0) : null));
return splitKey.toArray(new Key[0]);
}
static boolean isQuote(char c)
{
return c == '"' || c == '\'';
}
private Keys()
{
}
}

View File

@ -0,0 +1,48 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
public class LiteralStringValueReader implements ValueReader
{
public static final LiteralStringValueReader LITERAL_STRING_VALUE_READER = new LiteralStringValueReader();
@Override
public boolean canRead(String s)
{
return s.startsWith("'");
}
@Override
public Object read(String s, AtomicInteger index, dev.plex.toml.Context context)
{
int startLine = context.line.get();
boolean terminated = false;
int startIndex = index.incrementAndGet();
for (int i = index.get(); i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
if (c == '\'')
{
terminated = true;
break;
}
}
if (!terminated)
{
Results.Errors errors = new Results.Errors();
errors.unterminated(context.identifier.getName(), s.substring(startIndex), startLine);
return errors;
}
String substring = s.substring(startIndex, index.get());
return substring;
}
private LiteralStringValueReader()
{
}
}

View File

@ -0,0 +1,181 @@
package dev.plex.toml;
import java.io.File;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MapValueWriter implements dev.plex.toml.ValueWriter
{
static final dev.plex.toml.ValueWriter MAP_VALUE_WRITER = new MapValueWriter();
private static final Pattern REQUIRED_QUOTING_PATTERN = Pattern.compile("^.*[^A-Za-z\\d_-].*$");
@Override
public boolean canWrite(Object value)
{
return value instanceof Map;
}
@Override
public void write(Object value, WriterContext context)
{
File file = null;
if (context.file != null)
{
file = context.file;
}
Map<?, ?> from = (Map<?, ?>) value;
Toml toml = null;
if (file != null)
{
toml = new Toml().read(file);
}
if (hasPrimitiveValues(from, context))
{
if (context.hasRun)
{
if (toml != null)
{
if (!toml.getValues().containsKey(context.key))
{
context.writeKey();
}
}
else
{
context.writeKey();
}
}
}
// Render primitive types and arrays of primitive first so they are
// grouped under the same table (if there is one)
for (Map.Entry<?, ?> entry : from.entrySet())
{
Object key = entry.getKey();
Object fromValue = entry.getValue();
if (fromValue == null)
{
continue;
}
if (context.hasRun && toml != null)
{
if (context.key != null)
{
if (key.toString().equalsIgnoreCase(context.key))
{
continue;
}
if (toml.contains(context.key + "." + key))
{
continue;
}
}
}
dev.plex.toml.ValueWriter valueWriter = dev.plex.toml.ValueWriters.WRITERS.findWriterFor(fromValue);
if (valueWriter.isPrimitiveType())
{
context.indent();
context.write(quoteKey(key)).write(" = ");
valueWriter.write(fromValue, context);
context.write('\n');
}
else if (valueWriter == dev.plex.toml.PrimitiveArrayValueWriter.PRIMITIVE_ARRAY_VALUE_WRITER)
{
context.indent();
context.setArrayKey(key.toString());
context.write(quoteKey(key)).write(" = ");
valueWriter.write(fromValue, context);
context.write('\n');
}
}
// Now render (sub)tables and arrays of tables
for (Object key : from.keySet())
{
Object fromValue = from.get(key);
if (fromValue == null)
{
continue;
}
if (context.hasRun && toml != null)
{
if (context.key != null)
{
if (key.toString().equalsIgnoreCase(context.key))
{
continue;
}
if (toml.contains(context.key + "." + key))
{
continue;
}
}
}
dev.plex.toml.ValueWriter valueWriter = dev.plex.toml.ValueWriters.WRITERS.findWriterFor(fromValue);
if (valueWriter == this || valueWriter == dev.plex.toml.ObjectValueWriter.OBJECT_VALUE_WRITER || valueWriter == dev.plex.toml.TableArrayValueWriter.TABLE_ARRAY_VALUE_WRITER)
{
WriterContext context1 = context.pushTable(quoteKey(key));
context1.parentName = key.toString();
context1.hasRun = true;
context1.file = context.file;
valueWriter.write(fromValue, context1);
}
}
}
@Override
public boolean isPrimitiveType()
{
return false;
}
private static String quoteKey(Object key)
{
String stringKey = key.toString();
Matcher matcher = REQUIRED_QUOTING_PATTERN.matcher(stringKey);
if (matcher.matches())
{
stringKey = "\"" + stringKey + "\"";
}
return stringKey;
}
private static boolean hasPrimitiveValues(Map<?, ?> values, WriterContext context)
{
for (Object key : values.keySet())
{
Object fromValue = values.get(key);
if (fromValue == null)
{
continue;
}
dev.plex.toml.ValueWriter valueWriter = dev.plex.toml.ValueWriters.WRITERS.findWriterFor(fromValue);
if (valueWriter.isPrimitiveType() || valueWriter == dev.plex.toml.PrimitiveArrayValueWriter.PRIMITIVE_ARRAY_VALUE_WRITER)
{
return true;
}
}
return false;
}
private MapValueWriter()
{
}
}

View File

@ -0,0 +1,61 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
class MultilineLiteralStringValueReader implements ValueReader
{
static final MultilineLiteralStringValueReader MULTILINE_LITERAL_STRING_VALUE_READER = new MultilineLiteralStringValueReader();
@Override
public boolean canRead(String s)
{
return s.startsWith("'''");
}
@Override
public Object read(String s, AtomicInteger index, Context context)
{
AtomicInteger line = context.line;
int startLine = line.get();
int originalStartIndex = index.get();
int startIndex = index.addAndGet(3);
int endIndex = -1;
if (s.charAt(startIndex) == '\n')
{
startIndex = index.incrementAndGet();
line.incrementAndGet();
}
for (int i = startIndex; i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
if (c == '\n')
{
line.incrementAndGet();
}
if (c == '\'' && s.length() > i + 2 && s.charAt(i + 1) == '\'' && s.charAt(i + 2) == '\'')
{
endIndex = i;
index.addAndGet(2);
break;
}
}
if (endIndex == -1)
{
Results.Errors errors = new Results.Errors();
errors.unterminated(context.identifier.getName(), s.substring(originalStartIndex), startLine);
return errors;
}
return s.substring(startIndex, endIndex);
}
private MultilineLiteralStringValueReader()
{
}
}

View File

@ -0,0 +1,66 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
class MultilineStringValueReader implements ValueReader
{
static final MultilineStringValueReader MULTILINE_STRING_VALUE_READER = new MultilineStringValueReader();
@Override
public boolean canRead(String s)
{
return s.startsWith("\"\"\"");
}
@Override
public Object read(String s, AtomicInteger index, dev.plex.toml.Context context)
{
AtomicInteger line = context.line;
int startLine = line.get();
int originalStartIndex = index.get();
int startIndex = index.addAndGet(3);
int endIndex = -1;
if (s.charAt(startIndex) == '\n')
{
startIndex = index.incrementAndGet();
line.incrementAndGet();
}
for (int i = startIndex; i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
if (c == '\n')
{
line.incrementAndGet();
}
else if (c == '"' && s.length() > i + 2 && s.charAt(i + 1) == '"' && s.charAt(i + 2) == '"')
{
endIndex = i;
index.addAndGet(2);
break;
}
}
if (endIndex == -1)
{
dev.plex.toml.Results.Errors errors = new dev.plex.toml.Results.Errors();
errors.unterminated(context.identifier.getName(), s.substring(originalStartIndex), startLine);
return errors;
}
s = s.substring(startIndex, endIndex);
s = s.replaceAll("\\\\\\s+", "");
s = dev.plex.toml.StringValueReaderWriter.STRING_VALUE_READER_WRITER.replaceUnicodeCharacters(s);
s = dev.plex.toml.StringValueReaderWriter.STRING_VALUE_READER_WRITER.replaceSpecialCharacters(s);
return s;
}
private MultilineStringValueReader()
{
}
}

View File

@ -0,0 +1,134 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
class NumberValueReaderWriter implements dev.plex.toml.ValueReader, dev.plex.toml.ValueWriter
{
static final NumberValueReaderWriter NUMBER_VALUE_READER_WRITER = new NumberValueReaderWriter();
@Override
public boolean canRead(String s)
{
char firstChar = s.charAt(0);
return firstChar == '+' || firstChar == '-' || Character.isDigit(firstChar);
}
@Override
public Object read(String s, AtomicInteger index, dev.plex.toml.Context context)
{
boolean signable = true;
boolean dottable = false;
boolean exponentable = false;
boolean terminatable = false;
boolean underscorable = false;
String type = "";
StringBuilder sb = new StringBuilder();
for (int i = index.get(); i < s.length(); i = index.incrementAndGet())
{
char c = s.charAt(i);
boolean notLastChar = s.length() > i + 1;
if (Character.isDigit(c))
{
sb.append(c);
signable = false;
terminatable = true;
if (type.isEmpty())
{
type = "integer";
dottable = true;
}
underscorable = notLastChar;
exponentable = !type.equals("exponent");
}
else if ((c == '+' || c == '-') && signable && notLastChar)
{
signable = false;
terminatable = false;
if (c == '-')
{
sb.append('-');
}
}
else if (c == '.' && dottable && notLastChar)
{
sb.append('.');
type = "float";
terminatable = false;
dottable = false;
exponentable = false;
underscorable = false;
}
else if ((c == 'E' || c == 'e') && exponentable && notLastChar)
{
sb.append('E');
type = "exponent";
terminatable = false;
signable = true;
dottable = false;
exponentable = false;
underscorable = false;
}
else if (c == '_' && underscorable && notLastChar && Character.isDigit(s.charAt(i + 1)))
{
underscorable = false;
}
else
{
if (!terminatable)
{
type = "";
}
index.decrementAndGet();
break;
}
}
if (type.equals("integer"))
{
return Long.valueOf(sb.toString());
}
else if (type.equals("float"))
{
return Double.valueOf(sb.toString());
}
else if (type.equals("exponent"))
{
String[] exponentString = sb.toString().split("E");
return Double.parseDouble(exponentString[0]) * Math.pow(10, Double.parseDouble(exponentString[1]));
}
else
{
dev.plex.toml.Results.Errors errors = new dev.plex.toml.Results.Errors();
errors.invalidValue(context.identifier.getName(), sb.toString(), context.line.get());
return errors;
}
}
@Override
public boolean canWrite(Object value)
{
return value instanceof Number;
}
@Override
public void write(Object value, dev.plex.toml.WriterContext context)
{
context.write(value.toString());
}
@Override
public boolean isPrimitiveType()
{
return true;
}
@Override
public String toString()
{
return "number";
}
}

View File

@ -0,0 +1,91 @@
package dev.plex.toml;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
class ObjectValueWriter implements ValueWriter
{
static final ValueWriter OBJECT_VALUE_WRITER = new ObjectValueWriter();
@Override
public boolean canWrite(Object value)
{
return true;
}
@Override
public void write(Object value, WriterContext context)
{
Map<String, Object> to = new LinkedHashMap<String, Object>();
Set<Field> fields = getFields(value.getClass());
for (Field field : fields)
{
if (field.isAnnotationPresent(SerializedName.class))
{
to.put(field.getDeclaredAnnotation(SerializedName.class).value(), getFieldValue(field, value));
}
else
{
to.put(field.getName(), getFieldValue(field, value));
}
}
MapValueWriter.MAP_VALUE_WRITER.write(to, context);
}
@Override
public boolean isPrimitiveType()
{
return false;
}
private static Set<Field> getFields(Class<?> cls)
{
Set<Field> fields = new LinkedHashSet<Field>(Arrays.asList(cls.getDeclaredFields()));
while (cls != Object.class)
{
fields.addAll(Arrays.asList(cls.getDeclaredFields()));
cls = cls.getSuperclass();
}
removeConstantsAndSyntheticFields(fields);
return fields;
}
private static void removeConstantsAndSyntheticFields(Set<Field> fields)
{
Iterator<Field> iterator = fields.iterator();
while (iterator.hasNext())
{
Field field = iterator.next();
if ((Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) || field.isSynthetic() || Modifier.isTransient(field.getModifiers()))
{
iterator.remove();
}
}
}
private static Object getFieldValue(Field field, Object o)
{
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
Object value = null;
try
{
value = field.get(o);
}
catch (IllegalAccessException ignored)
{
}
field.setAccessible(isAccessible);
return value;
}
private ObjectValueWriter()
{
}
}

View File

@ -0,0 +1,63 @@
package dev.plex.toml;
import java.util.Collection;
class PrimitiveArrayValueWriter extends ArrayValueWriter
{
static final ValueWriter PRIMITIVE_ARRAY_VALUE_WRITER = new PrimitiveArrayValueWriter();
@Override
public boolean canWrite(Object value)
{
return isArrayish(value) && isArrayOfPrimitive(value);
}
@Override
public void write(Object o, WriterContext context)
{
Collection<?> values = normalize(o);
context.write('[');
context.writeArrayDelimiterPadding();
boolean first = true;
ValueWriter firstWriter = null;
for (Object value : values)
{
if (first)
{
firstWriter = ValueWriters.WRITERS.findWriterFor(value);
first = false;
}
else
{
ValueWriter writer = ValueWriters.WRITERS.findWriterFor(value);
if (writer != firstWriter)
{
throw new IllegalStateException(
context.getContextPath() +
": cannot write a heterogeneous array; first element was of type " + firstWriter +
" but found " + writer
);
}
context.write(", ");
}
ValueWriters.WRITERS.findWriterFor(value).write(value, context);
}
context.writeArrayDelimiterPadding();
context.write(']');
}
private PrimitiveArrayValueWriter()
{
}
@Override
public String toString()
{
return "primitive-array";
}
}

View File

@ -0,0 +1,356 @@
package dev.plex.toml;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
class Results
{
static class Errors
{
private final StringBuilder sb = new StringBuilder();
void duplicateTable(String table, int line)
{
sb.append("Duplicate table definition on line ")
.append(line)
.append(": [")
.append(table)
.append("]");
}
public void tableDuplicatesKey(String table, AtomicInteger line)
{
sb.append("Key already exists for table defined on line ")
.append(line.get())
.append(": [")
.append(table)
.append("]");
}
public void keyDuplicatesTable(String key, AtomicInteger line)
{
sb.append("Table already exists for key defined on line ")
.append(line.get())
.append(": ")
.append(key);
}
void emptyImplicitTable(String table, int line)
{
sb.append("Invalid table definition due to empty implicit table name: ")
.append(table);
}
void invalidTable(String table, int line)
{
sb.append("Invalid table definition on line ")
.append(line)
.append(": ")
.append(table)
.append("]");
}
void duplicateKey(String key, int line)
{
sb.append("Duplicate key");
if (line > -1)
{
sb.append(" on line ")
.append(line);
}
sb.append(": ")
.append(key);
}
void invalidTextAfterIdentifier(dev.plex.toml.Identifier identifier, char text, int line)
{
sb.append("Invalid text after key ")
.append(identifier.getName())
.append(" on line ")
.append(line)
.append(". Make sure to terminate the value or add a comment (#).");
}
void invalidKey(String key, int line)
{
sb.append("Invalid key on line ")
.append(line)
.append(": ")
.append(key);
}
void invalidTableArray(String tableArray, int line)
{
sb.append("Invalid table array definition on line ")
.append(line)
.append(": ")
.append(tableArray);
}
void invalidValue(String key, String value, int line)
{
sb.append("Invalid value on line ")
.append(line)
.append(": ")
.append(key)
.append(" = ")
.append(value);
}
void unterminatedKey(String key, int line)
{
sb.append("Key is not followed by an equals sign on line ")
.append(line)
.append(": ")
.append(key);
}
void unterminated(String key, String value, int line)
{
sb.append("Unterminated value on line ")
.append(line)
.append(": ")
.append(key)
.append(" = ")
.append(value.trim());
}
public void heterogenous(String key, int line)
{
sb.append(key)
.append(" becomes a heterogeneous array on line ")
.append(line);
}
boolean hasErrors()
{
return sb.length() > 0;
}
@Override
public String toString()
{
return sb.toString();
}
public void add(Errors other)
{
sb.append(other.sb);
}
}
final Errors errors = new Errors();
private final Set<String> tables = new HashSet<String>();
private final Deque<Container> stack = new ArrayDeque<Container>();
Results()
{
stack.push(new Container.Table(""));
}
void addValue(String key, Object value, AtomicInteger line)
{
Container currentTable = stack.peek();
if (value instanceof Map)
{
String path = getInlineTablePath(key);
if (path == null)
{
startTable(key, line);
}
else if (path.isEmpty())
{
startTables(dev.plex.toml.Identifier.from(key, null), line);
}
else
{
startTables(dev.plex.toml.Identifier.from(path, null), line);
}
@SuppressWarnings("unchecked")
Map<String, Object> valueMap = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : valueMap.entrySet())
{
addValue(entry.getKey(), entry.getValue(), line);
}
stack.pop();
}
else if (currentTable.accepts(key))
{
currentTable.put(key, value);
}
else
{
if (currentTable.get(key) instanceof Container)
{
errors.keyDuplicatesTable(key, line);
}
else
{
errors.duplicateKey(key, line != null ? line.get() : -1);
}
}
}
void startTableArray(dev.plex.toml.Identifier identifier, AtomicInteger line)
{
String tableName = identifier.getBareName();
while (stack.size() > 1)
{
stack.pop();
}
dev.plex.toml.Keys.Key[] tableParts = dev.plex.toml.Keys.split(tableName);
for (int i = 0; i < tableParts.length; i++)
{
String tablePart = tableParts[i].name;
Container currentContainer = stack.peek();
if (currentContainer.get(tablePart) instanceof Container.TableArray)
{
Container.TableArray currentTableArray = (Container.TableArray) currentContainer.get(tablePart);
stack.push(currentTableArray);
if (i == tableParts.length - 1)
{
currentTableArray.put(tablePart, new Container.Table());
}
stack.push(currentTableArray.getCurrent());
currentContainer = stack.peek();
}
else if (currentContainer.get(tablePart) instanceof Container.Table && i < tableParts.length - 1)
{
Container nextTable = (Container) currentContainer.get(tablePart);
stack.push(nextTable);
}
else if (currentContainer.accepts(tablePart))
{
Container newContainer = i == tableParts.length - 1 ? new Container.TableArray() : new Container.Table();
addValue(tablePart, newContainer, line);
stack.push(newContainer);
if (newContainer instanceof Container.TableArray)
{
stack.push(((Container.TableArray) newContainer).getCurrent());
}
}
else
{
errors.duplicateTable(tableName, line.get());
break;
}
}
}
void startTables(dev.plex.toml.Identifier id, AtomicInteger line)
{
String tableName = id.getBareName();
while (stack.size() > 1)
{
stack.pop();
}
dev.plex.toml.Keys.Key[] tableParts = dev.plex.toml.Keys.split(tableName);
for (int i = 0; i < tableParts.length; i++)
{
String tablePart = tableParts[i].name;
Container currentContainer = stack.peek();
if (currentContainer.get(tablePart) instanceof Container)
{
Container nextTable = (Container) currentContainer.get(tablePart);
if (i == tableParts.length - 1 && !nextTable.isImplicit())
{
errors.duplicateTable(tableName, line.get());
return;
}
stack.push(nextTable);
if (stack.peek() instanceof Container.TableArray)
{
stack.push(((Container.TableArray) stack.peek()).getCurrent());
}
}
else if (currentContainer.accepts(tablePart))
{
startTable(tablePart, i < tableParts.length - 1, line);
}
else
{
errors.tableDuplicatesKey(tablePart, line);
break;
}
}
}
/**
* Warning: After this method has been called, this instance is no longer usable.
*/
Map<String, Object> consume()
{
Container values = stack.getLast();
stack.clear();
return ((Container.Table) values).consume();
}
private Container startTable(String tableName, AtomicInteger line)
{
Container newTable = new Container.Table(tableName);
addValue(tableName, newTable, line);
stack.push(newTable);
return newTable;
}
private Container startTable(String tableName, boolean implicit, AtomicInteger line)
{
Container newTable = new Container.Table(tableName, implicit);
addValue(tableName, newTable, line);
stack.push(newTable);
return newTable;
}
private String getInlineTablePath(String key)
{
Iterator<Container> descendingIterator = stack.descendingIterator();
StringBuilder sb = new StringBuilder();
while (descendingIterator.hasNext())
{
Container next = descendingIterator.next();
if (next instanceof Container.TableArray)
{
return null;
}
Container.Table table = (Container.Table) next;
if (table.name == null)
{
break;
}
if (sb.length() > 0)
{
sb.append('.');
}
sb.append(table.name);
}
if (sb.length() > 0)
{
sb.append('.');
}
sb.append(key)
.insert(0, '[')
.append(']');
return sb.toString();
}
}

View File

@ -0,0 +1,154 @@
package dev.plex.toml;
import java.net.URI;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class StringValueReaderWriter implements ValueReader, ValueWriter
{
static final StringValueReaderWriter STRING_VALUE_READER_WRITER = new StringValueReaderWriter();
private static final Pattern UNICODE_REGEX = Pattern.compile("\\\\[uU](.{4})");
static private final String[] specialCharacterEscapes = new String[93];
static
{
specialCharacterEscapes['\b'] = "\\b";
specialCharacterEscapes['\t'] = "\\t";
specialCharacterEscapes['\n'] = "\\n";
specialCharacterEscapes['\f'] = "\\f";
specialCharacterEscapes['\r'] = "\\r";
specialCharacterEscapes['"'] = "\\\"";
specialCharacterEscapes['\\'] = "\\\\";
}
@Override
public boolean canRead(String s)
{
return s.startsWith("\"");
}
@Override
public Object read(String s, AtomicInteger index, Context context)
{
int startIndex = index.incrementAndGet();
int endIndex = -1;
for (int i = index.get(); i < s.length(); i = index.incrementAndGet())
{
char ch = s.charAt(i);
if (ch == '"' && s.charAt(i - 1) != '\\')
{
endIndex = i;
break;
}
}
if (endIndex == -1)
{
Results.Errors errors = new Results.Errors();
errors.unterminated(context.identifier.getName(), s.substring(startIndex - 1), context.line.get());
return errors;
}
String raw = s.substring(startIndex, endIndex);
s = replaceUnicodeCharacters(raw);
s = replaceSpecialCharacters(s);
if (s == null)
{
Results.Errors errors = new Results.Errors();
errors.invalidValue(context.identifier.getName(), raw, context.line.get());
return errors;
}
return s;
}
String replaceUnicodeCharacters(String value)
{
Matcher unicodeMatcher = UNICODE_REGEX.matcher(value);
while (unicodeMatcher.find())
{
value = value.replace(unicodeMatcher.group(), new String(Character.toChars(Integer.parseInt(unicodeMatcher.group(1), 16))));
}
return value;
}
String replaceSpecialCharacters(String s)
{
for (int i = 0; i < s.length() - 1; i++)
{
char ch = s.charAt(i);
char next = s.charAt(i + 1);
if (ch == '\\' && next == '\\')
{
i++;
}
else if (ch == '\\' && !(next == 'b' || next == 'f' || next == 'n' || next == 't' || next == 'r' || next == '"' || next == '\\'))
{
return null;
}
}
return s.replace("\\n", "\n")
.replace("\\\"", "\"")
.replace("\\t", "\t")
.replace("\\r", "\r")
.replace("\\\\", "\\")
.replace("\\/", "/")
.replace("\\b", "\b")
.replace("\\f", "\f");
}
@Override
public boolean canWrite(Object value)
{
return value instanceof String || value instanceof Character || value instanceof URL || value instanceof URI || value instanceof Enum;
}
@Override
public void write(Object value, WriterContext context)
{
context.write('"');
escapeUnicode(value.toString(), context);
context.write('"');
}
@Override
public boolean isPrimitiveType()
{
return true;
}
private void escapeUnicode(String in, WriterContext context)
{
for (int i = 0; i < in.length(); i++)
{
int codePoint = in.codePointAt(i);
if (codePoint < specialCharacterEscapes.length && specialCharacterEscapes[codePoint] != null)
{
context.write(specialCharacterEscapes[codePoint]);
}
else
{
context.write(in.charAt(i));
}
}
}
private StringValueReaderWriter()
{
}
@Override
public String toString()
{
return "string";
}
}

View File

@ -0,0 +1,39 @@
package dev.plex.toml;
import java.util.Collection;
import static dev.plex.toml.ValueWriters.WRITERS;
class TableArrayValueWriter extends ArrayValueWriter
{
static final ValueWriter TABLE_ARRAY_VALUE_WRITER = new TableArrayValueWriter();
@Override
public boolean canWrite(Object value)
{
return isArrayish(value) && !isArrayOfPrimitive(value);
}
@Override
public void write(Object from, WriterContext context)
{
Collection<?> values = normalize(from);
WriterContext subContext = context.pushTableFromArray();
for (Object value : values)
{
WRITERS.findWriterFor(value).write(value, subContext);
}
}
private TableArrayValueWriter()
{
}
@Override
public String toString()
{
return "table-array";
}
}

View File

@ -0,0 +1,489 @@
package dev.plex.toml;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import lombok.Getter;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* <p>Provides access to the keys and tables in a TOML data source.</p>
*
* <p>All getters can fall back to default values if they have been provided as a constructor argument.
* Getters for simple values (String, Date, etc.) will return null if no matching key exists.
* {@link #getList(String)}, {@link #getTable(String)} and {@link #getTables(String)} return empty values if there is no matching key.</p>
*
* <p>All read methods throw an {@link IllegalStateException} if the TOML is incorrect.</p>
*
* <p>Example usage:</p>
* <pre><code>
* Toml toml = new Toml().read(getTomlFile());
* String name = toml.getString("name");
* Long port = toml.getLong("server.ip"); // compound key. Is equivalent to:
* Long port2 = toml.getTable("server").getLong("ip");
* MyConfig config = toml.to(MyConfig.class);
* </code></pre>
*/
public class Toml
{
private static final Gson DEFAULT_GSON = new Gson();
@Getter
private Map<String, Object> values = new HashMap<String, Object>();
private final Toml defaults;
/**
* Creates Toml instance with no defaults.
*/
public Toml()
{
this(null);
}
/**
* @param defaults fallback values used when the requested key or table is not present in the TOML source that has been read.
*/
public Toml(Toml defaults)
{
this(defaults, new HashMap<>());
}
/**
* Populates the current Toml instance with values from file.
*
* @param file The File to be read. Expected to be encoded as UTF-8.
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml read(File file)
{
try
{
return read(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Populates the current Toml instance with values from inputStream.
*
* @param inputStream Closed after it has been read.
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml read(InputStream inputStream)
{
return read(new InputStreamReader(inputStream));
}
/**
* Populates the current Toml instance with values from reader.
*
* @param reader Closed after it has been read.
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml read(Reader reader)
{
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(reader);
StringBuilder w = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null)
{
w.append(line).append('\n');
line = bufferedReader.readLine();
}
read(w.toString());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
}
}
return this;
}
/**
* Populates the current Toml instance with values from otherToml.
*
* @param otherToml
* @return this instance
*/
public Toml read(Toml otherToml)
{
this.values = otherToml.values;
return this;
}
/**
* Populates the current Toml instance with values from tomlString.
*
* @param tomlString String to be read.
* @return this instance
* @throws IllegalStateException If tomlString is not valid TOML
*/
public Toml read(String tomlString) throws IllegalStateException
{
dev.plex.toml.Results results = dev.plex.toml.TomlParser.run(tomlString);
if (results.errors.hasErrors())
{
throw new IllegalStateException(results.errors.toString());
}
this.values = results.consume();
return this;
}
public String getString(String key)
{
return (String) get(key);
}
public String getString(String key, String defaultValue)
{
String val = getString(key);
return val == null ? defaultValue : val;
}
public Long getLong(String key)
{
return (Long) get(key);
}
public Long getLong(String key, Long defaultValue)
{
Long val = getLong(key);
return val == null ? defaultValue : val;
}
/**
* @param key a TOML key
* @param <T> type of list items
* @return <code>null</code> if the key is not found
*/
public <T> List<T> getList(String key)
{
@SuppressWarnings("unchecked")
List<T> list = (List<T>) get(key);
return list;
}
/**
* @param key a TOML key
* @param defaultValue a list of default values
* @param <T> type of list items
* @return <code>null</code> is the key is not found
*/
public <T> List<T> getList(String key, List<T> defaultValue)
{
List<T> list = getList(key);
return list != null ? list : defaultValue;
}
public Boolean getBoolean(String key)
{
return (Boolean) get(key);
}
public Boolean getBoolean(String key, Boolean defaultValue)
{
Boolean val = getBoolean(key);
return val == null ? defaultValue : val;
}
public Date getDate(String key)
{
return (Date) get(key);
}
public Date getDate(String key, Date defaultValue)
{
Date val = getDate(key);
return val == null ? defaultValue : val;
}
public Double getDouble(String key)
{
return (Double) get(key);
}
public Double getDouble(String key, Double defaultValue)
{
Double val = getDouble(key);
return val == null ? defaultValue : val;
}
/**
* @param key A table name, not including square brackets.
* @return A new Toml instance or <code>null</code> if no value is found for key.
*/
@SuppressWarnings("unchecked")
public Toml getTable(String key)
{
Map<String, Object> map = (Map<String, Object>) get(key);
return map != null ? new Toml(null, map) : null;
}
/**
* @param key Name of array of tables, not including square brackets.
* @return A {@link List} of Toml instances or <code>null</code> if no value is found for key.
*/
@SuppressWarnings("unchecked")
public List<Toml> getTables(String key)
{
List<Map<String, Object>> tableArray = (List<Map<String, Object>>) get(key);
if (tableArray == null)
{
return null;
}
ArrayList<Toml> tables = new ArrayList<Toml>();
for (Map<String, Object> table : tableArray)
{
tables.add(new Toml(null, table));
}
return tables;
}
/**
* @param key a key name, can be compound (eg. a.b.c)
* @return true if key is present
*/
public boolean contains(String key)
{
return get(key) != null;
}
/**
* @param key a key name, can be compound (eg. a.b.c)
* @return true if key is present and is a primitive
*/
public boolean containsPrimitive(String key)
{
Object object = get(key);
return object != null && !(object instanceof Map) && !(object instanceof List);
}
/**
* @param key a key name, can be compound (eg. a.b.c)
* @return true if key is present and is a table
*/
public boolean containsTable(String key)
{
Object object = get(key);
return object != null && (object instanceof Map);
}
/**
* @param key a key name, can be compound (eg. a.b.c)
* @return true if key is present and is a table array
*/
public boolean containsTableArray(String key)
{
Object object = get(key);
return object != null && (object instanceof List);
}
public boolean isEmpty()
{
return values.isEmpty();
}
/**
* <p>
* Populates an instance of targetClass with the values of this Toml instance.
* The target's field names must match keys or tables.
* Keys not present in targetClass will be ignored.
* </p>
*
* <p>Tables are recursively converted to custom classes or to {@link Map Map&lt;String, Object&gt;}.</p>
*
* <p>In addition to straight-forward conversion of TOML primitives, the following are also available:</p>
*
* <ul>
* <li>Integer -&gt; int, long (or wrapper), {@link java.math.BigInteger}</li>
* <li>Float -&gt; float, double (or wrapper), {@link java.math.BigDecimal}</li>
* <li>One-letter String -&gt; char, {@link Character}</li>
* <li>String -&gt; {@link String}, enum, {@link java.net.URI}, {@link java.net.URL}</li>
* <li>Multiline and Literal Strings -&gt; {@link String}</li>
* <li>Array -&gt; {@link List}, {@link Set}, array. The generic type can be anything that can be converted.</li>
* <li>Table -&gt; Custom class, {@link Map Map&lt;String, Object&gt;}</li>
* </ul>
*
* @param targetClass Class to deserialize TOML to.
* @param <T> type of targetClass.
* @return A new instance of targetClass.
*/
public <T> T to(Class<T> targetClass)
{
JsonElement json = DEFAULT_GSON.toJsonTree(toMap());
if (targetClass == JsonElement.class)
{
return targetClass.cast(json);
}
return DEFAULT_GSON.fromJson(json, targetClass);
}
public Map<String, Object> toMap()
{
HashMap<String, Object> valuesCopy = new HashMap<String, Object>(values);
if (defaults != null)
{
for (Map.Entry<String, Object> entry : defaults.values.entrySet())
{
if (!valuesCopy.containsKey(entry.getKey()))
{
valuesCopy.put(entry.getKey(), entry.getValue());
}
}
}
return valuesCopy;
}
/**
* @return a {@link Set} of Map.Entry instances. Modifications to the {@link Set} are not reflected in this Toml instance. Entries are immutable, so {@link Map.Entry#setValue(Object)} throws an UnsupportedOperationException.
*/
public Set<Map.Entry<String, Object>> entrySet()
{
Set<Map.Entry<String, Object>> entries = new LinkedHashSet<Map.Entry<String, Object>>();
for (Map.Entry<String, Object> entry : values.entrySet())
{
Class<? extends Object> entryClass = entry.getValue().getClass();
if (Map.class.isAssignableFrom(entryClass))
{
entries.add(new Entry(entry.getKey(), getTable(entry.getKey())));
}
else if (List.class.isAssignableFrom(entryClass))
{
List<?> value = (List<?>) entry.getValue();
if (!value.isEmpty() && value.get(0) instanceof Map)
{
entries.add(new Entry(entry.getKey(), getTables(entry.getKey())));
}
else
{
entries.add(new Entry(entry.getKey(), value));
}
}
else
{
entries.add(new Entry(entry.getKey(), entry.getValue()));
}
}
return entries;
}
private class Entry implements Map.Entry<String, Object>
{
private final String key;
private final Object value;
@Override
public String getKey()
{
return key;
}
@Override
public Object getValue()
{
return value;
}
@Override
public Object setValue(Object value)
{
throw new UnsupportedOperationException("TOML entry values cannot be changed.");
}
private Entry(String key, Object value)
{
this.key = key;
this.value = value;
}
}
@SuppressWarnings("unchecked")
public Object get(String key)
{
if (values.containsKey(key))
{
return values.get(key);
}
Object current = new HashMap<>(values);
dev.plex.toml.Keys.Key[] keys = dev.plex.toml.Keys.split(key);
for (dev.plex.toml.Keys.Key k : keys)
{
if (k.index == -1 && current instanceof Map && ((Map<String, Object>) current).containsKey(k.path))
{
return ((Map<String, Object>) current).get(k.path);
}
current = ((Map<String, Object>) current).get(k.name);
if (k.index > -1 && current != null)
{
if (k.index >= ((List<?>) current).size())
{
return null;
}
current = ((List<?>) current).get(k.index);
}
if (current == null)
{
return defaults != null ? defaults.get(key) : null;
}
}
return current;
}
private Toml(Toml defaults, Map<String, Object> values)
{
this.values = values;
this.defaults = defaults;
}
}

View File

@ -0,0 +1,88 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
class TomlParser
{
static dev.plex.toml.Results run(String tomlString)
{
final dev.plex.toml.Results results = new dev.plex.toml.Results();
if (tomlString.isEmpty())
{
return results;
}
AtomicInteger index = new AtomicInteger();
boolean inComment = false;
AtomicInteger line = new AtomicInteger(1);
dev.plex.toml.Identifier identifier = null;
Object value = null;
for (int i = index.get(); i < tomlString.length(); i = index.incrementAndGet())
{
char c = tomlString.charAt(i);
if (results.errors.hasErrors())
{
break;
}
if (c == '#' && !inComment)
{
inComment = true;
}
else if (!Character.isWhitespace(c) && !inComment && identifier == null)
{
dev.plex.toml.Identifier id = dev.plex.toml.IdentifierConverter.IDENTIFIER_CONVERTER.convert(tomlString, index, new dev.plex.toml.Context(null, line, results.errors));
if (id != dev.plex.toml.Identifier.INVALID)
{
if (id.isKey())
{
identifier = id;
}
else if (id.isTable())
{
results.startTables(id, line);
}
else if (id.isTableArray())
{
results.startTableArray(id, line);
}
}
}
else if (c == '\n')
{
inComment = false;
identifier = null;
value = null;
line.incrementAndGet();
}
else if (!inComment && identifier != null && identifier.isKey() && value == null && !Character.isWhitespace(c))
{
value = ValueReaders.VALUE_READERS.convert(tomlString, index, new dev.plex.toml.Context(identifier, line, results.errors));
if (value instanceof dev.plex.toml.Results.Errors)
{
results.errors.add((dev.plex.toml.Results.Errors) value);
}
else
{
results.addValue(identifier.getName(), value, line);
}
}
else if (value != null && !inComment && !Character.isWhitespace(c))
{
results.errors.invalidTextAfterIdentifier(identifier, c, line.get());
}
}
return results;
}
private TomlParser()
{
}
}

View File

@ -0,0 +1,182 @@
package dev.plex.toml;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import static dev.plex.toml.ValueWriters.WRITERS;
/**
* <p>Converts Objects to TOML</p>
*
* <p>An input Object can comprise arbitrarily nested combinations of Java primitive types,
* other {@link Object}s, {@link Map}s, {@link List}s, and Arrays. {@link Object}s and {@link Map}s
* are output to TOML tables, and {@link List}s and Array to TOML arrays.</p>
*
* <p>Example usage:</p>
* <pre><code>
* class AClass {
* int anInt = 1;
* int[] anArray = { 2, 3 };
* }
*
* String tomlString = new TomlWriter().write(new AClass());
* </code></pre>
*/
public class TomlWriter
{
public static class Builder
{
private int keyIndentation;
private int tableIndentation;
private int arrayDelimiterPadding = 0;
private TimeZone timeZone = TimeZone.getTimeZone("UTC");
private boolean showFractionalSeconds = false;
public Builder indentValuesBy(int spaces)
{
this.keyIndentation = spaces;
return this;
}
public Builder indentTablesBy(int spaces)
{
this.tableIndentation = spaces;
return this;
}
public Builder timeZone(TimeZone timeZone)
{
this.timeZone = timeZone;
return this;
}
/**
* @param spaces number of spaces to put between opening square bracket and first item and between closing square bracket and last item
* @return this TomlWriter.Builder instance
*/
public Builder padArrayDelimitersBy(int spaces)
{
this.arrayDelimiterPadding = spaces;
return this;
}
public TomlWriter build()
{
return new TomlWriter(keyIndentation, tableIndentation, arrayDelimiterPadding, timeZone, showFractionalSeconds);
}
public Builder showFractionalSeconds()
{
this.showFractionalSeconds = true;
return this;
}
}
private final IndentationPolicy indentationPolicy;
private final dev.plex.toml.DatePolicy datePolicy;
/**
* Creates a TomlWriter instance.
*/
public TomlWriter()
{
this(0, 0, 0, TimeZone.getTimeZone("UTC"), false);
}
private TomlWriter(int keyIndentation, int tableIndentation, int arrayDelimiterPadding, TimeZone timeZone, boolean showFractionalSeconds)
{
this.indentationPolicy = new IndentationPolicy(keyIndentation, tableIndentation, arrayDelimiterPadding);
this.datePolicy = new dev.plex.toml.DatePolicy(timeZone, showFractionalSeconds);
}
/**
* Write an Object into TOML String.
*
* @param from the object to be written
* @return a string containing the TOML representation of the given Object
*/
public String write(Object from)
{
try
{
StringWriter output = new StringWriter();
write(from, output, null);
return output.toString();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
/**
* Write an Object in TOML to a {@link File}. Output is encoded as UTF-8.
*
* @param from the object to be written
* @param target the File to which the TOML will be written
* @throws IOException if any file operations fail
*/
public void write(Object from, File target) throws IOException
{
OutputStream outputStream = new FileOutputStream(target, true);
try
{
write(from, outputStream, target);
}
finally
{
outputStream.close();
}
}
/**
* Write an Object in TOML to a {@link OutputStream}. Output is encoded as UTF-8.
*
* @param from the object to be written
* @param target the OutputStream to which the TOML will be written. The stream is NOT closed after being written to.
* @throws IOException if target.write() fails
*/
public void write(Object from, OutputStream target, @Nullable File file) throws IOException
{
OutputStreamWriter writer = new OutputStreamWriter(target, StandardCharsets.UTF_8);
write(from, writer, file);
writer.flush();
}
/**
* Write an Object in TOML to a {@link Writer}. You MUST ensure that the {@link Writer}s's encoding is set to UTF-8 for the TOML to be valid.
*
* @param from the object to be written. Can be a Map or a custom type. Must not be null.
* @param target the Writer to which TOML will be written. The Writer is not closed.
* @throws IOException if target.write() fails
* @throws IllegalArgumentException if from is of an invalid type
*/
public void write(Object from, Writer target, @Nullable File file) throws IOException
{
dev.plex.toml.ValueWriter valueWriter = WRITERS.findWriterFor(from);
if (valueWriter == MapValueWriter.MAP_VALUE_WRITER || valueWriter == dev.plex.toml.ObjectValueWriter.OBJECT_VALUE_WRITER)
{
WriterContext context = new WriterContext(indentationPolicy, datePolicy, target);
if (file != null && file.exists())
{
context.file = file;
}
valueWriter.write(from, context);
}
else
{
throw new IllegalArgumentException("An object of class " + from.getClass().getSimpleName() + " cannot produce valid TOML. Please pass in a Map or a custom type.");
}
}
}

View File

@ -0,0 +1,21 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
interface ValueReader
{
/**
* @param s must already have been trimmed
*/
boolean canRead(String s);
/**
* Partial validation. Stops after type terminator, rather than at EOI.
*
* @param s must already have been validated by {@link #canRead(String)}
* @param index where to start in s
* @return a value or a {@link dev.plex.toml.Results.Errors}
*/
Object read(String s, AtomicInteger index, dev.plex.toml.Context context);
}

View File

@ -0,0 +1,41 @@
package dev.plex.toml;
import java.util.concurrent.atomic.AtomicInteger;
import static dev.plex.toml.ArrayValueReader.ARRAY_VALUE_READER;
import static dev.plex.toml.BooleanValueReaderWriter.BOOLEAN_VALUE_READER_WRITER;
import static dev.plex.toml.DateValueReaderWriter.DATE_VALUE_READER_WRITER;
import static dev.plex.toml.LiteralStringValueReader.LITERAL_STRING_VALUE_READER;
import static dev.plex.toml.MultilineLiteralStringValueReader.MULTILINE_LITERAL_STRING_VALUE_READER;
import static dev.plex.toml.MultilineStringValueReader.MULTILINE_STRING_VALUE_READER;
import static dev.plex.toml.StringValueReaderWriter.STRING_VALUE_READER_WRITER;
class ValueReaders
{
static final ValueReaders VALUE_READERS = new ValueReaders();
Object convert(String value, AtomicInteger index, dev.plex.toml.Context context)
{
String substring = value.substring(index.get());
for (dev.plex.toml.ValueReader valueParser : READERS)
{
if (valueParser.canRead(substring))
{
return valueParser.read(value, index, context);
}
}
dev.plex.toml.Results.Errors errors = new dev.plex.toml.Results.Errors();
errors.invalidValue(context.identifier.getName(), substring, context.line.get());
return errors;
}
private ValueReaders()
{
}
private static final dev.plex.toml.ValueReader[] READERS = {
MULTILINE_STRING_VALUE_READER, MULTILINE_LITERAL_STRING_VALUE_READER, LITERAL_STRING_VALUE_READER, STRING_VALUE_READER_WRITER, DATE_VALUE_READER_WRITER, NumberValueReaderWriter.NUMBER_VALUE_READER_WRITER, BOOLEAN_VALUE_READER_WRITER, ARRAY_VALUE_READER, InlineTableValueReader.INLINE_TABLE_VALUE_READER
};
}

View File

@ -0,0 +1,10 @@
package dev.plex.toml;
interface ValueWriter
{
boolean canWrite(Object value);
void write(Object value, WriterContext context);
boolean isPrimitiveType();
}

View File

@ -0,0 +1,35 @@
package dev.plex.toml;
class ValueWriters
{
static final ValueWriters WRITERS = new ValueWriters();
ValueWriter findWriterFor(Object value)
{
for (ValueWriter valueWriter : VALUE_WRITERS)
{
if (valueWriter.canWrite(value))
{
return valueWriter;
}
}
return ObjectValueWriter.OBJECT_VALUE_WRITER;
}
private ValueWriters()
{
}
private static dev.plex.toml.DateValueReaderWriter getPlatformSpecificDateConverter()
{
String specificationVersion = Runtime.class.getPackage().getSpecificationVersion();
return specificationVersion != null && specificationVersion.startsWith("1.6") ? dev.plex.toml.DateValueReaderWriter.DATE_PARSER_JDK_6 : dev.plex.toml.DateValueReaderWriter.DATE_VALUE_READER_WRITER;
}
private static final ValueWriter[] VALUE_WRITERS = {
StringValueReaderWriter.STRING_VALUE_READER_WRITER, NumberValueReaderWriter.NUMBER_VALUE_READER_WRITER, dev.plex.toml.BooleanValueReaderWriter.BOOLEAN_VALUE_READER_WRITER, getPlatformSpecificDateConverter(),
MapValueWriter.MAP_VALUE_WRITER, dev.plex.toml.PrimitiveArrayValueWriter.PRIMITIVE_ARRAY_VALUE_WRITER, TableArrayValueWriter.TABLE_ARRAY_VALUE_WRITER
};
}

View File

@ -0,0 +1,185 @@
package dev.plex.toml;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
class WriterContext
{
private String arrayKey = null;
private boolean isArrayOfTable = false;
private boolean empty = true;
public final String key;
private final String currentTableIndent;
private final String currentFieldIndent;
private final Writer output;
private final dev.plex.toml.IndentationPolicy indentationPolicy;
private final dev.plex.toml.DatePolicy datePolicy;
public File file;
public String parentName;
public boolean hasRun = false;
WriterContext(dev.plex.toml.IndentationPolicy indentationPolicy, dev.plex.toml.DatePolicy datePolicy, Writer output)
{
this("", "", output, indentationPolicy, datePolicy);
}
WriterContext pushTable(String newKey)
{
String newIndent = "";
if (!key.isEmpty())
{
newIndent = growIndent(indentationPolicy);
}
String fullKey = key.isEmpty() ? newKey : key + "." + newKey;
WriterContext subContext = new WriterContext(fullKey, newIndent, output, indentationPolicy, datePolicy);
if (!empty)
{
subContext.empty = false;
}
return subContext;
}
WriterContext pushTableFromArray()
{
WriterContext subContext = new WriterContext(key, currentTableIndent, output, indentationPolicy, datePolicy);
if (!empty)
{
subContext.empty = false;
}
subContext.setIsArrayOfTable(true);
return subContext;
}
WriterContext write(String s)
{
try
{
output.write(s);
if (empty && !s.isEmpty())
{
empty = false;
}
return this;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
void write(char[] chars)
{
for (char c : chars)
{
write(c);
}
}
WriterContext write(char c)
{
try
{
output.write(c);
empty = false;
return this;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
void writeKey()
{
if (key.isEmpty())
{
return;
}
if (!empty)
{
write('\n');
}
write(currentTableIndent);
if (isArrayOfTable)
{
write("[[").write(key).write("]]\n");
}
else
{
write('[').write(key).write("]\n");
}
}
void writeArrayDelimiterPadding()
{
for (int i = 0; i < indentationPolicy.getArrayDelimiterPadding(); i++)
{
write(' ');
}
}
void indent()
{
if (!key.isEmpty())
{
write(currentFieldIndent);
}
}
dev.plex.toml.DatePolicy getDatePolicy()
{
return datePolicy;
}
WriterContext setIsArrayOfTable(boolean isArrayOfTable)
{
this.isArrayOfTable = isArrayOfTable;
return this;
}
WriterContext setArrayKey(String arrayKey)
{
this.arrayKey = arrayKey;
return this;
}
String getContextPath()
{
return key.isEmpty() ? arrayKey : key + "." + arrayKey;
}
private String growIndent(dev.plex.toml.IndentationPolicy indentationPolicy)
{
return currentTableIndent + fillStringWithSpaces(indentationPolicy.getTableIndent());
}
private String fillStringWithSpaces(int count)
{
char[] chars = new char[count];
Arrays.fill(chars, ' ');
return new String(chars);
}
private WriterContext(String key, String tableIndent, Writer output, dev.plex.toml.IndentationPolicy indentationPolicy, dev.plex.toml.DatePolicy datePolicy)
{
this.key = key;
this.output = output;
this.indentationPolicy = indentationPolicy;
this.currentTableIndent = tableIndent;
this.datePolicy = datePolicy;
this.currentFieldIndent = tableIndent + fillStringWithSpaces(this.indentationPolicy.getKeyValueIndent());
}
}

View File

@ -0,0 +1,66 @@
package dev.plex.util;
import dev.plex.Plex;
import dev.plex.settings.ServerSettings;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
public class PlexLog
{
public static void log(String message, Object... strings)
{
for (int i = 0; i < strings.length; i++)
{
if (message.contains("{" + i + "}"))
{
message = message.replace("{" + i + "}", strings[i].toString());
}
}
Plex.get().getServer().getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize("<yellow>[Plex] <gray>" + message));
}
public static void log(Component component)
{
Plex.get().getServer().getConsoleCommandSource().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++)
{
if (message.contains("{" + i + "}"))
{
message = message.replace("{" + i + "}", strings[i].toString());
}
}
Plex.get().getServer().getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize("<red>[Plex Error] <gold>" + message));
}
public static void warn(String message, Object... strings)
{
for (int i = 0; i < strings.length; i++)
{
if (message.contains("{" + i + "}"))
{
message = message.replace("{" + i + "}", strings[i].toString());
}
}
Plex.get().getServer().getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize("<#eb7c0e>[Plex Warning] <gold>" + message));
}
public static void debug(String message, Object... strings)
{
for (int i = 0; i < strings.length; i++)
{
if (message.contains("{" + i + "}"))
{
message = message.replace("{" + i + "}", strings[i].toString());
}
}
if (Plex.get().getConfig().as(ServerSettings.class).getServer().isDebug())
{
Plex.get().getServer().getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize("<dark_purple>[Plex Debug] <gold>" + message));
}
}
}

View File

@ -0,0 +1,34 @@
package dev.plex.util;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.concurrent.ThreadLocalRandom;
public class RandomUtil
{
public static NamedTextColor getRandomColor()
{
NamedTextColor[] colors = NamedTextColor.NAMES.values().stream().filter(namedTextColor -> namedTextColor != NamedTextColor.BLACK && namedTextColor != NamedTextColor.DARK_BLUE).toArray(NamedTextColor[]::new);
return colors[randomNum(colors.length)];
}
public static boolean randomBoolean()
{
return ThreadLocalRandom.current().nextBoolean();
}
public static int randomNum()
{
return ThreadLocalRandom.current().nextInt();
}
public static int randomNum(int limit)
{
return ThreadLocalRandom.current().nextInt(limit);
}
public static int randomNum(int start, int limit)
{
return ThreadLocalRandom.current().nextInt(start, limit);
}
}

View File

@ -0,0 +1,58 @@
package dev.plex.util;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import dev.plex.Plex;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ReflectionsUtil
{
@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);
}
}

View File

@ -0,0 +1,31 @@
#############################
# #
# Plex Velocity #
# v1.1 #
# #
#############################
[server]
name = "Plexus"
# Placeholders
# %mcversion% - The Velocity Version (i.e. 3.1.2-SNAPSHOT)
# %servername% - The name provided above
# %randomgradient% - Creates a random gradient every ping of two random colors for the whole string
# Supports MiniMessage strings, no legacy & and §
motd = ["%randomgradient%%servername% - %mcversion%", "Another motd"]
colorizeMotd = false
# Enables debug messages
debug = false
# Due to game code only supporting legacy color codes for
# player samples and not components, you may only use § or & here
# for colors.
sample = ["example", "example"]
# Adds this amount to the current player count
add-player-count = 0
# The max player count will always display as +1 more than the player count
plus-one-max-count = true

168
server/build.gradle.kts Normal file
View File

@ -0,0 +1,168 @@
import net.minecrell.pluginyml.paper.PaperPluginDescription
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*
plugins {
id("net.kyori.indra.git") version "3.1.3"
id("net.minecrell.plugin-yml.paper") version "0.6.0"
}
repositories {
maven(url = uri("https://maven.playpro.com"))
maven(url = uri("https://nexus.telesphoreo.me/repository/plex-modules/"))
}
dependencies {
library("org.projectlombok:lombok:1.18.32")
library("org.json:json:20240303")
library("commons-io:commons-io:2.16.1")
library("redis.clients:jedis:5.1.3")
library("org.mariadb.jdbc:mariadb-java-client:3.4.0")
library("com.zaxxer:HikariCP:5.1.0")
library("org.apache.maven.resolver:maven-resolver-transport-http:1.9.20")
library("org.jetbrains:annotations:24.1.0")
compileOnly("dev.folia:folia-api:1.20.4-R0.1-SNAPSHOT")
compileOnly("com.github.MilkBowl:VaultAPI:1.7.1") {
exclude("org.bukkit", "bukkit")
}
compileOnly("net.coreprotect:coreprotect:22.4")
compileOnly("network.darkhelmet.prism:Prism-Api:1.0.0")
implementation("org.bstats:bstats-base:3.0.2")
implementation("org.bstats:bstats-bukkit:3.0.2")
implementation("com.github.LeonMangler:SuperVanish:6.2.18-3")
annotationProcessor("org.projectlombok:lombok:1.18.32")
}
group = rootProject.group
version = rootProject.version
description = "Plex-Server"
paper {
name = "Plex"
version = rootProject.version.toString()
description = "Plex provides a new experience for freedom servers."
main = "dev.plex.Plex"
loader = "dev.plex.PlexLibraryManager"
website = "https://plex.us.org"
authors = listOf("Telesphoreo", "taahanis", "supernt")
apiVersion = "1.19"
foliaSupported = true
generateLibrariesJson = true
// Load BukkitTelnet and LibsDisguises before Plex so the modules register properly
serverDependencies {
register("BukkitTelnet") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("Essentials") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("LibsDisguises") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("Prism") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("CoreProtect") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("PremiumVanish") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("SlimeWorldManager") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.AFTER
}
register("SuperVanish") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("Vault") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
}
}
fun getBuildNumber(): String {
val stdout = ByteArrayOutputStream()
try {
exec {
commandLine("git", "rev-list", "HEAD", "--count")
standardOutput = stdout
isIgnoreExitValue = true
}
} catch (e: GradleException) {
logger.error("Couldn't determine build number because Git is not installed. " + e.message)
}
return if (stdout.size() > 0) stdout.toString().trim() else "unknown"
}
tasks {
build {
dependsOn(shadowJar)
}
jar {
enabled = false
}
sourceSets {
main {
blossom {
resources {
property("author", if (System.getenv("JENKINS_URL") != null) "jenkins" else System.getProperty("user.name"))
property("buildNumber", if (System.getenv("BUILD_NUMBER") != null) System.getenv("BUILD_NUMBER") else getBuildNumber())
property("date", SimpleDateFormat("MM/dd/yyyy '<light_purple>at<gold>' hh:mm:ss a z").format(Date()))
property("gitCommit", indraGit.commit()?.name?.take(7))
}
}
}
}
shadowJar {
archiveBaseName.set("Plex")
archiveClassifier.set("")
relocate("org.bstats", "dev.plex")
finalizedBy(rootProject.tasks["copyJars"])
}
javadoc {
options.memberLevel = JavadocMemberLevel.PRIVATE
}
}
publishing {
publications {
create<MavenPublication>("maven") {
pom.withXml {
val dependenciesNode = asNode().appendNode("dependencies")
configurations.getByName("library").allDependencies.configureEach {
dependenciesNode.appendNode("dependency")
.appendNode("groupId", group).parent()
.appendNode("artifactId", name).parent()
.appendNode("version", version).parent()
.appendNode("scope", "provided").parent()
}
configurations.getByName("implementation").allDependencies.configureEach {
dependenciesNode.appendNode("dependency")
.appendNode("groupId", group).parent()
.appendNode("artifactId", name).parent()
.appendNode("version", version).parent()
.appendNode("scope", "provided").parent()
}
}
artifacts.artifact(tasks.shadowJar)
}
}
}

View File

@ -1,74 +1,71 @@
package dev.plex;
import dev.plex.admin.Admin;
import dev.plex.admin.AdminList;
import dev.plex.cache.DataUtils;
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.cache.PlayerCache;
import dev.plex.config.Config;
import dev.plex.handlers.CommandHandler;
import dev.plex.handlers.ListenerHandler;
import dev.plex.hook.CoreProtectHook;
import dev.plex.hook.PrismHook;
import dev.plex.module.ModuleManager;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.PunishmentManager;
import dev.plex.rank.RankManager;
import dev.plex.services.ServiceManager;
import dev.plex.storage.MongoConnection;
import dev.plex.storage.RedisConnection;
import dev.plex.storage.SQLConnection;
import dev.plex.storage.StorageType;
import dev.plex.storage.player.SQLPlayerData;
import dev.plex.storage.punishment.SQLNotes;
import dev.plex.storage.punishment.SQLPunishment;
import dev.plex.util.BuildInfo;
import dev.plex.util.BungeeUtil;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.UpdateChecker;
import dev.plex.util.redis.MessageUtil;
import dev.plex.world.CustomWorld;
import java.io.File;
import lombok.Getter;
import lombok.Setter;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.permission.Permission;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
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();
public static final BuildInfo build = new BuildInfo();
private static Plex plugin;
public Config config;
public Config messages;
public Config indefBans;
public Config blockedCommands;
public Config commands;
public Config toggles;
public File modulesFolder;
private StorageType storageType = StorageType.SQLITE;
private SQLConnection sqlConnection;
private MongoConnection mongoConnection;
private RedisConnection redisConnection;
private MongoPlayerData mongoPlayerData;
private PlayerCache playerCache;
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;
private Permission permissions;
private Chat chat;
private CoreProtectHook coreProtectHook;
private PrismHook prismHook;
public static Plex get()
{
@ -78,11 +75,13 @@ public class Plex extends JavaPlugin
@Override
public void onLoad()
{
super.onLoad();
plugin = this;
config = new Config(this, "config.yml");
messages = new Config(this, "messages.yml");
indefBans = new Config(this, "indefbans.yml");
blockedCommands = new Config(this, "commands.yml");
commands = new Config(this, "commands.yml");
toggles = new Config(this, "toggles.yml");
build.load(this);
modulesFolder = new File(this.getDataFolder() + File.separator + "modules");
@ -94,6 +93,8 @@ public class Plex extends JavaPlugin
moduleManager = new ModuleManager();
moduleManager.loadAllModules();
moduleManager.loadModules();
//this.setChatHandler(new ChatListener.ChatHandlerImpl());
}
@Override
@ -101,29 +102,63 @@ public class Plex extends JavaPlugin
{
config.load();
messages.load();
// Don't add default entries to indefinite ban file
toggles.load();
// Don't add default entries to these files
indefBans.load(false);
blockedCommands.load();
commands.load(false);
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager.enableModules();
system = config.getString("system");
playerCache = new PlayerCache();
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();
}
if (!getServer().getPluginManager().isPluginEnabled("Vault"))
{
throw new RuntimeException("Vault is required to run on the server alongside a permissions plugin, we recommend LuckPerms!");
}
permissions = setupPermissions();
chat = setupChat();
if (plugin.getServer().getPluginManager().isPluginEnabled("CoreProtect"))
{
PlexLog.log("Hooked into CoreProtect!");
coreProtectHook = new CoreProtectHook(this);
}
else
{
PlexLog.debug("Not hooking into CoreProtect");
}
if (plugin.getServer().getPluginManager().isPluginEnabled("Prism"))
{
PlexLog.log("Hooked into Prism!");
prismHook = new PrismHook(this);
}
else
{
PlexLog.debug("Not hooking into Prism");
}
if (PlexUtils.hasVanishPlugin())
{
PlexLog.log("Hooked into SuperVanish / PremiumVanish!");
} else {
PlexLog.debug("Not hooking into SuperVanish / PremiumVanish");
}
updateChecker = new UpdateChecker();
PlexLog.log("Update checking enabled");
@ -135,38 +170,30 @@ public class Plex extends JavaPlugin
{
redisConnection.getJedis();
PlexLog.log("Connected to Redis!");
} else
MessageUtil.subscribe();
}
else
{
PlexLog.log("Redis is disabled in the configuration file, not connecting.");
}
if (storageType == StorageType.MONGODB)
{
mongoPlayerData = new MongoPlayerData();
} else
{
sqlPlayerData = new SQLPlayerData();
sqlPunishment = new SQLPunishment();
sqlNotes = new SQLNotes();
}
new ListenerHandler();
new CommandHandler();
rankManager = new RankManager();
rankManager.generateDefaultRanks();
rankManager.importDefaultRanks();
adminList = new AdminList();
PlexLog.log("Rank Manager initialized");
punishmentManager = new PunishmentManager();
punishmentManager.mergeIndefiniteBans();
PlexLog.log("Punishment System initialized");
commandBlockerManager = new CommandBlockerManager();
PlexLog.log("Command Blocker initialized");
if (!PlexUtils.isFolia())
{
// World generation is not supported on Folia yet
generateWorlds();
}
serviceManager = new ServiceManager();
PlexLog.log("Service Manager initialized");
@ -174,6 +201,16 @@ public class Plex extends JavaPlugin
PlexLog.log("Started " + serviceManager.serviceCount() + " services.");
reloadPlayers();
PlexLog.debug("Registered Bukkit -> BungeeCord Plugin Messaging Channel");
PlexLog.debug("Velocity Support? " + BungeeUtil.isVelocity());
PlexLog.debug("BungeeCord Support? " + BungeeUtil.isBungeeCord());
if (BungeeUtil.isBungeeCord() && BungeeUtil.isVelocity())
{
PlexLog.warn("It seems you have both velocity and bungeecord configuration options enabled! When running Velocity, you do NOT need to enable bungeecord.");
}
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
moduleManager.enableModules();
}
@Override
@ -181,20 +218,8 @@ public class Plex extends JavaPlugin
{
Bukkit.getOnlinePlayers().forEach(player ->
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId()); //get the player because it's literally impossible for them to not have an object
if (plugin.getRankManager().isAdmin(plexPlayer))
{
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
{
PlexPlayer plexPlayer = playerCache.getPlexPlayerMap().get(player.getUniqueId()); //get the player because it's literally impossible for them to not have an object
sqlPlayerData.update(plexPlayer);
}
});
if (redisConnection != null && redisConnection.isEnabled() && redisConnection.getJedis().isConnected())
{
@ -202,6 +227,8 @@ public class Plex extends JavaPlugin
redisConnection.getJedis().close();
}
this.getServer().getMessenger().unregisterOutgoingPluginChannel(this);
moduleManager.disableModules();
}
@ -220,44 +247,21 @@ public class Plex extends JavaPlugin
Bukkit.getOnlinePlayers().forEach(player ->
{
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
if (plugin.getRankManager().isAdmin(plexPlayer))
{
Admin admin = new Admin(plexPlayer.getUuid());
admin.setRank(plexPlayer.getRankFromString());
plugin.getAdminList().addToCache(admin);
}
playerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
});
}
public static class BuildProperties
private Permission setupPermissions()
{
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);
RegisteredServiceProvider<Permission> rsp = Bukkit.getServicesManager().getRegistration(Permission.class);
permissions = rsp.getProvider();
return permissions;
}
number = props.getProperty("buildNumber", "unknown");
author = props.getProperty("buildAuthor", "unknown");
date = props.getProperty("buildDate", "unknown");
head = props.getProperty("buildHead", "unknown");
} catch (Exception ex)
private Chat setupChat()
{
PlexLog.error("Could not load build properties! Did you compile with NetBeans/Maven?");
}
}
RegisteredServiceProvider<Chat> rsp = Bukkit.getServicesManager().getRegistration(Chat.class);
chat = rsp.getProvider();
return chat;
}
}

View File

@ -0,0 +1,6 @@
package dev.plex;
public interface PlexBase
{
Plex plugin = Plex.get();
}

View File

@ -0,0 +1,65 @@
package dev.plex;
import com.google.gson.Gson;
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
import io.papermc.paper.plugin.loader.PluginLoader;
import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.repository.RemoteRepository;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class PlexLibraryManager implements PluginLoader
{
@Override
public void classloader(@NotNull PluginClasspathBuilder classpathBuilder)
{
MavenLibraryResolver resolver = new MavenLibraryResolver();
PluginLibraries pluginLibraries = load();
pluginLibraries.asDependencies().forEach(resolver::addDependency);
pluginLibraries.asRepositories().forEach(resolver::addRepository);
// The plugin is null, a hacky way to check whether to load Jetty or not
if (new File("plugins/Plex/modules/Module-HTTPD.jar").isFile())
{
resolver.addDependency(new Dependency(new DefaultArtifact("org.eclipse.jetty:jetty-server:11.0.19"), null));
resolver.addDependency(new Dependency(new DefaultArtifact("org.eclipse.jetty:jetty-servlet:11.0.19"), null));
resolver.addDependency(new Dependency(new DefaultArtifact("org.eclipse.jetty:jetty-proxy:11.0.19"), null));
}
classpathBuilder.addLibrary(resolver);
}
public PluginLibraries load()
{
try (var in = getClass().getResourceAsStream("/paper-libraries.json"))
{
return new Gson().fromJson(new InputStreamReader(in, StandardCharsets.UTF_8), PluginLibraries.class);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private record PluginLibraries(Map<String, String> repositories, List<String> dependencies)
{
public Stream<Dependency> asDependencies()
{
return dependencies.stream()
.map(d -> new Dependency(new DefaultArtifact(d), null));
}
public Stream<RemoteRepository> asRepositories()
{
return repositories.entrySet().stream()
.map(e -> new RemoteRepository.Builder(e.getKey(), "default", e.getValue()).build());
}
}
}

View File

@ -0,0 +1,109 @@
package dev.plex.cache;
import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import java.util.Optional;
import java.util.UUID;
/**
* Parent cache class
*/
public class DataUtils
{
/**
* Checks if the player has been on the server before
*
* @param uuid The unique ID of the player
* @return true if the player is registered in the database
*/
public static boolean hasPlayedBefore(UUID uuid)
{
return Plex.get().getSqlPlayerData().exists(uuid);
}
public static boolean hasPlayedBefore(String username)
{
return Plex.get().getSqlPlayerData().exists(username);
}
/**
* Gets a player from cache or from the database
*
* @param uuid The unique ID of the player
* @return a PlexPlayer object
* @see PlexPlayer
*/
public static PlexPlayer getPlayer(UUID uuid)
{
return getPlayer(uuid, true);
}
public static PlexPlayer getPlayer(UUID uuid, boolean loadExtraData)
{
if (Plex.get().getPlayerCache().getPlexPlayerMap().containsKey(uuid))
{
return Plex.get().getPlayerCache().getPlexPlayerMap().get(uuid);
}
return Plex.get().getSqlPlayerData().getByUUID(uuid, loadExtraData);
}
public static PlexPlayer getPlayer(String username)
{
return getPlayer(username, true);
}
public static PlexPlayer getPlayer(String username, boolean loadExtraData)
{
Optional<PlexPlayer> plexPlayer = Plex.get().getPlayerCache().getPlexPlayerMap().values().stream().filter(player -> player.getName().equalsIgnoreCase(username)).findFirst();
if (plexPlayer.isPresent())
{
return plexPlayer.get();
}
return Plex.get().getSqlPlayerData().getByName(username, loadExtraData);
}
/**
* Gets a player from cache or from the database
*
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public static PlexPlayer getPlayerByIP(String ip)
{
PlexPlayer player = Plex.get().getPlayerCache().getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
return Plex.get().getSqlPlayerData().getByIP(ip);
}
/**
* Updates a player's information in the database
*
* @param plexPlayer The PlexPlayer to update
* @see PlexPlayer
*/
public static void update(PlexPlayer plexPlayer)
{
Plex.get().getSqlPlayerData().update(plexPlayer);
}
/**
* Inserts a player's information in the database
*
* @param plexPlayer The PlexPlayer to insert
* @see PlexPlayer
*/
public static void insert(PlexPlayer plexPlayer)
{
Plex.get().getSqlPlayerData().insert(plexPlayer);
}
}

View File

@ -1,7 +1,8 @@
package dev.plex.cache.player;
package dev.plex.cache;
import com.google.common.collect.Maps;
import dev.plex.player.PlexPlayer;
import java.util.Map;
import java.util.UUID;
@ -19,13 +20,13 @@ 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();
// private static final Map<UUID, PunishedPlayer> punishedPlayerMap = Maps.newHashMap();
// public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
// {
// return punishedPlayerMap;
// }
public static Map<UUID, PlexPlayer> getPlexPlayerMap()
// public static Map<UUID, PunishedPlayer> getPunishedPlayerMap()
// {
// return punishedPlayerMap;
// }
public Map<UUID, PlexPlayer> getPlexPlayerMap()
{
return plexPlayerMap;
}
@ -39,7 +40,7 @@ public class PlayerCache
return getPunishedPlayerMap().get(uuid);
}
*/
public static PlexPlayer getPlexPlayer(UUID uuid)
public PlexPlayer getPlexPlayer(UUID uuid)
{
return getPlexPlayerMap().get(uuid);
}

View File

@ -1,30 +1,29 @@
package dev.plex.command;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.player.PlayerCache;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
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 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.*;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
@ -47,11 +46,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
*/
private final CommandPermissions perms;
/**
* Minimum required rank fetched from the permissions
*/
private final Rank level;
/**
* Required command source fetched from the permissions
*/
@ -60,7 +54,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
/**
* Creates an instance of the command
*/
public PlexCommand()
public PlexCommand(boolean register)
{
super("");
this.params = getClass().getAnnotation(CommandParameters.class);
@ -69,16 +63,35 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
setName(this.params.name());
setLabel(this.params.name());
setDescription(params.description());
setPermission(this.perms.permission());
setUsage(params.usage().replace("<command>", this.params.name()));
if (params.aliases().split(",").length > 0)
{
setAliases(Arrays.asList(params.aliases().split(",")));
}
this.level = perms.level();
this.commandSource = perms.source();
if (register)
{
if (getMap().getKnownCommands().containsKey(this.getName().toLowerCase()))
{
getMap().getKnownCommands().remove(this.getName().toLowerCase());
}
this.getAliases().forEach(s ->
{
if (getMap().getKnownCommands().containsKey(s.toLowerCase()))
{
getMap().getKnownCommands().remove(s.toLowerCase());
}
});
getMap().register("plex", this);
}
}
public PlexCommand()
{
this(true);
}
/**
* Executes the command
@ -117,33 +130,27 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
if (sender instanceof Player player)
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
PlexPlayer plexPlayer = plugin.getPlayerCache().getPlexPlayerMap().get(player.getUniqueId());
if (plugin.getSystem().equalsIgnoreCase("ranks"))
if (plexPlayer == null)
{
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;
return false;
}
}
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (!player.hasPermission(perms.permission()))
if (!perms.permission().isEmpty() && !player.hasPermission(perms.permission()))
{
send(sender, messageComponent("noPermissionNode", perms.permission()));
return true;
}
} else
}
if (sender instanceof ConsoleCommandSender && !sender.getName().equalsIgnoreCase("console")) //telnet
{
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");
PlexPlayer plexPlayer = DataUtils.getPlayer(sender.getName());
if (!perms.permission().isEmpty() && !plugin.getPermissions().playerHas(null, Bukkit.getPlayer(plexPlayer.getName()), perms.permission()))
{
send(sender, messageComponent("noPermissionNode", perms.permission()));
return true;
}
}
@ -154,13 +161,26 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
{
send(sender, component);
}
} catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException | ConsoleMustDefinePlayerException | PlayerNotBannedException ex)
}
catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException |
ConsoleMustDefinePlayerException | PlayerNotBannedException | NumberFormatException ex)
{
send(sender, MiniMessage.miniMessage().deserialize(ex.getMessage()));
send(sender, PlexUtils.mmDeserialize(ex.getMessage()));
}
return true;
}
@NotNull
public abstract List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException;
@NotNull
@Override
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
List<String> list = smartTabComplete(sender, alias, args);
return StringUtil.copyPartialMatches(args[args.length - 1], list, Lists.newArrayList());
}
/**
* Checks if the String given is a matching command
*
@ -178,7 +198,8 @@ 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);
}
@ -223,87 +244,31 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
* Checks whether a sender has enough permissions or is high enough a rank
*
* @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)
* @param permission The permission to check
* @return true if the sender has enough permissions
* @see Rank
*/
protected boolean checkRank(CommandSender sender, Rank rank, String permission)
protected boolean checkPermission(CommandSender sender, String permission)
{
if (!isConsole(sender))
{
return checkRank((Player) sender, rank, permission);
return checkPermission((Player) sender, permission);
}
return true;
}
/**
* Checks whether a player has enough permissions or is high enough a rank
*
* @param player The player object
* @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
* @see Rank
*/
protected boolean checkRank(Player player, Rank rank, String permission)
{
if (player instanceof ConsoleCommandSender)
{
return true;
}
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (!plexPlayer.getRankFromString().isAtLeast(rank))
{
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"))
{
if (!player.hasPermission(permission))
{
throw new CommandFailException(PlexUtils.messageString("noPermissionNode", permission));
}
}
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
*
* @param sender The player object
* @param rank The rank to check (if the server is using ranks)
* @param permission The permission to check (if the server is using permissions)
* @param sender A CommandSender
* @param permission The permission to check
* @return true if the sender has enough permissions
* @see Rank
*/
protected boolean checkTab(CommandSender sender, Rank rank, String permission)
protected boolean silentCheckPermission(CommandSender sender, String permission)
{
PlexLog.debug("Checking {0} with {1}", sender.getName(), permission);
if (!isConsole(sender))
{
return checkTab((Player) sender, rank, permission);
return silentCheckPermission((Player) sender, permission);
}
return true;
}
@ -312,78 +277,25 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
* Checks whether a player has enough permissions or is high enough a rank
*
* @param player The player object
* @param rank The rank to check (if the server is using ranks)
* @param permission The permission to check (if the server is using permissions)
* @param permission The permission to check
* @return true if the sender has enough permissions
* @see Rank
*/
protected boolean checkTab(Player player, Rank rank, String permission)
protected boolean checkPermission(Player player, String permission)
{
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
if (player instanceof ConsoleCommandSender)
{
return rank.isAtLeast(Rank.ADMIN) ? plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(rank) : plexPlayer.getRankFromString().isAtLeast(rank);
} else if (plugin.getSystem().equalsIgnoreCase("permissions"))
return true;
}
if (!permission.isEmpty() && !player.hasPermission(permission))
{
return player.hasPermission(permission);
throw new CommandFailException(PlexUtils.messageString("noPermissionNode", permission));
}
return true;
}
/**
* Checks if a player is an admin
*
* @param plexPlayer The PlexPlayer object
* @return true if the player is an admin
* @see PlexPlayer
*/
protected boolean isAdmin(PlexPlayer plexPlayer)
protected boolean silentCheckPermission(Player player, String permission)
{
return Plex.get().getRankManager().isAdmin(plexPlayer);
}
/**
* Checks if a sender is an admin
*
* @param sender A command sender
* @return true if the sender is an admin or if console
*/
protected boolean isAdmin(CommandSender sender)
{
if (!(sender instanceof Player player))
{
return true;
}
PlexPlayer plexPlayer = getPlexPlayer(player);
return plugin.getRankManager().isAdmin(plexPlayer);
}
/**
* Checks if a username is an admin
*
* @param name The username
* @return true if the username is an admin
*/
protected boolean isAdmin(String name)
{
PlexPlayer plexPlayer = DataUtils.getPlayer(name);
return plugin.getRankManager().isAdmin(plexPlayer);
}
/**
* Checks if a sender is a senior admin
*
* @param sender A command sender
* @return true if the sender is a senior admin or if console
*/
protected boolean isSeniorAdmin(CommandSender sender)
{
if (!(sender instanceof Player player))
{
return true;
}
PlexPlayer plexPlayer = getPlexPlayer(player);
return plugin.getRankManager().isSeniorAdmin(plexPlayer);
return !permission.isEmpty() && player.hasPermission(permission);
}
/**
@ -437,6 +349,18 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
return PlexUtils.messageComponent(s, objects);
}
/**
* Converts a message entry from the "messages.yml" to a Component
*
* @param s The message entry
* @param objects Any objects to replace in order
* @return A Kyori Component
*/
protected Component messageComponent(String s, Component... objects)
{
return PlexUtils.messageComponent(s, objects);
}
/**
* Converts a message entry from the "messages.yml" to a String
*
@ -473,6 +397,16 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
protected Player getNonNullPlayer(String name)
{
try
{
UUID uuid = UUID.fromString(name);
return Bukkit.getPlayer(uuid);
}
catch (IllegalArgumentException ignored)
{
}
Player player = Bukkit.getPlayer(name);
if (player == null)
{
@ -484,7 +418,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
protected PlexPlayer getOnlinePlexPlayer(String name)
{
Player player = getNonNullPlayer(name);
PlexPlayer plexPlayer = PlayerCache.getPlexPlayer(player.getUniqueId());
PlexPlayer plexPlayer = plugin.getPlayerCache().getPlexPlayer(player.getUniqueId());
if (plexPlayer == null)
{
throw new PlayerNotFoundException();
@ -536,12 +470,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
*/
protected Component mmString(String s)
{
return MiniMessage.miniMessage().deserialize(s);
}
public Rank getLevel()
{
return level;
return PlexUtils.mmDeserialize(s);
}
public CommandMap getMap()

View File

@ -0,0 +1,28 @@
package dev.plex.command.annotation;
import dev.plex.command.source.RequiredCommandSource;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Storage for the command's permissions
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandPermissions
{
/**
* Required command source
*
* @return The required command source of the command
* @see RequiredCommandSource
*/
RequiredCommandSource source() default RequiredCommandSource.ANY;
/**
* The permission
*
* @return Permission of the command
*/
String permission() default ""; // No idea what to put here
}

View File

@ -0,0 +1,17 @@
package dev.plex.command.blocking;
import com.google.common.collect.Lists;
import lombok.Data;
import net.kyori.adventure.text.Component;
import java.util.List;
@Data
public class BlockedCommand
{
private Component message;
private String requiredLevel;
private String regex;
private String command;
private List<String> commandAliases = Lists.newArrayList();
}

View File

@ -0,0 +1,66 @@
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.hook.VaultHook;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.minimessage.SafeMiniMessage;
import dev.plex.util.redis.MessageUtil;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang3.BooleanUtils;
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.util.Collections;
import java.util.List;
import java.util.UUID;
@CommandPermissions(permission = "plex.adminchat", source = RequiredCommandSource.ANY)
@CommandParameters(name = "adminchat", description = "Talk privately with other admins", usage = "/<command> <message>", aliases = "o,ac,sc,staffchat")
public class AdminChatCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
PlexPlayer player;
if (args.length == 0)
{
if (playerSender != null)
{
player = plugin.getPlayerCache().getPlexPlayer(playerSender.getUniqueId());
player.setStaffChat(!player.isStaffChat());
return messageComponent("adminChatToggled", BooleanUtils.toStringOnOff(player.isStaffChat()));
}
return usage();
}
String prefix;
if (playerSender != null)
{
player = plugin.getPlayerCache().getPlexPlayer(playerSender.getUniqueId());
prefix = PlexUtils.mmSerialize(VaultHook.getPrefix(player));
}
else
{
prefix = "<dark_gray>[<dark_purple>Console<dark_gray>]";
}
PlexLog.debug("admin chat prefix: {0}", prefix);
String message = StringUtils.join(args, " ");
plugin.getServer().getConsoleSender().sendMessage(messageComponent("adminChatFormat", sender.getName(), prefix, message));
MessageUtil.sendStaffChat(sender, SafeMiniMessage.mmDeserialize(message), PlexUtils.adminChat(sender.getName(), prefix, message).toArray(UUID[]::new));
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -4,7 +4,6 @@ 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 net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -13,7 +12,10 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.ADMIN, permission = "plex.adminworld", source = RequiredCommandSource.IN_GAME)
import java.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.adminworld", source = RequiredCommandSource.IN_GAME)
@CommandParameters(name = "adminworld", aliases = "aw", description = "Teleport to the adminworld")
public class AdminworldCMD extends PlexCommand
{
@ -30,4 +32,10 @@ public class AdminworldCMD extends PlexCommand
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -7,9 +7,7 @@ import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.event.GameModeUpdateEvent;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
@ -18,8 +16,10 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.gamemode.adventure", source = RequiredCommandSource.ANY)
@CommandParameters(name = "adventure", aliases = "gma", description = "Set your own or another player's gamemode to adventure mode")
import java.util.List;
@CommandPermissions(permission = "plex.gamemode.adventure", source = RequiredCommandSource.ANY)
@CommandParameters(name = "adventure", aliases = "gma,egma,eadventure,adventuremode,eadventuremode", description = "Set your own or another player's gamemode to adventure mode")
public class AdventureCMD extends PlexCommand
{
@Override
@ -29,14 +29,13 @@ public class AdventureCMD extends PlexCommand
{
if (isConsole(sender))
{
throw new CommandFailException(PlexUtils.messageString("consoleMustDefinePlayer"));
throw new CommandFailException(messageString("consoleMustDefinePlayer"));
}
Bukkit.getServer().getPluginManager().callEvent(new GameModeUpdateEvent(sender, playerSender, GameMode.ADVENTURE));
return null;
}
if (checkRank(sender, Rank.ADMIN, "plex.gamemode.adventure.others"))
{
checkPermission(sender, "plex.gamemode.adventure.others");
if (args[0].equals("-a"))
{
for (Player targetPlayer : Bukkit.getServer().getOnlinePlayers())
@ -50,14 +49,13 @@ public class AdventureCMD extends PlexCommand
Player nPlayer = getNonNullPlayer(args[0]);
Bukkit.getServer().getPluginManager().callEvent(new GameModeUpdateEvent(sender, nPlayer, GameMode.ADVENTURE));
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (checkTab(sender, Rank.ADMIN, "plex.gamemode.adventure.others"))
if (silentCheckPermission(sender, "plex.gamemode.adventure.others"))
{
return PlexUtils.getPlayerNameList();
}

View File

@ -0,0 +1,144 @@
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.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.util.BungeeUtil;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;
@CommandParameters(name = "ban", usage = "/<command> <player> [reason] [-rb]", aliases = "offlineban,gtfo", description = "Bans a player, offline or online")
@CommandPermissions(permission = "plex.ban", source = RequiredCommandSource.ANY)
public class BanCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
final PlexPlayer plexPlayer = DataUtils.getPlayer(args[0]);
if (plexPlayer == null)
{
throw new PlayerNotFoundException();
}
Player player = Bukkit.getPlayer(plexPlayer.getUuid());
plugin.getPunishmentManager().isAsyncBanned(plexPlayer.getUuid()).whenComplete((aBoolean, throwable) ->
{
if (aBoolean)
{
send(sender, messageComponent("playerBanned"));
return;
}
String reason;
Punishment punishment = new Punishment(plexPlayer.getUuid(), getUUID(sender));
punishment.setType(PunishmentType.BAN);
boolean rollBack = false;
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
String newReason = StringUtils.normalizeSpace(reason.replace("-rb", ""));
punishment.setReason(newReason.trim().isEmpty() ? messageString("noReasonProvided") : newReason);
rollBack = reason.startsWith("-rb") || reason.endsWith("-rb");
}
else
{
punishment.setReason(messageString("noReasonProvided"));
}
punishment.setPunishedUsername(plexPlayer.getName());
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(true);
punishment.setIp(player != null ? player.getAddress().getAddress().getHostAddress().trim() : plexPlayer.getIps().get(plexPlayer.getIps().size() - 1));
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
Bukkit.getGlobalRegionScheduler().execute(plugin, () ->
{
if (player != null)
{
BungeeUtil.kickPlayer(player, Punishment.generateBanMessage(punishment));
}
});
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + plexPlayer.getUuid());
if (rollBack)
{
/*if (plugin.getPrismHook() != null && plugin.getPrismHook().hasPrism())
{
PrismParameters parameters = plugin.getPrismHook().prismApi().createParameters();
parameters.addActionType("block-place");
parameters.addActionType("block-break");
parameters.addActionType("block-burn");
parameters.addActionType("entity-spawn");
parameters.addActionType("entity-kill");
parameters.addActionType("entity-explode");
parameters.addPlayerName(plexPlayer.getName());
parameters.setBeforeTime(Instant.now().toEpochMilli());
parameters.setProcessType(PrismProcessType.ROLLBACK);
final Future<Result> result = plugin.getPrismHook().prismApi().performLookup(parameters, sender);
Bukkit.getAsyncScheduler().runNow(plugin, scheduledTask ->
{
try
{
final Result done = result.get();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
});
}
else */
if (plugin.getCoreProtectHook() != null && plugin.getCoreProtectHook().hasCoreProtect())
{
Bukkit.getAsyncScheduler().runNow(plugin, scheduledTask ->
{
plugin.getCoreProtectHook().coreProtectAPI().performRollback(86400, Collections.singletonList(plexPlayer.getName()), null, null, null, null, 0, null);
});
}
}
});
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1 && silentCheckPermission(sender, this.getPermission()))
{
return PlexUtils.getPlayerNameList();
}
if (args.length > 1 && silentCheckPermission(sender, this.getPermission()))
{
return Collections.singletonList("-rb");
}
return Collections.emptyList();
}
}

View File

@ -0,0 +1,61 @@
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.punishment.Punishment;
import net.kyori.adventure.text.Component;
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.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@CommandParameters(name = "banlist", description = "Manages the banlist", usage = "/<command> [purge]")
@CommandPermissions(permission = "plex.banlist")
public class BanListCommand extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player player, @NotNull String[] args)
{
if (args.length == 0)
{
plugin.getPunishmentManager().getActiveBans().whenComplete((punishments, throwable) ->
{
send(sender, mmString("<gold>Active Bans (" + punishments.size() + "): <yellow>" + StringUtils.join(punishments.stream().map(Punishment::getPunishedUsername).collect(Collectors.toList()), ", ")));
});
return null;
}
if (args[0].equalsIgnoreCase("purge") || args[0].equalsIgnoreCase("clear"))
{
if (sender instanceof Player)
{
return messageComponent("noPermissionInGame");
}
if (!sender.getName().equalsIgnoreCase("console"))
{
if (!checkPermission(sender, "plex.banlist.clear"))
{
return null;
}
}
plugin.getPunishmentManager().getActiveBans().whenComplete((punishments, throwable) ->
{
punishments.forEach(plugin.getPunishmentManager()::unban);
send(sender, mmString("<gold>Unbanned " + punishments.size() + " players."));
});
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && silentCheckPermission(sender, "plex.banlist.clear") ? List.of("purge", "clear") : ImmutableList.of();
}
}

View File

@ -0,0 +1,59 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
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.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.meta.PlayerMeta;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexUtils;
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.util.List;
@CommandPermissions(permission = "plex.broadcastloginmessage", source = RequiredCommandSource.ANY)
@CommandParameters(name = "bcastloginmessage", usage = "/<command> <player>", description = "Broadcast your login message (for vanish support)", aliases = "bcastlm")
public class BcastLoginMessageCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(args[0]);
if (plexPlayer == null)
{
throw new PlayerNotFoundException();
}
String loginMessage = PlayerMeta.getLoginMessage(plexPlayer);
if (!loginMessage.isEmpty())
{
PlexUtils.broadcast(PlexUtils.stringToComponent(loginMessage));
PlexUtils.broadcast(messageComponent("loginMessage", plexPlayer.getName()));
}
else
{
return mmString("<red>This player does not have a login message.");
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -4,17 +4,20 @@ 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")
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@CommandPermissions(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
{
@ -30,7 +33,8 @@ public class BlockEditCMD extends PlexCommand
if (args[0].equalsIgnoreCase("list"))
{
send(sender, "The following have block modification abilities restricted:");
send(sender, messageComponent("listOfPlayersBlocked"));
int count = 0;
for (String player : bl.blockedPlayers.stream().toList())
{
@ -45,7 +49,7 @@ public class BlockEditCMD extends PlexCommand
}
else if (args[0].equalsIgnoreCase("purge"))
{
PlexUtils.broadcast(componentFromString(sender.getName() + " - Unblocking block modification abilities for all players").color(NamedTextColor.AQUA));
PlexUtils.broadcast(messageComponent("unblockingEdits", sender.getName(), "all players"));
int count = 0;
for (String player : bl.blockedPlayers.stream().toList())
{
@ -55,44 +59,60 @@ public class BlockEditCMD extends PlexCommand
++count;
}
}
return messageComponent("unblockedEditsSize", count);
return messageComponent("blockeditSize", "Unblocked", count);
}
else if (args[0].equalsIgnoreCase("all"))
{
PlexUtils.broadcast(componentFromString(sender.getName() + " - Blocking block modification abilities for all non-admins").color(NamedTextColor.RED));
PlexUtils.broadcast(messageComponent("blockingEdits", sender.getName(), "all non-admins"));
int count = 0;
for (final Player player : Bukkit.getOnlinePlayers())
{
if (!silentCheckRank(player, Rank.ADMIN, "plex.blockedit"))
if (!silentCheckPermission(player, "plex.blockedit"))
{
bl.blockedPlayers.add(player.getName());
++count;
}
}
return messageComponent("blockedEditsSize", count);
return messageComponent("blockeditSize", "Blocked", count);
}
final Player player = getNonNullPlayer(args[0]);
if (!bl.blockedPlayers.contains(player.getName()))
{
if (silentCheckRank(player, Rank.ADMIN, "plex.blockedit"))
if (silentCheckPermission(player, "plex.blockedit"))
{
send(sender, messageComponent("higherRankThanYou"));
return null;
}
PlexUtils.broadcast(messageComponent("blockingEditFor", sender.getName(), player.getName()));
PlexUtils.broadcast(messageComponent("blockingEdits", sender.getName(), player.getName()));
bl.blockedPlayers.add(player.getName());
send(player, messageComponent("yourEditsHaveBeenBlocked"));
send(player, messageComponent("editsModified", "blocked"));
send(sender, messageComponent("editsBlocked", player.getName()));
}
else
{
PlexUtils.broadcast(messageComponent("unblockingEditFor", sender.getName(), player.getName()));
PlexUtils.broadcast(messageComponent("unblockingEdits", sender.getName(), player.getName()));
bl.blockedPlayers.remove(player.getName());
send(player, messageComponent("yourEditsHaveBeenUnblocked"));
send(player, messageComponent("editsModified", "unblocked"));
send(sender, messageComponent("editsUnblocked", player.getName()));
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (silentCheckPermission(sender, this.getPermission()))
{
List<String> options = new ArrayList<>();
if (args.length == 1)
{
options.addAll(Arrays.asList("list", "purge", "all"));
options.addAll(PlexUtils.getPlayerNameList());
return options;
}
}
return Collections.emptyList();
}
}

View File

@ -6,16 +6,16 @@ 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.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
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.commandspy", source = RequiredCommandSource.IN_GAME)
import java.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.commandspy", source = RequiredCommandSource.IN_GAME)
@CommandParameters(name = "commandspy", aliases = "cmdspy", description = "Spy on other player's commands")
public class CommandSpyCMD extends PlexCommand
{
@ -24,7 +24,7 @@ public class CommandSpyCMD extends PlexCommand
{
if (playerSender != null)
{
PlexPlayer plexPlayer = DataUtils.getPlayer(playerSender.getUniqueId());
PlexPlayer plexPlayer = plugin.getPlayerCache().getPlexPlayer(playerSender.getUniqueId());
plexPlayer.setCommandSpy(!plexPlayer.isCommandSpy());
DataUtils.update(plexPlayer);
send(sender, messageComponent("toggleCommandSpy")
@ -33,4 +33,10 @@ public class CommandSpyCMD extends PlexCommand
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -0,0 +1,39 @@
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.util.PlexUtils;
import net.kyori.adventure.text.Component;
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.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.consolesay", source = RequiredCommandSource.CONSOLE)
@CommandParameters(name = "consolesay", usage = "/<command> <message>", description = "Displays a message to everyone", aliases = "csay")
public class ConsoleSayCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
PlexUtils.broadcast(PlexUtils.messageComponent("consoleSayMessage", sender.getName(), PlexUtils.mmStripColor(StringUtils.join(args, " "))));
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -7,9 +7,7 @@ import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.event.GameModeUpdateEvent;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
@ -18,8 +16,10 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.gamemode.creative", source = RequiredCommandSource.ANY)
@CommandParameters(name = "creative", aliases = "gmc", description = "Set your own or another player's gamemode to creative mode")
import java.util.List;
@CommandPermissions(permission = "plex.gamemode.creative", source = RequiredCommandSource.ANY)
@CommandParameters(name = "creative", aliases = "gmc,egmc,ecreative,eecreative,creativemode,ecreativemode", description = "Set your own or another player's gamemode to creative mode")
public class CreativeCMD extends PlexCommand
{
@Override
@ -29,7 +29,7 @@ public class CreativeCMD extends PlexCommand
{
if (isConsole(sender))
{
throw new CommandFailException(PlexUtils.messageString("consoleMustDefinePlayer"));
throw new CommandFailException(messageString("consoleMustDefinePlayer"));
}
if (!(playerSender == null))
{
@ -38,8 +38,7 @@ public class CreativeCMD extends PlexCommand
return null;
}
if (checkRank(sender, Rank.ADMIN, "plex.gamemode.creative.others"))
{
checkPermission(sender, "plex.gamemode.creative.others");
if (args[0].equals("-a"))
{
for (Player targetPlayer : Bukkit.getServer().getOnlinePlayers())
@ -55,13 +54,11 @@ public class CreativeCMD extends PlexCommand
Bukkit.getServer().getPluginManager().callEvent(new GameModeUpdateEvent(sender, nPlayer, GameMode.CREATIVE));
return null;
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (checkTab(sender, Rank.ADMIN, "plex.gamemode.creative.others"))
if (silentCheckPermission(sender, "plex.gamemode.creative.others"))
{
return PlexUtils.getPlayerNameList();
}

View File

@ -0,0 +1,97 @@
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.menu.impl.MaterialMenu;
import dev.plex.util.GameRuleUtil;
import dev.plex.util.PlexLog;
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.World;
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;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
@CommandParameters(name = "pdebug", description = "Plex's debug command", usage = "/<command> <aliases <command> | redis-reset <player> | gamerules>")
@CommandPermissions(permission = "plex.debug")
public class DebugCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
if (args[0].equalsIgnoreCase("redis-reset"))
{
if (args.length == 2)
{
Player player = getNonNullPlayer(args[1]);
if (plugin.getRedisConnection().getJedis().exists(player.getUniqueId().toString()))
{
plugin.getRedisConnection().getJedis().del(player.getUniqueId().toString());
return messageComponent("redisResetSuccessful", player.getName());
}
return messageComponent("redisResetPlayerNotFound");
}
}
if (args[0].equalsIgnoreCase("gamerules"))
{
for (World world : Bukkit.getWorlds())
{
GameRuleUtil.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)
{
GameRuleUtil.commitSpecificGameRules(bukkitWorld);
PlexLog.log("Set specific gamerules for world: " + world.toLowerCase(Locale.ROOT));
}
}
return messageComponent("reappliedGamerules");
}
if (args[0].equalsIgnoreCase("aliases"))
{
if (args.length == 2)
{
String commandName = args[1];
Command command = plugin.getServer().getCommandMap().getCommand(commandName);
if (command == null)
{
return messageComponent("commandNotFound");
}
return messageComponent("commandAliases", commandName, Arrays.toString(command.getAliases().toArray(new String[0])));
}
}
if (args[0].equalsIgnoreCase("pagination"))
{
if (playerSender == null)
{
return messageComponent("noPermissionConsole");
}
new MaterialMenu().open(playerSender);
return null;
}
return usage();
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -1,17 +1,13 @@
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.PlexLog;
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;
@ -20,13 +16,10 @@ 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;
import java.util.*;
@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")
@CommandPermissions(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> [entity] [radius]", aliases = "ew,rd")
public class EntityWipeCMD extends PlexCommand
{
@Override
@ -36,6 +29,22 @@ public class EntityWipeCMD extends PlexCommand
List<String> entityWhitelist = new LinkedList<>(Arrays.asList(args));
boolean radiusSpecified = !entityWhitelist.isEmpty() && isNumeric(entityWhitelist.get(entityWhitelist.size() - 1)); // try and detect if the last argument of the command is a number
boolean useBlacklist = args.length == 0 || (args.length == 1 && radiusSpecified); // if there are no arguments or the one argument is a number
int radius = 0;
PlexLog.debug("using blacklist: " + useBlacklist);
PlexLog.debug("radius specified: " + radiusSpecified);
if (radiusSpecified)
{
radius = parseInt(sender, args[entityWhitelist.size() - 1]); // get the args length as the size of the list
radius *= radius;
entityWhitelist.remove(entityWhitelist.size() - 1); // remove the radius from the list
}
PlexLog.debug("radius: " + radius);
EntityType[] entityTypes = EntityType.values();
entityWhitelist.removeIf(name ->
{
@ -47,8 +56,6 @@ public class EntityWipeCMD extends PlexCommand
return res;
});
boolean useBlacklist = args.length == 0;
HashMap<String, Integer> entityCounts = new HashMap<>();
for (World world : Bukkit.getWorlds())
@ -57,10 +64,20 @@ public class EntityWipeCMD extends PlexCommand
{
if (entity.getType() != EntityType.PLAYER)
{
String type = entity.getName();
String type = entity.getType().name();
if (useBlacklist ? entityBlacklist.stream().noneMatch(entityName -> entityName.equalsIgnoreCase(type)) : entityWhitelist.stream().anyMatch(entityName -> entityName.equalsIgnoreCase(type)))
{
if (radius > 0)
{
PlexLog.debug("we got here, radius is > 0");
if (playerSender != null && entity.getWorld() == playerSender.getWorld() && playerSender.getLocation().distanceSquared(entity.getLocation()) > radius)
{
PlexLog.debug("continuing");
continue;
}
}
PlexLog.debug("removed entity: " + entity.getType().name());
entity.remove();
entityCounts.put(type, entityCounts.getOrDefault(type, 0) + 1);
@ -86,14 +103,12 @@ public class EntityWipeCMD extends PlexCommand
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
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (silentCheckPermission(sender, this.getPermission()))
{
List<String> entities = new ArrayList<>();
for (World world : Bukkit.getWorlds())
@ -102,10 +117,42 @@ public class EntityWipeCMD extends PlexCommand
{
if (entity.getType() != EntityType.PLAYER)
{
entities.add(entity.getName());
entities.add(entity.getType().name());
}
}
}
return entities.stream().toList();
}
return Collections.emptyList();
}
private Integer parseInt(CommandSender sender, String string)
{
try
{
return Integer.parseInt(string);
}
catch (NumberFormatException ex)
{
sender.sendMessage(messageComponent("notANumber", string));
}
return null;
}
private boolean isNumeric(String string)
{
if (string == null)
{
return false;
}
try
{
int num = Integer.parseInt(string);
}
catch (NumberFormatException nfe)
{
return false;
}
return true;
}
}

View File

@ -4,7 +4,6 @@ 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 net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -13,11 +12,13 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.flatlands", source = RequiredCommandSource.IN_GAME)
import java.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.flatlands", source = RequiredCommandSource.IN_GAME)
@CommandParameters(name = "flatlands", description = "Teleport to the flatlands")
public class FlatlandsCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
@ -30,4 +31,10 @@ public class FlatlandsCMD extends PlexCommand
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -7,19 +7,20 @@ import dev.plex.command.annotation.CommandPermissions;
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 dev.plex.util.TimeUtils;
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.time.ZoneId;
import java.time.ZonedDateTime;
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")
@CommandPermissions(permission = "plex.freeze")
public class FreezeCMD extends PlexCommand
{
@Override
@ -37,27 +38,15 @@ public class FreezeCMD extends PlexCommand
return messageComponent("playerFrozen");
}
if (isAdmin(getPlexPlayer(player)))
{
if (!isConsole(sender))
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()) && getPlexPlayer(player).isAdminActive())
{
return messageComponent("higherRankThanYou");
}
}
}
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
punishment.setCustomTime(false);
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
punishment.setEndDate(date.plusSeconds(plugin.config.getInt("punishments.freeze-timer", 300)));
punishment.setType(PunishmentType.FREEZE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
punishment.setActive(true);
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("frozePlayer", sender.getName(), player.getName()));
@ -65,8 +54,8 @@ public class FreezeCMD extends PlexCommand
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && checkTab(sender, Rank.ADMIN, "plex.freeze") ? PlexUtils.getPlayerNameList() : ImmutableList.of();
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -0,0 +1,106 @@
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.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.event.GameModeUpdateEvent;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@CommandParameters(name = "gamemode", usage = "/<command> <creative | survival | adventure | default | spectator> [player]", description = "Change your gamemode", aliases = "gm,egamemode,gmt,egmt")
@CommandPermissions(permission = "plex.gamemode", source = RequiredCommandSource.ANY)
public class GamemodeCMD extends PlexCommand
{
private GameMode gamemode;
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
switch (args[0].toLowerCase())
{
case "survival", "s", "0" ->
{
gamemode = GameMode.SURVIVAL;
update(sender, playerSender, GameMode.SURVIVAL);
return null;
}
case "creative", "c", "1" ->
{
gamemode = GameMode.CREATIVE;
update(sender, playerSender, GameMode.CREATIVE);
return null;
}
case "adventure", "a", "2" ->
{
gamemode = GameMode.ADVENTURE;
update(sender, playerSender, GameMode.ADVENTURE);
return null;
}
case "default", "d", "5" ->
{
gamemode = plugin.getServer().getDefaultGameMode();
update(sender, playerSender, plugin.getServer().getDefaultGameMode());
return null;
}
case "spectator", "sp", "3", "6" ->
{
gamemode = GameMode.SPECTATOR;
checkPermission(sender, "plex.gamemode.spectator");
update(sender, playerSender, GameMode.SPECTATOR);
return null;
}
}
if (args.length > 1)
{
checkPermission(sender, "plex.gamemode.others");
Player player = getNonNullPlayer(args[1]);
Bukkit.getServer().getPluginManager().callEvent(new GameModeUpdateEvent(sender, player, gamemode));
}
return null;
}
private void update(CommandSender sender, Player playerSender, GameMode gameMode)
{
if (isConsole(sender))
{
throw new CommandFailException(PlexUtils.messageString("consoleMustDefinePlayer"));
}
if (!(playerSender == null))
{
Bukkit.getServer().getPluginManager().callEvent(new GameModeUpdateEvent(sender, playerSender.getPlayer(), gameMode));
}
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1)
{
return Arrays.asList("creative", "survival", "adventure", "spectator", "default");
}
if (args.length == 2)
{
if (silentCheckPermission(sender, "plex.gamemode.others"))
{
return PlexUtils.getPlayerNameList();
}
}
return Collections.emptyList();
}
}

View File

@ -1,5 +1,6 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.DataUtils;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
@ -9,20 +10,23 @@ 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.BungeeUtil;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.util.UUID;
import dev.plex.util.TimeUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
@CommandParameters(name = "kick", description = "Kicks a player", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.kick", source = RequiredCommandSource.ANY)
@CommandPermissions(permission = "plex.kick", source = RequiredCommandSource.ANY)
public class KickCMD extends PlexCommand
{
@Override
@ -33,36 +37,41 @@ public class KickCMD extends PlexCommand
return usage();
}
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason = "No reason provided";
PlexPlayer plexPlayer = DataUtils.getPlayer(args[0]);
String reason = messageString("noReasonProvided");
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
if (plexPlayer == null)
{
throw new PlayerNotFoundException();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
Player player = Bukkit.getPlayer(targetUUID);
Player player = Bukkit.getPlayer(plexPlayer.getUuid());
if (player == null)
{
throw new PlayerNotFoundException();
}
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
Punishment punishment = new Punishment(plexPlayer.getUuid(), getUUID(sender));
punishment.setType(PunishmentType.KICK);
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
punishment.setReason(reason);
}
punishment.setReason(reason);
punishment.setPunishedUsername(plexPlayer.getName());
punishment.setEndDate(LocalDateTime.now());
punishment.setEndDate(ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE)));
punishment.setCustomTime(false);
punishment.setActive(false);
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("kickedPlayer", sender.getName(), plexPlayer.getName()));
player.kick(componentFromString(reason));
BungeeUtil.kickPlayer(player, Punishment.generateKickMessage(punishment));
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -0,0 +1,77 @@
package dev.plex.command.impl;
import com.google.common.collect.Lists;
import dev.plex.command.PlexCommand;
import dev.plex.util.PlexUtils;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.hook.VaultHook;
import dev.plex.meta.PlayerMeta;
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;
import java.util.Collections;
import java.util.List;
@CommandParameters(name = "list", description = "Show a list of all online players", usage = "/<command> [-d | -v]", aliases = "lsit,who,playerlist,online")
@CommandPermissions(permission = "plex.list")
public class ListCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
List<Player> players = Lists.newArrayList(Bukkit.getOnlinePlayers());
if (args.length > 0 && args[0].equalsIgnoreCase("-v"))
{
checkPermission(sender, "plex.list.vanished");
players.removeIf(player -> !PlayerMeta.isVanished(player));
}
else
{
players.removeIf(PlayerMeta::isVanished);
}
Component list = Component.empty();
Component header = PlexUtils.messageComponent(players.size() == 1 ? "listHeader" : "listHeaderPlural", players.size(), Bukkit.getMaxPlayers());
send(sender, header);
if (players.isEmpty())
{
return null;
}
for (int i = 0; i < players.size(); i++)
{
Player player = players.get(i);
Component prefix = VaultHook.getPrefix(getPlexPlayer(player));
if (prefix != null && !prefix.equals(Component.empty()) && !prefix.equals(Component.space()))
{
list = list.append(prefix).append(Component.space());
}
list = list.append(Component.text(player.getName()).color(NamedTextColor.WHITE));
if (args.length > 0 && args[0].equalsIgnoreCase("-d"))
{
list = list.append(Component.space());
list = list.append(Component.text("(").color(NamedTextColor.WHITE));
list = list.append(player.displayName());
list = list.append(Component.text(")").color(NamedTextColor.WHITE));
}
if (i != players.size() - 1)
{
list = list.append(Component.text(",")).append(Component.space());
}
}
return list;
}
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1 && silentCheckPermission(sender, this.getPermission()))
{
return List.of("-d", "-v");
}
return Collections.emptyList();
}
}

View File

@ -4,15 +4,18 @@ 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 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.util.Collections;
import java.util.List;
@CommandParameters(name = "localspawn", description = "Teleport to the spawnpoint of the world you are in")
@CommandPermissions(level = Rank.OP, permission = "plex.spawnpoint", source = RequiredCommandSource.IN_GAME)
@CommandPermissions(permission = "plex.localspawn", source = RequiredCommandSource.IN_GAME)
public class LocalSpawnCMD extends PlexCommand
{
@Override
@ -22,4 +25,10 @@ public class LocalSpawnCMD extends PlexCommand
playerSender.teleportAsync(playerSender.getWorld().getSpawnLocation());
return messageComponent("teleportedToWorldSpawn");
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -5,17 +5,17 @@ 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.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.util.List;
@CommandParameters(name = "lockup", description = "Lockup a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.lockup")
@CommandPermissions(permission = "plex.lockup")
public class LockupCMD extends PlexCommand
{
@Override
@ -28,27 +28,18 @@ public class LockupCMD extends PlexCommand
Player player = getNonNullPlayer(args[0]);
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
if (isAdmin(getPlexPlayer(player)))
{
if (!isConsole(sender))
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
}
}
punishedPlayer.setLockedUp(!punishedPlayer.isLockedUp());
if (punishedPlayer.isLockedUp())
{
player.openInventory(player.getInventory());
}
PlexUtils.broadcast(messageComponent(punishedPlayer.isLockedUp() ? "lockedUpPlayer" : "unlockedPlayer", sender.getName(), player.getName()));
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && checkTab(sender, Rank.ADMIN, "plex.mute") ? PlexUtils.getPlayerNameList() : ImmutableList.of();
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

View File

@ -4,7 +4,7 @@ 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 net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -13,11 +13,13 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.masterbuilderworld", source = RequiredCommandSource.IN_GAME)
import java.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.masterbuilderworld", source = RequiredCommandSource.IN_GAME)
@CommandParameters(name = "masterbuilderworld", aliases = "mbw", description = "Teleport to the Master Builder world")
public class MasterbuilderworldCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
@ -31,4 +33,10 @@ public class MasterbuilderworldCMD extends PlexCommand
}
return null;
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return Collections.emptyList();
}
}

View File

@ -0,0 +1,96 @@
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.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@CommandParameters(name = "moblimit", usage = "/<command> [on | off | setmax <limit>]", aliases = "entitylimit", description = "Manages the mob limit per chunk.")
@CommandPermissions(permission = "plex.moblimit", source = RequiredCommandSource.ANY)
public class MobLimitCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
Chunk chunk = playerSender != null ? playerSender.getLocation().getChunk() : Bukkit.getWorlds().get(0).getChunkAt(0, 0);
int currentLimit = plugin.config.getInt("entity_limit.max_mobs_per_chunk");
int currentMobCount = (int) Arrays.stream(chunk.getEntities())
.filter(entity -> entity instanceof LivingEntity && !(entity instanceof Player))
.count();
String status = plugin.config.getBoolean("entity_limit.mob_limit_enabled") ? "<green>Enabled" : "<red>Disabled";
return PlexUtils.messageComponent("mobLimitStatus", status, currentMobCount, currentLimit, chunk.getX(), chunk.getZ());
}
switch (args[0].toLowerCase())
{
case "on":
plugin.config.set("entity_limit.mob_limit_enabled", true);
plugin.config.save();
return PlexUtils.messageComponent("mobLimitToggle", "enabled");
case "off":
plugin.config.set("entity_limit.mob_limit_enabled", false);
plugin.config.save();
return PlexUtils.messageComponent("mobLimitToggle", "disabled");
case "setmax":
try
{
if (args.length != 2) return usage();
int newLimit = Integer.parseInt(args[1]);
if (newLimit < 0) throw new NumberFormatException();
int limitCeiling = plugin.config.getInt("entity_limit.mob_limit_ceiling");
if (newLimit > limitCeiling)
{
newLimit = limitCeiling;
sender.sendMessage(PlexUtils.messageComponent("mobLimitCeiling"));
}
plugin.config.set("entity_limit.max_mobs_per_chunk", newLimit);
plugin.config.save();
return PlexUtils.messageComponent("mobLimitSet", newLimit);
}
catch (NumberFormatException e)
{
return PlexUtils.messageComponent("unableToParseNumber", args[1]);
}
default:
return usage();
}
}
@Override
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (silentCheckPermission(sender, this.getPermission()))
{
if (args.length == 1)
{
return Arrays.asList("on", "off", "setmax");
}
if (args.length == 2 && args[0].equals("setmax"))
{
return Collections.emptyList();
}
return Collections.emptyList();
}
return Collections.emptyList();
}
}

View File

@ -0,0 +1,122 @@
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.util.PlexLog;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang3.text.WordUtils;
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.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@CommandPermissions(permission = "plex.mobpurge", source = RequiredCommandSource.ANY)
@CommandParameters(name = "mobpurge", description = "Purge all mobs.", usage = "/<command> [mob]", aliases = "mp")
public class MobPurgeCMD extends PlexCommand
{
private final List<EntityType> MOB_TYPES = new ArrayList<>();
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, @NotNull String[] args)
{
EntityType type = null;
String mobName = null;
if (args.length > 0)
{
try
{
type = EntityType.valueOf(args[0].toUpperCase());
}
catch (Exception e)
{
PlexLog.debug("A genius tried and failed removing the following invalid mob: " + args[0].toUpperCase());
send(sender, messageComponent("notAValidMob"));
return null;
}
if (!MOB_TYPES.contains(type))
{
PlexLog.debug(Arrays.deepToString(MOB_TYPES.toArray()));
PlexLog.debug("A genius tried to remove a mob that doesn't exist: " + args[0].toUpperCase());
sender.sendMessage(messageComponent("notAValidMobButValidEntity"));
return null;
}
}
if (type != null)
{
mobName = WordUtils.capitalizeFully(type.name().replace("_", " "));
PlexLog.debug("The args aren't null so the mob is: " + mobName);
}
int count = purgeMobs(type);
if (type != null)
{
PlexUtils.broadcast(messageComponent("removedEntitiesOfTypes", sender.getName(), count, mobName));
PlexLog.debug("All " + count + " of " + mobName + " were removed");
}
else
{
PlexUtils.broadcast(messageComponent("removedMobs", sender.getName(), count));
PlexLog.debug("All " + count + " valid mobs were removed");
}
sender.sendMessage(messageComponent("amountOfMobsRemoved", count, (type != null ? mobName : "mob") + multipleS(count)));
return null;
}
private String multipleS(int count)
{
return (count == 1 ? "" : "s");
}
private int purgeMobs(EntityType type)
{
int removed = 0;
for (World world : Bukkit.getWorlds())
{
for (Entity entity : world.getLivingEntities())
{
if (entity instanceof LivingEntity && !(entity instanceof Player))
{
if (type != null && !entity.getType().equals(type))
{
continue;
}
entity.remove();
removed++;
}
}
}
return removed;
}
private List<String> getAllMobs()
{
List<String> mobs = new ArrayList<>();
Arrays.stream(EntityType.values()).filter(EntityType::isAlive).filter(EntityType::isSpawnable).forEach(MOB_TYPES::add);
for (EntityType entityType : MOB_TYPES)
{
mobs.add(entityType.name());
}
return mobs;
}
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1 && silentCheckPermission(sender, this.getPermission()))
{
return getAllMobs();
}
return Collections.emptyList();
}
}

View File

@ -7,19 +7,20 @@ import dev.plex.command.annotation.CommandPermissions;
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.List;
import java.util.UUID;
import dev.plex.util.TimeUtils;
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.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
@CommandParameters(name = "mute", description = "Mute a player on the server", usage = "/<command> <player>", aliases = "stfu")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.mute")
@CommandPermissions(permission = "plex.mute")
public class MuteCMD extends PlexCommand
{
@Override
@ -37,27 +38,21 @@ public class MuteCMD extends PlexCommand
return messageComponent("playerMuted");
}
if (isAdmin(getPlexPlayer(player)))
if (silentCheckPermission(player, "plex.mute"))
{
if (!isConsole(sender))
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
}
send(sender, messageComponent("higherRankThanYou"));
return null;
}
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
punishment.setCustomTime(false);
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
punishment.setEndDate(date.plusSeconds(plugin.config.getInt("punishments.mute-timer", 300)));
punishment.setType(PunishmentType.MUTE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
punishment.setActive(true);
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("mutedPlayer", sender.getName(), player.getName()));
@ -65,8 +60,8 @@ public class MuteCMD extends PlexCommand
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
public @NotNull List<String> smartTabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
return args.length == 1 && checkTab(sender, Rank.ADMIN, "plex.mute") ? PlexUtils.getPlayerNameList() : ImmutableList.of();
return args.length == 1 && silentCheckPermission(sender, this.getPermission()) ? PlexUtils.getPlayerNameList() : ImmutableList.of();
}
}

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