1 Commits

Author SHA1 Message Date
17aec8736f Plex 0.9 2022-03-19 14:37:11 -05:00
135 changed files with 1521 additions and 5718 deletions

View File

@ -1,77 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ master, server ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '29 4 * * *'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
distribution: temurin
java-version: 17
cache: gradle
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
- run: |
chmod +x gradlew
./gradlew build --no-daemon
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

3
.gitignore vendored
View File

@ -1,7 +1,6 @@
/.idea/
*.iml
/target/
src/main/resources/build.properties
# OS
.DS_Store
@ -13,4 +12,4 @@ Thumbs.db
# Gradle
/build/
/.gradle/
/.gradle/

View File

@ -1,23 +0,0 @@
For those who are wanting to contribute, we fully encourage doing so. There are a few rules we require following when contributing however.
## Steps
1. Make an isuse 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 Plex
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
5. 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.

32
Jenkinsfile vendored
View File

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

View File

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

View File

@ -1,8 +1,3 @@
# Plex [![Build Status](https://ci.plex.us.org/job/Plex/job/master/badge/icon)](https://ci.plex.us.org/job/Plex/job/master/)
# Plex
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.
A new freedom plugin.

View File

@ -1,7 +1,7 @@
plugins {
id "java"
id "maven-publish"
id "net.minecrell.plugin-yml.bukkit" version "0.6.1-SNAPSHOT"
id "net.minecrell.plugin-yml.bukkit" version "0.5.1"
id "com.github.johnrengelman.shadow" version "7.1.2"
}
@ -19,46 +19,26 @@ repositories {
url = uri("https://repo.maven.apache.org/maven2/")
}
maven {
url = uri("https://jitpack.io")
content {
includeGroup("com.github.MilkBowl")
}
}
mavenCentral()
}
dependencies {
library "org.projectlombok:lombok:1.18.22"
annotationProcessor "org.projectlombok:lombok:1.18.22"
library "org.json:json:20220320"
library "org.json:json:20211205"
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 "dev.morphia.morphia:morphia-core:2.2.3"
library "redis.clients:jedis:4.1.1"
library "org.mariadb.jdbc:mariadb-java-client:3.0.3"
library "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"
compileOnly("com.github.MilkBowl:VaultAPI:1.7") {
exclude group: "org.bukkit", module: "bukkit"
}
implementation "org.bstats:bstats-base:3.0.0"
implementation "org.bstats:bstats-bukkit:3.0.0"
}
group = "dev.plex"
version = "1.0.2"
version = "0.9"
description = "Plex"
shadowJar {
@ -72,52 +52,10 @@ bukkit {
description = "Plex provides a new experience for freedom servers."
main = "dev.plex.Plex"
website = "https://plex.us.org"
authors = ["Telesphoreo", "taahanis", "supernt"]
softDepend = ["Vault"]
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 z")
}
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))
}
@ -125,36 +63,18 @@ java {
publishing {
publications {
maven(MavenPublication) {
pom.withXml {
def dependenciesNode = asNode().appendNode("dependencies")
configurations.getByName("library").getAllDependencies().each { dependency ->
dependenciesNode.appendNode("dependency").with {
it.appendNode("groupId", dependency.group)
it.appendNode("artifactId", dependency.name)
it.appendNode("version", dependency.version)
it.appendNode("scope", "provided")
}
}
configurations.getByName("implementation").getAllDependencies().each { dependency ->
dependenciesNode.appendNode("dependency").with {
it.appendNode("groupId", dependency.group)
it.appendNode("artifactId", dependency.name)
it.appendNode("version", dependency.version)
it.appendNode("scope", "runtime")
}
}
}
artifacts = [shadowJar]
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")
plexReleases(MavenPublication) {
from(components.java)
repositories {
maven {
url("https://nexus.telesphoreo.me/repository/plex-releases/")
credentials {
username = System.getenv("plex_repo_user")
password = System.getenv("plex_repo_pass")
}
}
}
}
}
@ -167,10 +87,18 @@ tasks.withType(JavaCompile) {
tasks {
build {
dependsOn(shadowJar)
finalizedBy(buildProperties)
if (System.getenv("plex_repo_user") != null && System.getenv("plex_repo_pass") != null) {
if (!getVersion().toString().toLowerCase().endsWith("-snapshot")) {
dependsOn(publishPlexReleasesPublicationToMavenRepository)
}
}
}
javadoc {
options.memberLevel = JavadocMemberLevel.PRIVATE
}
}
task publishRelease {
dependsOn(publishPlexReleasesPublicationToMavenRepository)
}

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -1,7 +1 @@
pluginManagement {
repositories {
maven { url = uri("https://nexus.telesphoreo.me/repository/gradle-plugins/") }
gradlePluginPortal()
}
}
rootProject.name = "Plex"
rootProject.name = 'Plex'

View File

@ -3,12 +3,15 @@ package dev.plex;
import dev.plex.admin.Admin;
import dev.plex.admin.AdminList;
import dev.plex.cache.DataUtils;
import dev.plex.cache.MongoPlayerData;
import dev.plex.cache.PlayerCache;
import dev.plex.cache.SQLPlayerData;
import dev.plex.config.Config;
import dev.plex.handlers.CommandHandler;
import dev.plex.handlers.ListenerHandler;
import dev.plex.module.ModuleManager;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.PunishmentManager;
import dev.plex.rank.RankManager;
import dev.plex.services.ServiceManager;
@ -16,23 +19,16 @@ import dev.plex.storage.MongoConnection;
import dev.plex.storage.RedisConnection;
import dev.plex.storage.SQLConnection;
import dev.plex.storage.StorageType;
import dev.plex.storage.permission.SQLPermissions;
import dev.plex.storage.player.MongoPlayerData;
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.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.UpdateChecker;
import dev.plex.world.CustomWorld;
import java.io.File;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
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;
@Getter
@ -40,16 +36,13 @@ import org.bukkit.plugin.java.JavaPlugin;
public class Plex extends JavaPlugin
{
private static Plex plugin;
public Config config;
public Config messages;
public Config indefBans;
public Config commands;
public File modulesFolder;
private StorageType storageType = StorageType.SQLITE;
public static final BuildInfo build = new BuildInfo();
private StorageType storageType = StorageType.SQLITE;
private SQLConnection sqlConnection;
private MongoConnection mongoConnection;
@ -58,20 +51,17 @@ public class Plex extends JavaPlugin
private MongoPlayerData mongoPlayerData;
private SQLPlayerData sqlPlayerData;
private SQLPunishment sqlPunishment;
private SQLNotes sqlNotes;
private SQLPermissions sqlPermissions;
private ModuleManager moduleManager;
private RankManager rankManager;
private ServiceManager serviceManager;
private PunishmentManager punishmentManager;
private AdminList adminList;
private UpdateChecker updateChecker;
private String system;
private Permission permissions;
private UpdateChecker updateChecker;
private String system;
public static Plex get()
{
@ -85,8 +75,6 @@ public class Plex extends JavaPlugin
config = new Config(this, "config.yml");
messages = new Config(this, "messages.yml");
indefBans = new Config(this, "indefbans.yml");
commands = new Config(this, "commands.yml");
build.load(this);
modulesFolder = new File(this.getDataFolder() + File.separator + "modules");
if (!modulesFolder.exists())
@ -94,6 +82,10 @@ public class Plex extends JavaPlugin
modulesFolder.mkdir();
}
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager = new ModuleManager();
moduleManager.loadAllModules();
moduleManager.loadModules();
@ -106,17 +98,11 @@ public class Plex extends JavaPlugin
messages.load();
// Don't add default entries to indefinite ban file
indefBans.load(false);
commands.load(false);
sqlConnection = new SQLConnection();
mongoConnection = new MongoConnection();
redisConnection = new RedisConnection();
moduleManager.enableModules();
system = config.getString("system");
system = config.getString("commands.permissions");
PlexLog.log("Attempting to connect to DB: {0}", plugin.config.getString("data.central.db"));
try
{
PlexUtils.testConnections();
@ -128,11 +114,6 @@ public class Plex extends JavaPlugin
e.printStackTrace();
}
if (!setupPermissions() && system.equalsIgnoreCase("permissions") && !getServer().getPluginManager().isPluginEnabled("Vault"))
{
throw new RuntimeException("Vault is required to run on the server if you use permissions!");
}
updateChecker = new UpdateChecker();
PlexLog.log("Update checking enabled");
@ -140,7 +121,7 @@ public class Plex extends JavaPlugin
Metrics metrics = new Metrics(this, 14143);
PlexLog.log("Enabled Metrics");
if (redisConnection != null && redisConnection.isEnabled())
if (redisConnection.isEnabled())
{
redisConnection.getJedis();
PlexLog.log("Connected to Redis!");
@ -157,9 +138,6 @@ public class Plex extends JavaPlugin
else
{
sqlPlayerData = new SQLPlayerData();
sqlPunishment = new SQLPunishment();
sqlNotes = new SQLNotes();
sqlPermissions = new SQLPermissions();
}
new ListenerHandler();
@ -194,7 +172,7 @@ public class Plex extends JavaPlugin
if (plugin.getRankManager().isAdmin(plexPlayer))
{
plugin.getAdminList().removeFromCache(plexPlayer.getUuid());
plugin.getAdminList().removeFromCache(UUID.fromString(plexPlayer.getUuid()));
}
if (mongoPlayerData != null) //back to mongo checking
@ -206,7 +184,7 @@ public class Plex extends JavaPlugin
sqlPlayerData.update(plexPlayer);
}
});
if (redisConnection != null && redisConnection.isEnabled() && redisConnection.getJedis().isConnected())
if (redisConnection.isEnabled() && redisConnection.getJedis().isConnected())
{
PlexLog.log("Disabling Redis/Jedis. No memory leaks in this Anarchy server!");
redisConnection.getJedis().close();
@ -231,20 +209,14 @@ public class Plex extends JavaPlugin
{
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
PlayerCache.getPlexPlayerMap().put(player.getUniqueId(), plexPlayer); //put them into the cache
PlayerCache.getPunishedPlayerMap().put(player.getUniqueId(), new PunishedPlayer(player.getUniqueId()));
if (plugin.getRankManager().isAdmin(plexPlayer))
{
Admin admin = new Admin(plexPlayer.getUuid());
Admin admin = new Admin(UUID.fromString(plexPlayer.getUuid()));
admin.setRank(plexPlayer.getRankFromString());
plugin.getAdminList().addToCache(admin);
}
});
}
public boolean setupPermissions()
{
RegisteredServiceProvider<Permission> rsp = Bukkit.getServicesManager().getRegistration(Permission.class);
permissions = rsp.getProvider();
return permissions != null;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,7 @@ package dev.plex.cache;
import com.google.common.collect.Maps;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import java.util.Map;
import java.util.UUID;
@ -19,18 +20,19 @@ 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, PunishedPlayer> getPunishedPlayerMap()
// {
// return punishedPlayerMap;
// }
public static Map<UUID, PlexPlayer> getPlexPlayerMap()
{
return plexPlayerMap;
}
/*public static PunishedPlayer getPunishedPlayer(UUID uuid)
public static PunishedPlayer getPunishedPlayer(UUID uuid)
{
if (!getPunishedPlayerMap().containsKey(uuid))
{
@ -38,7 +40,7 @@ public class PlayerCache
}
return getPunishedPlayerMap().get(uuid);
}
*/
public static PlexPlayer getPlexPlayer(UUID uuid)
{
return getPlexPlayerMap().get(uuid);

View File

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

View File

@ -20,6 +20,7 @@ import java.util.UUID;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -132,14 +133,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
}
else
{
if (getLevel().isAtLeast(Rank.ADMIN) && !plexPlayer.isAdminActive())
{
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
}
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
@ -156,42 +149,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
return true;
}
}
if (sender instanceof ConsoleCommandSender && !sender.getName().equalsIgnoreCase("console")) //telnet
{
PlexPlayer plexPlayer = DataUtils.getPlayer(sender.getName());
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (!plexPlayer.getRankFromString().isAtLeast(getLevel()))
{
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
}
else
{
if (getLevel().isAtLeast(Rank.ADMIN) && !plexPlayer.isAdminActive())
{
send(sender, messageComponent("noPermissionRank", ChatColor.stripColor(getLevel().getLoginMessage())));
return true;
}
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
if (!plugin.getPermissions().playerHas(null, Bukkit.getOfflinePlayer(plexPlayer.getUuid()), perms.permission()))
{
send(sender, messageComponent("noPermissionNode", perms.permission()));
return true;
}
}
else
{
PlexLog.error("Neither permissions or ranks were selected to be used in the configuration file!");
send(sender, "There is a server misconfiguration. Please alert a developer or the owner");
return true;
}
}
try
{
Component component = this.execute(sender, isConsole(sender) ? null : (Player)sender, args);
@ -200,10 +157,9 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
send(sender, component);
}
}
catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException |
ConsoleMustDefinePlayerException | PlayerNotBannedException | NumberFormatException ex)
catch (PlayerNotFoundException | CommandFailException | ConsoleOnlyException | ConsoleMustDefinePlayerException | PlayerNotBannedException ex)
{
send(sender, PlexUtils.mmDeserialize(ex.getMessage()));
send(sender, MiniMessage.miniMessage().deserialize(ex.getMessage()));
}
return true;
}
@ -282,28 +238,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
{
return checkRank((Player)sender, rank, permission);
}
if (!sender.getName().equalsIgnoreCase("console"))
{
PlexPlayer plexPlayer = DataUtils.getPlayer(sender.getName());
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 (!plugin.getPermissions().playerHas(null, Bukkit.getOfflinePlayer(plexPlayer.getUuid()), permission))
{
throw new CommandFailException(PlexUtils.messageString("noPermissionNode", permission));
}
}
}
return true;
}
@ -329,10 +263,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
{
throw new CommandFailException(PlexUtils.messageString("noPermissionRank", ChatColor.stripColor(rank.getLoginMessage())));
}
if (rank.isAtLeast(Rank.ADMIN) && !plexPlayer.isAdminActive())
{
throw new CommandFailException(PlexUtils.messageString("noPermissionRank", ChatColor.stripColor(rank.getLoginMessage())));
}
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
@ -344,24 +274,6 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
return true;
}
protected boolean silentCheckRank(Player player, Rank rank, String permission)
{
if (player instanceof ConsoleCommandSender)
{
return true;
}
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
return rank.isAtLeast(Rank.ADMIN) ? plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(rank) : plexPlayer.getRankFromString().isAtLeast(rank);
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
return player.hasPermission(permission);
}
return false;
}
/**
* Checks whether a sender has enough permissions or is high enough a rank
*
@ -394,7 +306,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
PlexPlayer plexPlayer = getPlexPlayer(player);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
return rank.isAtLeast(Rank.ADMIN) ? plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(rank) : plexPlayer.getRankFromString().isAtLeast(rank);
return plexPlayer.getRankFromString().isAtLeast(rank);
}
else if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
@ -609,7 +521,7 @@ public abstract class PlexCommand extends Command implements PluginIdentifiableC
*/
protected Component mmString(String s)
{
return PlexUtils.mmDeserialize(s);
return MiniMessage.miniMessage().deserialize(s);
}
public Rank getLevel()

View File

@ -1,9 +1,5 @@
package dev.plex.command.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface System
{
String value() default "";

View File

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

View File

@ -17,6 +17,7 @@ import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
@ -27,7 +28,7 @@ import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, source = RequiredCommandSource.ANY)
@CommandParameters(name = "admin", usage = "/<command> <add <player> | remove <player> | setrank <player> <rank> | list>", aliases = "saconfig,slconfig,adminconfig,adminmanage", description = "Manage all admins")
@System(value = "ranks")
@System("ranks")
public class AdminCMD extends PlexCommand
{
//TODO: Better return messages
@ -52,18 +53,13 @@ public class AdminCMD extends PlexCommand
throw new ConsoleOnlyException();
}
/*UUID targetUUID = PlexUtils.getFromName(args[1]);
UUID targetUUID = PlexUtils.getFromName(args[1]);
if (targetUUID != null)
{
PlexLog.debug("Admin Adding UUID: " + targetUUID);
}*/
if (!DataUtils.hasPlayedBefore(args[1]))
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(args[1]);
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
if (isAdmin(plexPlayer))
{
@ -85,13 +81,13 @@ public class AdminCMD extends PlexCommand
throw new ConsoleOnlyException();
}
// UUID targetUUID = PlexUtils.getFromName(args[1]);
UUID targetUUID = PlexUtils.getFromName(args[1]);
if (!DataUtils.hasPlayedBefore(args[1]))
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
PlexPlayer plexPlayer = DataUtils.getPlayer(args[1]);
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
if (!isAdmin(plexPlayer))
{
@ -114,9 +110,9 @@ public class AdminCMD extends PlexCommand
throw new ConsoleOnlyException();
}
// UUID targetUUID = PlexUtils.getFromName(args[1]);
UUID targetUUID = PlexUtils.getFromName(args[1]);
if (!DataUtils.hasPlayedBefore(args[1]))
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
@ -133,7 +129,7 @@ public class AdminCMD extends PlexCommand
return messageComponent("rankMustBeHigherThanAdmin");
}
PlexPlayer plexPlayer = DataUtils.getPlayer(args[1]);
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
if (!isAdmin(plexPlayer))
{

View File

@ -39,7 +39,7 @@ public class AdminChatCMD extends PlexCommand
if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
if (plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN) && plexPlayer.isAdminActive())
if (plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN))
{
player.sendMessage(PlexUtils.messageComponent("adminChatFormat", sender.getName(), message));
}

View File

@ -1,24 +1,21 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import dev.plex.util.WebUtils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
@ -42,7 +39,8 @@ public class BanCMD extends PlexCommand
return usage();
}
UUID targetUUID = WebUtils.getFromName(args[0]);
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
@ -51,62 +49,48 @@ public class BanCMD extends PlexCommand
PlexPlayer plexPlayer = DataUtils.getPlayer(targetUUID);
Player player = Bukkit.getPlayer(targetUUID);
if (plugin.getSystem().equalsIgnoreCase("ranks"))
if (isAdmin(plexPlayer))
{
if (isAdmin(plexPlayer))
if (!isConsole(sender))
{
if (!isConsole(sender))
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
return messageComponent("higherRankThanYou");
}
}
}
plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
if (plugin.getPunishmentManager().isBanned(targetUUID))
{
if (aBoolean)
{
send(sender, messageComponent("playerBanned"));
return;
}
String reason;
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
punishment.setReason(reason);
}
else
{
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().punish(plexPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
Bukkit.getScheduler().runTask(Plex.get(), () ->
{
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
});
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + plexPlayer.getUuid());
});
return messageComponent("playerBanned");
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.BAN);
if (args.length > 1)
{
reason = StringUtils.join(args, " ", 1, args.length);
punishment.setReason(reason);
}
else
{
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusDays(1));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{
player.kick(Punishment.generateBanMessage(punishment));
}
PlexLog.debug("(From /ban command) PunishedPlayer UUID: " + punishedPlayer.getUuid());
return null;
}

View File

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

View File

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

View File

@ -1,31 +0,0 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
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.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;
}
}

View File

@ -6,23 +6,19 @@ import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.annotation.System;
import dev.plex.rank.enums.Rank;
import dev.plex.util.GameRuleUtil;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
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;
@CommandParameters(name = "pdebug", description = "Plex's debug command", usage = "/<command> <aliases <command> | redis-reset <player> | gamerules>")
@CommandParameters(name = "pdebug", description = "Plex's debug command", usage = "/<command> <redis-reset <player> | gamerules>")
@CommandPermissions(level = Rank.EXECUTIVE, permission = "plex.debug")
@System(debug = true)
public class DebugCMD extends PlexCommand
@ -48,30 +44,11 @@ public class DebugCMD extends PlexCommand
{
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));
}
PlexUtils.commitGameRules(world);
PlexLog.debug("Set gamerules for world: " + world.getName());
}
return mmString("<aqua>Re-applied game all the game rules!");
}
if (args[0].equalsIgnoreCase("aliases"))
{
String commandName = args[1];
Command command = plugin.getServer().getCommandMap().getCommand(commandName);
if (command == null)
{
return mmString("<red>That command could not be found!");
}
return mmString("<aqua>Aliases for " + commandName + " are: " + Arrays.toString(command.getAliases().toArray(new String[0])));
}
return null;
}

View File

@ -15,7 +15,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "deopall", description = "Deop everyone on the server", aliases = "deopa")
@CommandPermissions(level = Rank.ADMIN)
@System(value = "ranks")
@System("ranks")
public class DeopAllCMD extends PlexCommand
{
@Override

View File

@ -16,7 +16,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "deop", description = "Deop a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.ADMIN, permission = "plex.deop")
@System(value = "ranks")
@System("ranks")
public class DeopCMD extends PlexCommand
{
@Override

View File

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

View File

@ -17,6 +17,7 @@ import org.jetbrains.annotations.Nullable;
@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)
{

View File

@ -1,20 +1,19 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import dev.plex.util.TimeUtils;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -33,7 +32,7 @@ public class FreezeCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PlexPlayer punishedPlayer = getPlexPlayer(player);
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
if (punishedPlayer.isFrozen())
{
@ -46,23 +45,22 @@ public class FreezeCMD extends PlexCommand
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()) && getPlexPlayer(player).isAdminActive())
if (!plexPlayer1.getRankFromString().isAtLeast(getPlexPlayer(player).getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
}
}
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
Punishment punishment = new Punishment(UUID.fromString(punishedPlayer.getUuid()), getUUID(sender));
punishment.setCustomTime(false);
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
punishment.setType(PunishmentType.FREEZE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("frozePlayer", sender.getName(), player.getName()));
return null;
}

View File

@ -1,21 +1,19 @@
package dev.plex.command.impl;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import dev.plex.util.WebUtils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
@ -37,7 +35,7 @@ public class KickCMD extends PlexCommand
return usage();
}
UUID targetUUID = WebUtils.getFromName(args[0]);
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason = "No reason provided";
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
@ -51,6 +49,8 @@ public class KickCMD extends PlexCommand
{
throw new PlayerNotFoundException();
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.KICK);
if (args.length > 1)
@ -60,11 +60,10 @@ public class KickCMD extends PlexCommand
}
punishment.setPunishedUsername(plexPlayer.getName());
punishment.setEndDate(ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE)));
punishment.setEndDate(LocalDateTime.now());
punishment.setCustomTime(false);
punishment.setActive(false);
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
plugin.getPunishmentManager().punish(plexPlayer, punishment);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("kickedPlayer", sender.getName(), plexPlayer.getName()));
player.kick(componentFromString(reason));
return null;

View File

@ -15,9 +15,9 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "list", description = "Show a list of all online players", aliases = "lsit")
@CommandParameters(name = "list", description = "Show a list of all online players")
@CommandPermissions(level = Rank.OP, permission = "plex.list")
@System(value = "ranks")
@System("ranks")
public class ListCMD extends PlexCommand
{
@Override
@ -37,10 +37,6 @@ public class ListCMD extends PlexCommand
.append(Component.space())
.append(Component.text(Bukkit.getMaxPlayers() == 1 ? "player." : "players.").color(NamedTextColor.GRAY));
send(sender, header);
if (players.size() == 0)
{
return null;
}
for (int i = 0; i < players.size(); i++)
{
Player player = players.get(i);

View File

@ -1,10 +1,12 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.List;
@ -26,7 +28,7 @@ public class LockupCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
if (isAdmin(getPlexPlayer(player)))
{

View File

@ -17,6 +17,7 @@ import org.jetbrains.annotations.Nullable;
@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)
{

View File

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

View File

@ -1,20 +1,19 @@
package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import dev.plex.util.TimeUtils;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -33,7 +32,7 @@ public class MuteCMD extends PlexCommand
return usage();
}
Player player = getNonNullPlayer(args[0]);
PlexPlayer punishedPlayer = getOfflinePlexPlayer(player.getUniqueId());
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId());
if (punishedPlayer.isMuted())
{
@ -53,16 +52,15 @@ public class MuteCMD extends PlexCommand
}
}
Punishment punishment = new Punishment(punishedPlayer.getUuid(), getUUID(sender));
Punishment punishment = new Punishment(UUID.fromString(punishedPlayer.getUuid()), getUUID(sender));
punishment.setCustomTime(false);
ZonedDateTime date = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
LocalDateTime date = LocalDateTime.now();
punishment.setEndDate(date.plusMinutes(5));
punishment.setType(PunishmentType.MUTE);
punishment.setPunishedUsername(player.getName());
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
punishment.setReason("");
plugin.getPunishmentManager().punish(punishedPlayer, punishment);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("mutedPlayer", sender.getName(), player.getName()));
return null;
}

View File

@ -10,7 +10,7 @@ import dev.plex.util.AshconInfo;
import dev.plex.util.MojangUtils;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import net.kyori.adventure.text.Component;
@ -24,6 +24,8 @@ import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.namehistory")
public class NameHistoryCMD extends PlexCommand
{
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
@ -43,12 +45,12 @@ public class NameHistoryCMD extends PlexCommand
List<Component> historyList = Lists.newArrayList();
Arrays.stream(info.getUsernameHistories()).forEach(history ->
{
if (history.getZonedDateTime() != null)
if (history.getLocalDateTime() != null)
{
historyList.add(
messageComponent("nameHistoryBody",
history.getUsername(),
TimeUtils.useTimezone(history.getZonedDateTime())));
DATE_FORMAT.format(history.getLocalDateTime())));
}
else
{

View File

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

View File

@ -15,7 +15,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "opall", description = "Op everyone on the server", aliases = "opa")
@CommandPermissions(level = Rank.ADMIN)
@System(value = "ranks")
@System("ranks")
public class OpAllCMD extends PlexCommand
{
@Override

View File

@ -16,7 +16,7 @@ import org.jetbrains.annotations.Nullable;
@CommandParameters(name = "op", description = "Op a player on the server", usage = "/<command> <player>")
@CommandPermissions(level = Rank.OP)
@System(value = "ranks")
@System("ranks")
public class OpCMD extends PlexCommand
{
@Override

View File

@ -1,6 +1,5 @@
package dev.plex.command.impl;
import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
@ -9,17 +8,11 @@ import dev.plex.command.source.RequiredCommandSource;
import dev.plex.module.PlexModule;
import dev.plex.module.PlexModuleFile;
import dev.plex.rank.enums.Rank;
import dev.plex.util.BuildInfo;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import dev.plex.util.TimeUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -37,11 +30,9 @@ public class PlexCMD extends PlexCommand
if (args.length == 0)
{
send(sender, mmString("<light_purple>Plex - A new freedom plugin."));
send(sender, mmString("<light_purple>Plugin version: <gold>" + plugin.getDescription().getVersion() + " #" + BuildInfo.getNumber() + " <light_purple>Git: <gold>" + BuildInfo.getHead()));
send(sender, mmString("<light_purple>Plugin version: <gold>" + plugin.getDescription().getVersion()));
send(sender, mmString("<light_purple>Authors: <gold>Telesphoreo, Taahh"));
send(sender, mmString("<light_purple>Built by: <gold>" + BuildInfo.getAuthor() + " <light_purple>on <gold>" + BuildInfo.getDate()));
send(sender, mmString("<light_purple>Run <gold>/plex modules <light_purple>to see a list of modules."));
plugin.getUpdateChecker().getUpdateStatusMessage(sender, true, 2);
return null;
}
if (args[0].equalsIgnoreCase("reload"))
@ -54,20 +45,8 @@ public class PlexCMD extends PlexCommand
plugin.indefBans.load(false);
plugin.getPunishmentManager().mergeIndefiniteBans();
send(sender, "Reloaded indefinite bans");
plugin.commands.load();
send(sender, "Reloaded blocked commands file");
plugin.getRankManager().importDefaultRanks();
send(sender, "Imported ranks");
plugin.setSystem(plugin.config.getString("system"));
if (!plugin.setupPermissions() && plugin.getSystem().equalsIgnoreCase("permissions") && !plugin.getServer().getPluginManager().isPluginEnabled("Vault"))
{
throw new RuntimeException("Vault is required to run on the server if you use permissions!");
}
plugin.getServiceManager().endServices();
plugin.getServiceManager().startServices();
PlexLog.debug("Restarted services");
TimeUtils.TIMEZONE = plugin.config.getString("server.timezone");
send(sender, "Set timezone to: " + TimeUtils.TIMEZONE);
send(sender, "Plex successfully reloaded.");
return null;
}
@ -97,22 +76,9 @@ public class PlexCMD extends PlexCommand
plugin.getModuleManager().loadAllModules();
plugin.getModuleManager().loadModules();
plugin.getModuleManager().enableModules();
return mmString("<green>All modules reloaded!");
return componentFromString("All modules reloaded!");
}
}
else if (args[0].equalsIgnoreCase("update"))
{
if (sender instanceof Player player && !PlexUtils.DEVELOPERS.contains(player.getUniqueId().toString()))
{
return messageComponent("noPermissionRank", "a developer");
}
if (!plugin.getUpdateChecker().getUpdateStatusMessage(sender, false, 0))
{
return mmString("<red>Plex is already up to date!");
}
plugin.getUpdateChecker().updateJar(sender);
return null;
}
else
{
return usage();

View File

@ -7,9 +7,6 @@ import dev.plex.command.annotation.System;
import dev.plex.command.exception.CommandFailException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import java.util.Collections;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -18,7 +15,7 @@ import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.OP, permission = "plex.rank", source = RequiredCommandSource.ANY)
@CommandParameters(name = "rank", description = "Displays your rank")
@System(value = "ranks")
@System("ranks")
public class RankCMD extends PlexCommand
{
@Override
@ -33,25 +30,15 @@ public class RankCMD extends PlexCommand
if (!(playerSender == null))
{
Rank rank = getPlexPlayer(playerSender).getRankFromString();
return messageComponent("yourRank", rank.isAtLeast(Rank.ADMIN) && !getPlexPlayer(playerSender).isAdminActive() ? (playerSender.isOp() ? Rank.OP.getReadable() : Rank.NONOP.getReadable()) : rank.getReadable());
return messageComponent("yourRank", rank.getReadable());
}
}
else
{
Player player = getNonNullPlayer(args[0]);
Rank rank = getPlexPlayer(player).getRankFromString();
return messageComponent("otherRank", player.getName(), rank.isAtLeast(Rank.ADMIN) && !getPlexPlayer(player).isAdminActive() ? (player.isOp() ? Rank.OP.getReadable() : Rank.NONOP.getReadable()) : rank.getReadable());
return messageComponent("otherRank", player.getName(), rank.getReadable());
}
return null;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException
{
if (args.length == 1)
{
return PlexUtils.getPlayerNameList();
}
return Collections.emptyList();
}
}

View File

@ -14,7 +14,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@CommandPermissions(level = Rank.SENIOR_ADMIN, permission = "plex.rawsay", source = RequiredCommandSource.ANY)
@CommandParameters(name = "rawsay", usage = "/<command> <message>", description = "Displays a raw message to everyone")
@CommandParameters(name = "rawsay", usage = "/<command> <message>", description = "Displays a message to everyone")
public class RawSayCMD extends PlexCommand
{
@Override

View File

@ -1,31 +0,0 @@
package dev.plex.command.impl;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang.StringUtils;
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.say", source = RequiredCommandSource.ANY)
@CommandParameters(name = "say", usage = "/<command> <message>", description = "Displays a message to everyone")
public class SayCMD extends PlexCommand
{
@Override
protected Component execute(@NotNull CommandSender sender, @Nullable Player playerSender, String[] args)
{
if (args.length == 0)
{
return usage();
}
PlexUtils.broadcast(PlexUtils.messageComponent("sayMessage", sender.getName(), PlexUtils.mmStripColor(StringUtils.join(args, " "))));
return null;
}
}

View File

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

View File

@ -7,10 +7,9 @@ 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.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.CommandSender;
@ -48,16 +47,15 @@ public class TagCMD extends PlexCommand
return usage("/tag set <prefix>");
}
String prefix = StringUtils.join(args, " ", 1, args.length);
Component convertedComponent = removeEvents(PlexUtils.mmCustomDeserialize(prefix = prefix.replace("<newline>", "").replace("<br>", ""), StandardTags.color(), StandardTags.rainbow(), StandardTags.decorations(), StandardTags.gradient(), StandardTags.transition())); //noColorComponentFromString(prefix)
Component convertedComponent = removeEvents(noColorComponentFromString(prefix));
convertedComponent = removeEvents(MiniMessage.miniMessage().deserialize(LegacyComponentSerializer.legacySection().serialize(convertedComponent)));
if (PlainTextComponentSerializer.plainText().serialize(convertedComponent).length() > plugin.config.getInt("chat.max-tag-length", 16))
{
return messageComponent("maximumPrefixLength", plugin.config.getInt("chat.max-tag-length", 16));
}
player.setPrefix(prefix);
DataUtils.update(player);
player.setPrefix(MiniMessage.miniMessage().serialize(convertedComponent));
return messageComponent("prefixSetTo", MiniMessage.miniMessage().serialize(convertedComponent));
}
@ -70,14 +68,8 @@ public class TagCMD extends PlexCommand
return messageComponent("noPermissionConsole");
}
if (playerSender == null)
{
return null;
}
PlexPlayer player = DataUtils.getPlayer(playerSender.getUniqueId());
player.setPrefix("");
DataUtils.update(player);
return messageComponent("prefixCleared");
}
@ -85,8 +77,7 @@ public class TagCMD extends PlexCommand
Player target = getNonNullPlayer(args[1]);
PlexPlayer plexTarget = DataUtils.getPlayer(target.getUniqueId());
plexTarget.setPrefix("");
DataUtils.update(plexTarget);
return messageComponent("otherPrefixCleared", target.getName());
messageComponent("otherPrefixCleared");
}
return usage();
}

View File

@ -2,18 +2,18 @@ package dev.plex.command.impl;
import com.google.common.collect.ImmutableList;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.CommandParameters;
import dev.plex.command.annotation.CommandPermissions;
import dev.plex.command.exception.PlayerNotFoundException;
import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import dev.plex.util.WebUtils;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
@ -37,7 +37,7 @@ public class TempbanCMD extends PlexCommand
return usage();
}
UUID targetUUID = WebUtils.getFromName(args[0]);
UUID targetUUID = PlexUtils.getFromName(args[0]);
String reason;
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
@ -54,7 +54,7 @@ public class TempbanCMD extends PlexCommand
{
assert playerSender != null;
PlexPlayer plexPlayer1 = getPlexPlayer(playerSender);
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()) && plexPlayer.isAdminActive())
if (!plexPlayer1.getRankFromString().isAtLeast(plexPlayer.getRankFromString()))
{
return messageComponent("higherRankThanYou");
}
@ -65,8 +65,10 @@ public class TempbanCMD extends PlexCommand
{
return messageComponent("playerBanned");
}
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(targetUUID) == null ? new PunishedPlayer(targetUUID) : PlayerCache.getPunishedPlayer(targetUUID);
Punishment punishment = new Punishment(targetUUID, getUUID(sender));
punishment.setType(PunishmentType.TEMPBAN);
punishment.setType(PunishmentType.BAN);
if (args.length > 2)
{
reason = StringUtils.join(args, " ", 2, args.length);
@ -77,14 +79,10 @@ public class TempbanCMD extends PlexCommand
punishment.setReason("No reason provided.");
}
punishment.setPunishedUsername(plexPlayer.getName());
punishment.setEndDate(TimeUtils.createDate(args[1]));
punishment.setEndDate(PlexUtils.parseDateOffset(args[1]));
punishment.setCustomTime(false);
punishment.setActive(!isAdmin(plexPlayer));
if (player != null)
{
punishment.setIp(player.getAddress().getAddress().getHostAddress().trim());
}
plugin.getPunishmentManager().punish(plexPlayer, punishment);
plugin.getPunishmentManager().doPunishment(punishedPlayer, punishment);
PlexUtils.broadcast(messageComponent("banningPlayer", sender.getName(), plexPlayer.getName()));
if (player != null)
{

View File

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

View File

@ -11,7 +11,6 @@ import dev.plex.command.source.RequiredCommandSource;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.util.PlexUtils;
import dev.plex.util.WebUtils;
import java.util.List;
import java.util.UUID;
import net.kyori.adventure.text.Component;
@ -35,24 +34,21 @@ public class UnbanCMD extends PlexCommand
if (args.length == 1)
{
UUID targetUUID = WebUtils.getFromName(args[0]);
UUID targetUUID = PlexUtils.getFromName(args[0]);
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
if (!DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}
plugin.getPunishmentManager().isAsyncBanned(targetUUID).whenComplete((aBoolean, throwable) ->
if (!plugin.getPunishmentManager().isBanned(targetUUID))
{
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
if (!aBoolean)
{
send(sender, PlexUtils.mmDeserialize(new PlayerNotBannedException().getMessage()));
return;
}
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName()));
});
throw new PlayerNotBannedException();
}
plugin.getPunishmentManager().unban(targetUUID);
PlexUtils.broadcast(messageComponent("unbanningPlayer", sender.getName(), plexPlayer.getName()));
}
return null;
}

View File

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

View File

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

View File

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

View File

@ -1,95 +0,0 @@
package dev.plex.config;
import dev.plex.module.PlexModule;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
/**
* Creates a custom Config object
*/
public class ModuleConfig extends YamlConfiguration
{
/**
* The plugin instance
*/
private PlexModule module;
/**
* The File instance
*/
private File file;
/**
* Where the file is in the module JAR
*/
private String from;
/**
* Where it should be copied to in the module folder
*/
private String to;
/**
* Creates a config object
*
* @param module The module instance
* @param to The file name
*/
public ModuleConfig(PlexModule module, String from, String to)
{
this.module = module;
this.file = new File(module.getDataFolder(), to);
this.to = to;
this.from = from;
if (!file.exists())
{
saveDefault();
}
}
public void load()
{
try
{
super.load(file);
}
catch (IOException | InvalidConfigurationException ex)
{
ex.printStackTrace();
}
}
/**
* Saves the configuration file
*/
public void save()
{
try
{
super.save(file);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* Moves the configuration file from the plugin's resources folder to the data folder (plugins/Plex/)
*/
private void saveDefault()
{
try
{
Files.copy(module.getClass().getResourceAsStream("/" + from), this.file.toPath());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

View File

@ -8,7 +8,7 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event that is run when a player is added to the admin list
* Event that is ran when a player is added to the admin list
*/
@EqualsAndHashCode(callSuper = false)
@Data

View File

@ -8,7 +8,7 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event that is run when a player is removed from the admin list
* Event that is ran when a player is removed from the admin list
*/
@EqualsAndHashCode(callSuper = false)
@Data

View File

@ -9,7 +9,7 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event that is run when an admins rank is set
* Event that is ran when an admin's rank is set
*/
@EqualsAndHashCode(callSuper = false)
@Data

View File

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

View File

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

View File

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

View File

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

View File

@ -5,28 +5,29 @@ import dev.plex.PlexBase;
import dev.plex.command.PlexCommand;
import dev.plex.command.annotation.System;
import dev.plex.util.PlexLog;
import dev.plex.util.ReflectionsUtil;
import dev.plex.util.PlexUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
public class CommandHandler implements PlexBase
public class CommandHandler extends PlexBase
{
public CommandHandler()
{
Set<Class<? extends PlexCommand>> commandSet = ReflectionsUtil.getClassesBySubType("dev.plex.command.impl", PlexCommand.class);
Set<Class<? extends PlexCommand>> commandSet = PlexUtils.getClassesBySubType("dev.plex.command.impl", PlexCommand.class);
List<PlexCommand> commands = Lists.newArrayList();
commandSet.forEach(clazz ->
{
try
{
if (clazz.isAnnotationPresent(System.class))
System annotation = clazz.getDeclaredAnnotation(System.class);
if (annotation != null)
{
System annotation = clazz.getDeclaredAnnotation(System.class);
if (annotation.value().equalsIgnoreCase(plugin.getSystem().toLowerCase()))
if (annotation.value().equalsIgnoreCase(plugin.getSystem()))
{
commands.add(clazz.getConstructor().newInstance());
return;
}
if (plugin.config.getBoolean("debug") && annotation.debug())
@ -39,12 +40,12 @@ public class CommandHandler implements PlexBase
commands.add(clazz.getConstructor().newInstance());
}
}
catch (InvocationTargetException | InstantiationException | IllegalAccessException |
NoSuchMethodException ex)
catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException ex)
{
PlexLog.error("Failed to register " + clazz.getSimpleName() + " as a command!");
}
});
PlexLog.log(String.format("Registered %s commands from %s classes!", commands.size(), commandSet.size()));
}
}

View File

@ -3,29 +3,28 @@ package dev.plex.handlers;
import com.google.common.collect.Lists;
import dev.plex.PlexBase;
import dev.plex.listener.PlexListener;
import dev.plex.listener.annotation.Toggleable;
import dev.plex.listener.annotation.Toggled;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import dev.plex.util.ReflectionsUtil;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
public class ListenerHandler implements PlexBase
public class ListenerHandler extends PlexBase
{
public ListenerHandler()
{
Set<Class<? extends PlexListener>> listenerSet = ReflectionsUtil.getClassesBySubType("dev.plex.listener.impl", PlexListener.class);
Set<Class<? extends PlexListener>> listenerSet = PlexUtils.getClassesBySubType("dev.plex.listener.impl", PlexListener.class);
List<PlexListener> listeners = Lists.newArrayList();
listenerSet.forEach(clazz ->
{
try
{
if (clazz.isAnnotationPresent(Toggleable.class))
Toggled annotation = clazz.getDeclaredAnnotation(Toggled.class);
if (annotation != null)
{
Toggleable annotation = clazz.getDeclaredAnnotation(Toggleable.class);
if (plugin.config.get(annotation.value()) != null && plugin.config.getBoolean(annotation.value()))
if (plugin.config.getBoolean("chat.enabled") && annotation.enabled())
{
listeners.add(clazz.getConstructor().newInstance());
}
@ -35,8 +34,7 @@ public class ListenerHandler implements PlexBase
listeners.add(clazz.getConstructor().newInstance());
}
}
catch (InvocationTargetException | InstantiationException | IllegalAccessException |
NoSuchMethodException ex)
catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException ex)
{
PlexLog.error("Failed to register " + clazz.getSimpleName() + " as a listener!");
}

View File

@ -3,7 +3,7 @@ package dev.plex.listener;
import dev.plex.PlexBase;
import org.bukkit.event.Listener;
public abstract class PlexListener implements Listener, PlexBase
public abstract class PlexListener extends PlexBase implements Listener
{
public PlexListener()
{

View File

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

View File

@ -0,0 +1,6 @@
package dev.plex.listener.annotation;
public @interface Toggled
{
boolean enabled() default false;
}

View File

@ -18,17 +18,9 @@ public class AdminListener extends PlexListener
{
String userSender = event.getSender().getName();
PlexPlayer target = event.getPlexPlayer();
if (target.getRankFromString().isAtLeast(Rank.ADMIN))
{
PlexUtils.broadcast(messageComponent("adminReadded", userSender, target.getName(), target.getRankFromString().getReadable()));
}
else
{
target.setRank(Rank.ADMIN.name());
PlexUtils.broadcast(messageComponent("newAdminAdded", userSender, target.getName()));
}
target.setAdminActive(true);
target.setRank(Rank.ADMIN.name());
DataUtils.update(target);
PlexUtils.broadcast(messageComponent("newAdminAdded", userSender, target.getName()));
}
@EventHandler
@ -36,7 +28,7 @@ public class AdminListener extends PlexListener
{
String userSender = event.getSender().getName();
PlexPlayer target = event.getPlexPlayer();
target.setAdminActive(false);
target.setRank("");
DataUtils.update(target);
PlexUtils.broadcast(messageComponent("adminRemoved", userSender, target.getName()));
}

View File

@ -1,42 +0,0 @@
package dev.plex.listener.impl;
import dev.plex.listener.PlexListener;
import dev.plex.services.impl.TimingService;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
public class AntiNukerListener extends PlexListener
{
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event)
{
TimingService.nukerCooldown.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
if (getCount(event.getPlayer().getUniqueId()) > 200L)
{
TimingService.strikes.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
event.getPlayer().kick(Component.text("Please turn off your nuker!"));
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event)
{
TimingService.nukerCooldown.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
if (getCount(event.getPlayer().getUniqueId()) > 200L)
{
TimingService.strikes.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
event.getPlayer().kick(Component.text("Please turn off your nuker!"));
event.setCancelled(true);
}
}
public long getCount(UUID uuid)
{
return TimingService.nukerCooldown.getOrDefault(uuid, 1L);
}
}

View File

@ -1,41 +0,0 @@
package dev.plex.listener.impl;
import dev.plex.listener.PlexListener;
import dev.plex.services.impl.TimingService;
import io.papermc.paper.event.player.AsyncChatEvent;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class AntiSpamListener extends PlexListener
{
@EventHandler
public void onChat(AsyncChatEvent event)
{
TimingService.spamCooldown.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
if (getCount(event.getPlayer().getUniqueId()) > 8L)
{
event.getPlayer().sendMessage(Component.text("Please refrain from spamming messages.").color(NamedTextColor.GRAY));
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
TimingService.spamCooldown.merge(event.getPlayer().getUniqueId(), 1L, Long::sum);
if (getCount(event.getPlayer().getUniqueId()) > 8L)
{
event.getPlayer().sendMessage(Component.text("Please refrain from spamming commands.").color(NamedTextColor.GRAY));
event.setCancelled(true);
}
}
public long getCount(UUID uuid)
{
return TimingService.spamCooldown.getOrDefault(uuid, 1L);
}
}

View File

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

View File

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

View File

@ -2,19 +2,20 @@ package dev.plex.listener.impl;
import dev.plex.cache.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.listener.annotation.Toggleable;
import dev.plex.listener.annotation.Toggled;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexUtils;
import io.papermc.paper.chat.ChatRenderer;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.jetbrains.annotations.NotNull;
@Toggleable("chat.enabled")
@Toggled(enabled = true)
public class ChatListener extends PlexListener
{
private final PlexChatRenderer renderer = new PlexChatRenderer();
@ -23,6 +24,12 @@ public class ChatListener extends PlexListener
public void onChat(AsyncChatEvent event)
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(event.getPlayer().getUniqueId());
if (PlayerCache.getPunishedPlayer(event.getPlayer().getUniqueId()).isMuted())
{
event.getPlayer().sendMessage(PlexUtils.messageComponent("muted"));
event.setCancelled(true);
return;
}
Component prefix = plugin.getRankManager().getPrefix(plexPlayer);
if (prefix != null)
@ -51,14 +58,14 @@ public class ChatListener extends PlexListener
return Component.empty()
.append(prefix)
.append(Component.space())
.append(MiniMessage.miniMessage().deserialize(plugin.config.getString("chat.name-color", "<white>"))).append(sourceDisplayName)
.append(LegacyComponentSerializer.legacyAmpersand().deserialize("&" + plugin.config.getString("chat.name-color") + LegacyComponentSerializer.legacyAmpersand().serialize(sourceDisplayName)))
.append(Component.space())
.append(Component.text("»").color(NamedTextColor.GRAY))
.append(Component.space())
.append(message);
}
return Component.empty()
.append(MiniMessage.miniMessage().deserialize(plugin.config.getString("chat.name-color", "<white>"))).append(sourceDisplayName)
.append(LegacyComponentSerializer.legacyAmpersand().deserialize("&" + plugin.config.getString("chat.name-color") + LegacyComponentSerializer.legacyAmpersand().serialize(sourceDisplayName)))
.append(Component.space())
.append(Component.text("»").color(NamedTextColor.GRAY))
.append(Component.space())

View File

@ -1,18 +1,7 @@
package dev.plex.listener.impl;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.command.blocking.BlockedCommand;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.services.impl.CommandBlockerService;
import dev.plex.util.PlexLog;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
@ -35,99 +24,4 @@ public class CommandListener extends PlexListener
}
});
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommandBlocking(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
PlexPlayer plexPlayer = DataUtils.getPlayer(player.getUniqueId());
String commandName = StringUtils.normalizeSpace(event.getMessage()).split(" ")[0].replaceFirst("/", "");
String arguments = StringUtils.normalizeSpace(StringUtils.normalizeSpace(event.getMessage()).replace(event.getMessage().split(" ")[0], ""));
PlexLog.debug("Checking Command: {0} with args {1}", commandName, arguments);
AtomicReference<BlockedCommand> cmdRef = new AtomicReference<>();
PlexLog.debug("Blocked Commands List: " + CommandBlockerService.getBLOCKED_COMMANDS().size());
CommandBlockerService.getBLOCKED_COMMANDS().stream().filter(blockedCommand -> blockedCommand.getCommand() != null).forEach(blockedCommand ->
{
boolean matches = true;
String[] args = blockedCommand.getCommand().split(" ");
String[] cmdArgs = event.getMessage().replaceFirst("/", "").split(" ");
for (int i = 0; i < args.length; i++)
{
if (i + 1 > cmdArgs.length)
{
matches = false;
break;
}
if (!args[i].equalsIgnoreCase(cmdArgs[i]))
{
matches = false;
break;
}
}
if (matches)
{
PlexLog.debug("Used blocked command exactly matched");
cmdRef.set(blockedCommand);
return;
}
if (blockedCommand.getCommandAliases().stream().anyMatch(s -> s.equalsIgnoreCase(commandName)))
{
PlexLog.debug("Found a command name in a blocked command alias, checking arguments now.");
String[] commandArgs = blockedCommand.getCommand().split(" ");
if (arguments.toLowerCase(Locale.ROOT).startsWith(StringUtils.join(commandArgs, " ", 1, commandArgs.length).toLowerCase(Locale.ROOT)))
{
PlexLog.debug("Player attempted to use a blocked command with an alias.");
cmdRef.set(blockedCommand);
return;
}
}
});
if (cmdRef.get() == null)
{
CommandBlockerService.getBLOCKED_COMMANDS().forEach(blockedCommand ->
{
if (blockedCommand.getRegex() != null)
{
Pattern pattern = Pattern.compile(blockedCommand.getRegex(), Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(event.getMessage().replaceFirst("/", ""));
if (matcher.find())
{
PlexLog.debug("Player attempted to use a blocked regex");
cmdRef.set(blockedCommand);
}
}
});
}
if (cmdRef.get() != null)
{
BlockedCommand cmd = cmdRef.get();
switch (cmd.getRequiredLevel().toLowerCase(Locale.ROOT))
{
case "e" ->
{
event.setCancelled(true);
event.getPlayer().sendMessage(cmd.getMessage());
}
case "a" ->
{
if (plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN))
{
return;
}
event.setCancelled(true);
event.getPlayer().sendMessage(cmd.getMessage());
}
case "s" ->
{
if (plexPlayer.isAdminActive() && plexPlayer.getRankFromString().isAtLeast(Rank.SENIOR_ADMIN))
{
return;
}
event.setCancelled(true);
event.getPlayer().sendMessage(cmd.getMessage());
}
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -3,11 +3,9 @@ package dev.plex.listener.impl;
import com.destroystokyo.paper.event.server.PaperServerListPingEvent;
import dev.plex.listener.PlexListener;
import dev.plex.util.PlexUtils;
import dev.plex.util.RandomUtil;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
@ -22,17 +20,16 @@ public class ServerListener extends PlexListener
baseMotd = baseMotd.replace("%mcversion%", Bukkit.getBukkitVersion().split("-")[0]);
if (plugin.config.getBoolean("server.colorize_motd"))
{
AtomicReference<Component> motd = new AtomicReference<>(Component.empty());
final StringBuilder motd = new StringBuilder();
for (final String word : baseMotd.split(" "))
{
motd.set(motd.get().append(Component.text(word).color(RandomUtil.getRandomColor())));
motd.set(motd.get().append(Component.space()));
motd.append(PlexUtils.randomChatColor()).append(word).append(" ");
}
event.motd(motd.get());
event.motd(LegacyComponentSerializer.legacyAmpersand().deserialize(motd.toString().trim()));
}
else
{
event.motd(PlexUtils.mmDeserialize(baseMotd.trim()));
event.motd(LegacyComponentSerializer.legacyAmpersand().deserialize(baseMotd.trim()));
}
if (plugin.config.contains("server.sample"))
{

View File

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

View File

@ -27,10 +27,6 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@ -39,10 +35,6 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@ -51,10 +43,6 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
}

View File

@ -1,7 +1,6 @@
package dev.plex.listener.impl;
import dev.plex.Plex;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.listener.PlexListener;
import dev.plex.player.PlexPlayer;
@ -12,41 +11,100 @@ import dev.plex.util.PlexUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.jetbrains.annotations.NotNull;
public class WorldListener extends PlexListener
{
@EventHandler
public void onBlockPlace(BlockPlaceEvent e)
{
if (!checkPermission(e.getPlayer(), true))
Player player = e.getPlayer();
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
World world = player.getWorld();
if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
e.setCancelled(true);
String permission = plugin.config.getString("worlds." + world.getName().toLowerCase() + ".permission");
if (permission == null)
{
return;
}
if (player.hasPermission(permission))
{
return;
}
}
else if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (plugin.config.contains("worlds." + world.getName().toLowerCase() + ".requiredLevels"))
{
@NotNull List<String> requiredLevel = plugin.config.getStringList("worlds." + world.getName().toLowerCase() + ".requiredLevels");
if (checkLevel(plexPlayer, requiredLevel.toArray(String[]::new)))
{
return;
}
}
else
{
return;
}
}
e.setCancelled(true);
String noEdit = plugin.config.getString("worlds." + world.getName().toLowerCase() + ".noEdit");
if (noEdit != null)
{
player.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(noEdit));
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e)
{
if (!checkPermission(e.getPlayer(), true))
Player player = e.getPlayer();
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
World world = player.getWorld();
if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
e.setCancelled(true);
String permission = plugin.config.getString("worlds." + world.getName().toLowerCase() + ".permission");
if (permission == null)
{
return;
}
if (player.hasPermission(permission))
{
return;
}
}
else if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (plugin.config.contains("worlds." + world.getName().toLowerCase() + ".requiredLevels"))
{
@NotNull List<String> requiredLevel = plugin.config.getStringList("worlds." + world.getName().toLowerCase() + ".requiredLevels");
if (checkLevel(plexPlayer, requiredLevel.toArray(String[]::new)))
{
return;
}
}
else
{
return;
}
}
e.setCancelled(true);
String noEdit = plugin.config.getString("worlds." + world.getName().toLowerCase() + ".noEdit");
if (noEdit != null)
{
player.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(noEdit));
}
}
@ -60,54 +118,6 @@ public class WorldListener extends PlexListener
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
// If the person has permission to modify the world, we don't need to block WorldEdit
if (checkPermission(event.getPlayer(), false))
{
return;
}
String message = event.getMessage();
// Don't check the arguments
message = message.replaceAll("\\s.*", "").replaceFirst("/", "");
Command command = Bukkit.getCommandMap().getCommand(message);
if (command != null)
{
// This does check for aliases
boolean isWeCommand = command instanceof PluginIdentifiableCommand && ((PluginIdentifiableCommand)command).getPlugin().equals(Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit"));
if (isWeCommand)
{
event.getPlayer().sendMessage(Component.text("You do not have permission to use WorldEdit in this world!").color(NamedTextColor.RED));
event.setCancelled(true);
}
}
}
// TODO: Add an entry setting in the config.yml and allow checking for all worlds
@EventHandler
public void onWorldTeleport(PlayerTeleportEvent e)
{
final World adminworld = Bukkit.getWorld("adminworld");
if (adminworld == null)
{
return;
}
PlexPlayer plexPlayer = DataUtils.getPlayer(e.getPlayer().getUniqueId());
if (e.getTo().getWorld().equals(adminworld))
{
if (plugin.getSystem().equals("ranks") && !plexPlayer.isAdminActive())
{
e.setCancelled(true);
}
else if (plugin.getSystem().equals("permissions") && !e.getPlayer().hasPermission("plex.adminworld.enter"))
{
e.setCancelled(true);
}
}
}
private boolean checkLevel(PlexPlayer player, String[] requiredList)
{
PlexLog.debug("Checking world required levels " + Arrays.toString(requiredList));
@ -121,20 +131,16 @@ public class WorldListener extends PlexListener
Title title = Title.valueOf(titleString.toUpperCase(Locale.ROOT));
switch (title)
{
case DEV ->
{
hasAccess = PlexUtils.DEVELOPERS.contains(player.getUuid().toString());
case DEV -> {
hasAccess = PlexUtils.DEVELOPERS.contains(player.getUuid());
}
case MASTER_BUILDER ->
{
case MASTER_BUILDER -> {
hasAccess = Plex.get().config.contains("titles.masterbuilders") && Plex.get().config.getStringList("titles.masterbuilders").contains(player.getName());
}
case OWNER ->
{
case OWNER -> {
hasAccess = Plex.get().config.contains("titles.owners") && Plex.get().config.getStringList("titles.owners").contains(player.getName());
}
default ->
{
default -> {
return false;
}
}
@ -143,52 +149,9 @@ public class WorldListener extends PlexListener
{
String rankString = required.split("\\.")[1];
Rank rank = Rank.valueOf(rankString.toUpperCase(Locale.ROOT));
hasAccess = rank.isAtLeast(Rank.ADMIN) ? player.isAdminActive() && player.getRankFromString().isAtLeast(rank) : player.getRankFromString().isAtLeast(rank);
hasAccess = player.getRankFromString().isAtLeast(rank);
}
}
return hasAccess;
}
private boolean checkPermission(Player player, boolean showMessage)
{
PlexPlayer plexPlayer = PlayerCache.getPlexPlayerMap().get(player.getUniqueId());
World world = player.getWorld();
if (plugin.getSystem().equalsIgnoreCase("permissions"))
{
String permission = plugin.config.getString("plex." + world.getName().toLowerCase() + ".permission");
if (permission == null)
{
return true;
}
if (player.hasPermission(permission))
{
return true;
}
}
else if (plugin.getSystem().equalsIgnoreCase("ranks"))
{
if (plugin.config.contains("worlds." + world.getName().toLowerCase() + ".requiredLevels"))
{
@NotNull List<String> requiredLevel = plugin.config.getStringList("worlds." + world.getName().toLowerCase() + ".requiredLevels");
if (checkLevel(plexPlayer, requiredLevel.toArray(String[]::new)))
{
return true;
}
}
else
{
return true;
}
}
if (showMessage)
{
String noEdit = plugin.config.getString("worlds." + world.getName().toLowerCase() + ".noEdit");
if (noEdit != null)
{
player.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(noEdit));
}
}
return false;
}
}

View File

@ -1,11 +1,9 @@
package dev.plex.menu;
import com.google.common.collect.Lists;
import dev.plex.cache.DataUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.player.PunishedPlayer;
import dev.plex.punishment.Punishment;
import dev.plex.util.PlexUtils;
import dev.plex.util.menu.AbstractMenu;
import java.util.Collections;
import java.util.List;
@ -25,17 +23,17 @@ import org.bukkit.inventory.meta.SkullMeta;
public class PunishedPlayerMenu extends AbstractMenu
{
private final PlexPlayer punishedPlayer;
private final PunishedPlayer punishedPlayer;
private final List<Inventory> inventories = Lists.newArrayList();
public PunishedPlayerMenu(PlexPlayer player)
public PunishedPlayerMenu(PunishedPlayer player)
{
super("§c§lPunishments");
this.punishedPlayer = player;
for (int i = 0; i <= punishedPlayer.getPunishments().size() / 53; i++)
{
Inventory inventory = Bukkit.createInventory(null, 54, PlexUtils.mmDeserialize("Punishments Page " + (i + 1)));
Inventory inventory = Bukkit.createInventory(null, 54, "Punishments Page " + (i + 1));
ItemStack nextPage = new ItemStack(Material.FEATHER);
ItemMeta meta = nextPage.getItemMeta();
meta.displayName(Component.text("Next Page").color(NamedTextColor.LIGHT_PURPLE));
@ -164,7 +162,7 @@ public class PunishedPlayerMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
assert player != null;
PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPlexPlayer(player.getUniqueId());
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId());
if (punishedPlayer == null)
{
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -1,9 +1,8 @@
package dev.plex.menu;
import com.google.common.collect.Lists;
import dev.plex.cache.DataUtils;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexUtils;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.util.menu.AbstractMenu;
import java.util.List;
import org.bukkit.Bukkit;
@ -28,15 +27,15 @@ public class PunishmentMenu extends AbstractMenu
super("§c§lPunishments");
for (int i = 0; i <= Bukkit.getOnlinePlayers().size() / 53; i++)
{
Inventory inventory = Bukkit.createInventory(null, 54, PlexUtils.mmDeserialize("Punishments Page " + (i + 1)));
Inventory inventory = Bukkit.createInventory(null, 54, "Punishments Page " + (i + 1));
ItemStack nextPage = new ItemStack(Material.FEATHER);
ItemMeta meta = nextPage.getItemMeta();
meta.displayName(PlexUtils.mmDeserialize("<light_purple>Next Page"));
meta.setDisplayName(ChatColor.LIGHT_PURPLE + "Next Page");
nextPage.setItemMeta(meta);
ItemStack previousPage = new ItemStack(Material.FEATHER);
ItemMeta meta2 = previousPage.getItemMeta();
meta2.displayName(PlexUtils.mmDeserialize("<light_purple>Previous Page"));
meta2.setDisplayName(ChatColor.LIGHT_PURPLE + "Previous Page");
previousPage.setItemMeta(meta2);
inventory.setItem(50, nextPage);
@ -73,7 +72,7 @@ public class PunishmentMenu extends AbstractMenu
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
SkullMeta meta = (SkullMeta)item.getItemMeta();
meta.setOwningPlayer(players);
meta.displayName(PlexUtils.mmDeserialize("<!italic><yellow>" + players.getName()));
meta.setDisplayName(ChatColor.YELLOW + players.getName());
item.setItemMeta(meta);
inv.setItem(currentItemIndex, item);
@ -99,19 +98,11 @@ public class PunishmentMenu extends AbstractMenu
{
return;
}
if (!event.getCurrentItem().hasItemMeta())
{
return;
}
if (!event.getCurrentItem().getItemMeta().hasDisplayName())
{
return;
}
ItemStack item = event.getCurrentItem();
event.setCancelled(true);
if (item.getType() == Material.FEATHER)
{
if (item.getItemMeta().displayName().equals(PlexUtils.mmDeserialize("<light_purple>Next Page")))
if (item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.LIGHT_PURPLE + "Next Page"))
{
if (getCurrentInventoryIndex(inv) + 1 > inventories.size() - 1)
{
@ -123,7 +114,7 @@ public class PunishmentMenu extends AbstractMenu
}
openInv((Player)event.getWhoClicked(), getCurrentInventoryIndex(inv) + 1);
}
else if (item.getItemMeta().displayName().equals(PlexUtils.mmDeserialize("<light_purple>Previous Page")))
else if (item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.LIGHT_PURPLE + "Previous Page"))
{
if (getCurrentInventoryIndex(inv) - 1 < 0)
{
@ -147,7 +138,7 @@ public class PunishmentMenu extends AbstractMenu
SkullMeta meta = (SkullMeta)item.getItemMeta();
OfflinePlayer player = meta.getOwningPlayer();
assert player != null;
PlexPlayer punishedPlayer = DataUtils.getPlayer(player.getUniqueId());
PunishedPlayer punishedPlayer = PlayerCache.getPunishedPlayer(player.getUniqueId()) == null ? null : PlayerCache.getPunishedPlayer(player.getUniqueId());
if (punishedPlayer == null)
{
event.getWhoClicked().sendMessage(ChatColor.RED + "This player does not exist. Try doing /punishments <player> instead.");

View File

@ -3,7 +3,6 @@ package dev.plex.module;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.module.exception.ModuleLoadException;
import dev.plex.module.loader.LibraryLoader;
import dev.plex.util.PlexLog;
import java.io.File;
import java.io.IOException;
@ -24,12 +23,6 @@ public class ModuleManager
{
private final List<PlexModule> modules = Lists.newArrayList();
private final LibraryLoader libraryLoader;
public ModuleManager()
{
this.libraryLoader = new LibraryLoader(Plex.get().getLogger());
}
public void loadAllModules()
{
@ -63,10 +56,8 @@ public class ModuleManager
String description = internalModuleConfig.getString("description", "A Plex module");
String version = internalModuleConfig.getString("version", "1.0");
List<String> libraries = internalModuleConfig.getStringList("libraries");
PlexModuleFile plexModuleFile = new PlexModuleFile(name, main, description, version);
plexModuleFile.setLibraries(libraries);
Class<? extends PlexModule> module = (Class<? extends PlexModule>)Class.forName(main, true, loader);
PlexModule plexModule = module.getConstructor().newInstance();
@ -82,8 +73,7 @@ public class ModuleManager
plexModule.setLogger(LogManager.getLogger(plexModuleFile.getName()));
modules.add(plexModule);
}
catch (MalformedURLException | ClassNotFoundException | InvocationTargetException |
InstantiationException | IllegalAccessException | NoSuchMethodException e)
catch (MalformedURLException | ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e)
{
e.printStackTrace();
}
@ -97,7 +87,6 @@ public class ModuleManager
{
PlexLog.log("Loading module " + module.getPlexModuleFile().getName() + " with version " + module.getPlexModuleFile().getVersion());
module.load();
// this.libraryLoader.createLoader(module, module.getPlexModuleFile());
});
}

View File

@ -5,10 +5,6 @@ import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.listener.PlexListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import lombok.AccessLevel;
@ -16,8 +12,6 @@ import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.Logger;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Getter
@Setter(AccessLevel.MODULE)
@ -71,25 +65,4 @@ public abstract class PlexModule
{
return commands.stream().filter(plexCommand -> plexCommand.getName().equalsIgnoreCase(name) || plexCommand.getAliases().stream().map(String::toLowerCase).toList().contains(name.toLowerCase(Locale.ROOT))).findFirst().orElse(null);
}
@Nullable
public InputStream getResource(@NotNull String filename)
{
try
{
URL url = this.getClass().getClassLoader().getResource(filename);
if (url == null)
{
return null;
}
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
}
catch (IOException ex)
{
return null;
}
}
}

View File

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

View File

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

View File

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

View File

@ -1,14 +0,0 @@
package dev.plex.permission;
import dev.morphia.annotations.Entity;
import java.util.UUID;
import lombok.Data;
@Data
@Entity
public class Permission
{
private final UUID uuid;
private final String permission;
private boolean allowed = true;
}

View File

@ -1,32 +1,21 @@
package dev.plex.player;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import dev.plex.Plex;
import dev.plex.permission.Permission;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.extra.Note;
import dev.plex.rank.enums.Rank;
import dev.plex.storage.StorageType;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import dev.plex.util.adapter.ZonedDateTimeSerializer;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachment;
@Getter
@Setter
@ -39,11 +28,11 @@ public class PlexPlayer
@Setter(AccessLevel.NONE)
@Indexed(options = @IndexOptions(unique = true))
private UUID uuid;
private String uuid;
@Indexed
private String name;
private transient Player player;
private Player player;
private String loginMessage;
private String prefix;
@ -51,23 +40,11 @@ public class PlexPlayer
private boolean vanished;
private boolean commandSpy;
// These fields are transient so MongoDB doesn't automatically drop them in.
private transient boolean frozen;
private transient boolean muted;
private transient boolean lockedUp;
private boolean adminActive;
private long coins;
private String rank;
private List<String> ips = Lists.newArrayList();
private List<Punishment> punishments = Lists.newArrayList();
private List<Note> notes = Lists.newArrayList();
private List<Permission> permissions = Lists.newArrayList();
private transient PermissionAttachment permissionAttachment;
private List<String> ips;
public PlexPlayer()
{
@ -75,9 +52,9 @@ public class PlexPlayer
public PlexPlayer(UUID playerUUID)
{
this.uuid = playerUUID;
this.uuid = playerUUID.toString();
this.id = uuid.toString().substring(0, 8);
this.id = uuid.substring(0, 8);
this.name = "";
this.player = Bukkit.getPlayer(name);
@ -90,12 +67,9 @@ public class PlexPlayer
this.coins = 0;
this.ips = new ArrayList<>();
this.rank = "";
this.loadPunishments();
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
this.permissions.addAll(Plex.get().getSqlPermissions().getPermissions(this.uuid));
}
}
public String displayName()
@ -105,8 +79,8 @@ public class PlexPlayer
public Rank getRankFromString()
{
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (rank.isEmpty() || !isAdminActive())
OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(uuid));
if (rank.isEmpty())
{
if (player.isOp())
{
@ -122,26 +96,4 @@ public class PlexPlayer
return Rank.valueOf(rank.toUpperCase());
}
}
public void loadPunishments()
{
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
this.setPunishments(Plex.get().getSqlPunishment().getPunishments(this.getUuid()));
}
}
public CompletableFuture<List<Note>> loadNotes()
{
if (Plex.get().getStorageType() != StorageType.MONGODB)
{
return Plex.get().getSqlNotes().getNotes(this.getUuid());
}
return null;
}
public String toJSON()
{
return new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeSerializer()).create().toJson(this);
}
}

View File

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

View File

@ -1,51 +1,53 @@
package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import dev.morphia.annotations.Entity;
import dev.plex.Plex;
import dev.plex.util.MojangUtils;
import dev.plex.util.PlexUtils;
import dev.plex.util.TimeUtils;
import java.time.ZonedDateTime;
import dev.plex.util.adapter.LocalDateTimeDeserializer;
import dev.plex.util.adapter.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import dev.plex.util.adapter.ZonedDateTimeDeserializer;
import dev.plex.util.adapter.ZonedDateTimeSerializer;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
@Getter
@Setter
@Entity
public class Punishment
{
private static final String banUrl = Plex.get().config.getString("banning.ban_url");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a");
private final UUID punished;
private final UUID punisher;
private String ip;
private final List<String> IPS;
private String punishedUsername;
private PunishmentType type;
private String reason;
private boolean customTime;
private boolean active; // Field is only for bans
private ZonedDateTime endDate;
public Punishment()
{
this.punished = null;
this.punisher = null;
}
private LocalDateTime endDate;
public Punishment(UUID punished, UUID punisher)
{
this.punished = punished;
this.punisher = punisher;
this.IPS = Lists.newArrayList();
this.punishedUsername = "";
this.type = null;
this.reason = "";
this.customTime = false;
this.endDate = null;
}
public static Component generateBanMessage(Punishment punishment)
{
return PlexUtils.messageComponent("banMessage", banUrl, punishment.getReason(), TimeUtils.useTimezone(punishment.getEndDate()), punishment.getPunisher() == null ? "CONSOLE" : MojangUtils.getInfo(punishment.getPunisher().toString()).getUsername());
return PlexUtils.messageComponent("banMessage", banUrl, punishment.getReason(),
DATE_FORMAT.format(punishment.getEndDate()), punishment.getPunisher() == null ? "CONSOLE" : MojangUtils.getInfo(punishment.getPunisher().toString()).getUsername());
}
public static Component generateIndefBanMessage(String type)
@ -55,11 +57,11 @@ public class Punishment
public static Punishment fromJson(String json)
{
return new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeDeserializer()).create().fromJson(json, Punishment.class);
return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()).create().fromJson(json, Punishment.class);
}
public String toJSON()
{
return new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeSerializer()).create().toJson(this);
return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer()).create().toJson(this);
}
}

View File

@ -1,38 +1,37 @@
package dev.plex.punishment;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.PlexBase;
import dev.plex.cache.DataUtils;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PunishedPlayer;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import dev.plex.util.TimeUtils;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.JSONObject;
import org.json.JSONTokener;
import redis.clients.jedis.Jedis;
public class PunishmentManager implements PlexBase
public class PunishmentManager extends PlexBase
{
@Getter
private final List<IndefiniteBan> indefiniteBans = Lists.newArrayList();
public void mergeIndefiniteBans()
@ -98,19 +97,55 @@ public class PunishmentManager implements PlexBase
return this.indefiniteBans.stream().anyMatch(indefiniteBan -> indefiniteBan.getUsernames().contains(username));
}
public void issuePunishment(PlexPlayer plexPlayer, Punishment punishment)
public void insertPunishment(PunishedPlayer player, Punishment punishment)
{
plexPlayer.getPunishments().add(punishment);
if (Plex.get().getStorageType() == StorageType.MONGODB)
File file = player.getPunishmentsFile();
try
{
CompletableFuture.runAsync(() ->
if (isNotEmpty(file))
{
DataUtils.update(plexPlayer);
});
JSONTokener tokener = new JSONTokener(new FileInputStream(file));
JSONObject object = new JSONObject(tokener);
object.getJSONObject(punishment.getPunished().toString()).getJSONArray("punishments").put(punishment.toJSON());
if (plugin.getRedisConnection().isEnabled())
{
plugin.getRedisConnection().getJedis().set(player.getUuid(), object.toString());
PlexLog.debug("Added " + player.getUuid() + "'s punishment to the Redis database.");
plugin.getRedisConnection().getJedis().close();
}
FileWriter writer = new FileWriter(file);
writer.append(object.toString(8));
writer.flush();
writer.close();
}
else
{
JSONObject object = new JSONObject();
Map<String, List<String>> punishments = Maps.newHashMap();
List<String> punishmentList = Lists.newArrayList();
punishmentList.add(punishment.toJSON());
punishments.put("punishments", punishmentList);
object.put(punishment.getPunished().toString(), punishments);
if (plugin.getRedisConnection().isEnabled())
{
plugin.getRedisConnection().getJedis().set(player.getUuid(), object.toString());
PlexLog.debug("Added " + player.getUuid() + "'s punishment to the Redis database.");
plugin.getRedisConnection().getJedis().close();
}
FileWriter writer = new FileWriter(file);
writer.append(object.toString(8));
writer.flush();
writer.close();
}
}
else
catch (IOException e)
{
Plex.get().getSqlPunishment().insertPunishment(punishment);
e.printStackTrace();
}
}
@ -127,54 +162,46 @@ public class PunishmentManager implements PlexBase
return false;
}
public CompletableFuture<Boolean> isAsyncBanned(UUID uuid)
{
return CompletableFuture.supplyAsync(() ->
{
PlexPlayer player = DataUtils.getPlayer(uuid);
player.loadPunishments();
return player.getPunishments().stream().anyMatch(punishment -> (punishment.getType() == PunishmentType.BAN || punishment.getType() == PunishmentType.TEMPBAN) && punishment.isActive());
});
}
public boolean isBanned(UUID uuid)
{
// TODO: If a person is using MongoDB, this will error out because it is checking for bans on a player that doesn't exist yet
/*if (!DataUtils.hasPlayedBefore(uuid))
{
return false;
}*/
return DataUtils.getPlayer(uuid).getPunishments().stream().anyMatch(punishment -> (punishment.getType() == PunishmentType.BAN || punishment.getType() == PunishmentType.TEMPBAN) && punishment.isActive());
return PlayerCache.getPunishedPlayer(uuid).getPunishments().stream().anyMatch(punishment -> punishment.getType() == PunishmentType.BAN && punishment.isActive());
}
public boolean isBanned(PlexPlayer player)
public boolean isBanned(PunishedPlayer player)
{
return isBanned(player.getUuid());
return isBanned(UUID.fromString(player.getUuid()));
}
public CompletableFuture<List<Punishment>> getActiveBans()
public List<Punishment> getActiveBans()
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
List<Punishment> punishments = Lists.newArrayList();
if (Plex.get().getRedisConnection().isEnabled())
{
return CompletableFuture.supplyAsync(() ->
Jedis jedis = Plex.get().getRedisConnection().getJedis();
jedis.keys("*").forEach(key ->
{
List<PlexPlayer> players = Plex.get().getMongoPlayerData().getPlayers();
return players.stream().map(PlexPlayer::getPunishments).flatMap(Collection::stream).filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN || punishment.getType() == PunishmentType.TEMPBAN).toList();
try
{
UUID uuid = UUID.fromString(key);
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
object.getJSONObject(uuid.toString()).getJSONArray("punishments").forEach(json ->
{
Punishment punishment = Punishment.fromJson(json.toString());
if (punishment.isActive() && punishment.getType() == PunishmentType.BAN)
{
punishments.add(punishment);
}
});
}
catch (IllegalArgumentException ignored)
{
}
});
}
else
{
//PlexLog.debug("Checking active bans mysql");
CompletableFuture<List<Punishment>> future = new CompletableFuture<>();
Plex.get().getSqlPunishment().getPunishments().whenComplete((punishments, throwable) ->
{
//PlexLog.debug("Received Punishments");
List<Punishment> punishmentList = punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN || punishment.getType() == PunishmentType.TEMPBAN).toList();
//PlexLog.debug("Completing with {0} punishments", punishmentList.size());
future.complete(punishmentList);
});
return future;
}
return punishments;
}
public void unban(Punishment punishment)
@ -182,31 +209,69 @@ public class PunishmentManager implements PlexBase
this.unban(punishment.getPunished());
}
public CompletableFuture<Void> unban(UUID uuid)
public void unban(UUID uuid)
{
if (Plex.get().getStorageType() == StorageType.MONGODB)
if (Plex.get().getRedisConnection().isEnabled())
{
return CompletableFuture.runAsync(() ->
Jedis jedis = Plex.get().getRedisConnection().getJedis();
String jsonPunishmentString = jedis.get(uuid.toString());
JSONObject object = new JSONObject(jsonPunishmentString);
List<Punishment> punishments = object.getJSONObject(uuid.toString()).getJSONArray("punishments").toList().stream().map(obj -> Punishment.fromJson(obj.toString())).collect(Collectors.toList());
while (punishments.stream().anyMatch(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN))
{
PlexPlayer plexPlayer = DataUtils.getPlayer(uuid);
plexPlayer.setPunishments(plexPlayer.getPunishments().stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN || punishment.getType() == PunishmentType.TEMPBAN)
.peek(punishment -> punishment.setActive(false)).collect(Collectors.toList()));
DataUtils.update(plexPlayer);
});
punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).findFirst().ifPresent(punishment ->
{
int index = punishments.indexOf(punishment);
punishment.setActive(false);
punishments.set(index, punishment);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
jedis.set(uuid.toString(), object.toString());
}
else
PunishedPlayer player = PlayerCache.getPunishedPlayer(uuid);
File file = player.getPunishmentsFile();
if (isNotEmpty(file))
{
return Plex.get().getSqlPunishment().removeBan(uuid);
try (FileInputStream fis = new FileInputStream(file))
{
JSONTokener tokener = new JSONTokener(fis);
JSONObject object = new JSONObject(tokener);
List<Punishment> punishments = object.getJSONObject(uuid.toString()).getJSONArray("punishments").toList().stream().map(obj -> Punishment.fromJson(obj.toString())).collect(Collectors.toList());
while (punishments.stream().anyMatch(punishment -> punishment.isActive() && punishment.getType() == PunishmentType.BAN))
{
punishments.stream().filter(Punishment::isActive).filter(punishment -> punishment.getType() == PunishmentType.BAN).findFirst().ifPresent(punishment ->
{
int index = punishments.indexOf(punishment);
punishment.setActive(false);
punishments.set(index, punishment);
});
}
object.getJSONObject(uuid.toString()).getJSONArray("punishments").clear();
object.getJSONObject(uuid.toString()).getJSONArray("punishments").putAll(punishments.stream().map(Punishment::toJSON).collect(Collectors.toList()));
FileWriter writer = new FileWriter(file);
writer.append(object.toString());
writer.flush();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void doPunishment(PlexPlayer player, Punishment punishment)
private void issuePunishment(PunishedPlayer player, Punishment punishment)
{
if (punishment.getType() == PunishmentType.FREEZE)
{
player.setFrozen(true);
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
ZonedDateTime then = punishment.getEndDate();
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = punishment.getEndDate();
long seconds = ChronoUnit.SECONDS.between(now, then);
new BukkitRunnable()
{
@ -219,15 +284,15 @@ public class PunishmentManager implements PlexBase
return;
}
player.setFrozen(false);
Bukkit.broadcast(PlexUtils.messageComponent("unfrozePlayer", "Plex", Bukkit.getOfflinePlayer(player.getUuid()).getName()));
Bukkit.broadcast(PlexUtils.messageComponent("unfrozePlayer", "Plex", Bukkit.getOfflinePlayer(UUID.fromString(player.getUuid())).getName()));
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
else if (punishment.getType() == PunishmentType.MUTE)
{
player.setMuted(true);
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(TimeUtils.TIMEZONE));
ZonedDateTime then = punishment.getEndDate();
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = punishment.getEndDate();
long seconds = ChronoUnit.SECONDS.between(now, then);
new BukkitRunnable()
{
@ -240,16 +305,16 @@ public class PunishmentManager implements PlexBase
return;
}
player.setMuted(false);
Bukkit.broadcast(PlexUtils.messageComponent("unmutedPlayer", "Plex", Bukkit.getOfflinePlayer(player.getUuid()).getName()));
Bukkit.broadcast(PlexUtils.messageComponent("unmutedPlayer", "Plex", Bukkit.getOfflinePlayer(UUID.fromString(player.getUuid())).getName()));
}
}.runTaskLater(Plex.get(), 20 * seconds);
}
}
public void punish(PlexPlayer player, Punishment punishment)
public void doPunishment(PunishedPlayer player, Punishment punishment)
{
issuePunishment(player, punishment);
doPunishment(player, punishment);
insertPunishment(player, punishment);
}
@Data

View File

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

View File

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

View File

@ -4,6 +4,7 @@ import dev.plex.Plex;
import dev.plex.player.PlexPlayer;
import dev.plex.rank.enums.Rank;
import dev.plex.rank.enums.Title;
import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.io.File;
import java.io.FileInputStream;
@ -14,7 +15,7 @@ import java.util.stream.Collectors;
import lombok.SneakyThrows;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
@ -95,13 +96,13 @@ public class RankManager
{
if (!player.getPrefix().equals(""))
{
return PlexUtils.mmCustomDeserialize(player.getPrefix(), StandardTags.color(), StandardTags.rainbow(), StandardTags.decorations(), StandardTags.gradient(), StandardTags.transition());
return MiniMessage.miniMessage().deserialize(player.getPrefix());
}
if (Plex.get().config.contains("titles.owners") && Plex.get().config.getStringList("titles.owners").contains(player.getName()))
{
return Title.OWNER.getPrefix();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
if (PlexUtils.DEVELOPERS.contains(player.getUuid())) // don't remove or we will front door ur mother
{
return Title.DEV.getPrefix();
}
@ -126,7 +127,7 @@ public class RankManager
{
return Title.OWNER.getLoginMessage();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
if (PlexUtils.DEVELOPERS.contains(player.getUuid())) // don't remove or we will front door ur mother
{
return Title.DEV.getLoginMessage();
}
@ -147,7 +148,7 @@ public class RankManager
{
return Title.OWNER.getColor();
}
if (PlexUtils.DEVELOPERS.contains(player.getUuid().toString())) // don't remove or we will front door ur mother
if (PlexUtils.DEVELOPERS.contains(player.getUuid())) // don't remove or we will front door ur mother
{
return Title.DEV.getColor();
}
@ -164,11 +165,11 @@ public class RankManager
public boolean isAdmin(PlexPlayer plexPlayer)
{
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN) && plexPlayer.isAdminActive();
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN);
}
public boolean isSeniorAdmin(PlexPlayer plexPlayer)
{
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.SENIOR_ADMIN) && plexPlayer.isAdminActive();
return !plexPlayer.getRank().isEmpty() && plexPlayer.getRankFromString().isAtLeast(Rank.SENIOR_ADMIN);
}
}

View File

@ -1,21 +1,21 @@
package dev.plex.rank.enums;
import dev.plex.util.PlexUtils;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.json.JSONObject;
@Getter
public enum Rank
{
IMPOSTOR(-1, "<aqua>an <yellow>Impostor<reset>", "Impostor", "<dark_gray>[<yellow>Imp<dark_gray>]", NamedTextColor.YELLOW),
NONOP(0, "a <white>Non-Op<reset>", "Non-Op", "", NamedTextColor.WHITE),
OP(1, "an <green>Op<reset>", "Operator", "<dark_gray>[<green>OP<dark_gray>]", NamedTextColor.GREEN),
ADMIN(2, "an <dark_green>Admin<reset>", "Admin", "<dark_gray>[<green>Admin<dark_gray>]", NamedTextColor.DARK_GREEN),
SENIOR_ADMIN(3, "a <gold>Senior Admin<reset>", "Senior Admin", "<dark_gray>[<gold>SrA<dark_gray>]", NamedTextColor.GOLD),
EXECUTIVE(4, "an <red>Executive<reset>", "Executive", "<dark_gray>[<red>Exec<dark_gray>]", NamedTextColor.RED);
IMPOSTOR(-1, "<aqua>an <yellow>Impostor", "Impostor", "<dark_gray>[<yellow>Imp<dark_gray>]", NamedTextColor.YELLOW),
NONOP(0, "a <white>Non-Op", "Non-Op", "", NamedTextColor.WHITE),
OP(1, "an <green>Op", "Operator", "<dark_gray>[<green>OP<dark_gray>]", NamedTextColor.GREEN),
ADMIN(2, "an <dark_green>Admin", "Admin", "<dark_gray>[<green>Admin<dark_gray>]", NamedTextColor.DARK_GREEN),
SENIOR_ADMIN(3, "a <gold>Senior Admin", "Senior Admin", "<dark_gray>[<gold>SrA<dark_gray>]", NamedTextColor.GOLD),
EXECUTIVE(4, "an <red>Executive", "Executive", "<dark_gray>[<red>Exec<dark_gray>]", NamedTextColor.RED);
private final int level;
@ -47,7 +47,7 @@ public enum Rank
public Component getPrefix()
{
return PlexUtils.mmDeserialize(this.prefix);
return MiniMessage.miniMessage().deserialize(this.prefix);
}
public JSONObject toJSON()

View File

@ -1,18 +1,18 @@
package dev.plex.rank.enums;
import dev.plex.util.PlexUtils;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.json.JSONObject;
@Getter
public enum Title
{
MASTER_BUILDER(0, "<aqua>a <dark_aqua>Master Builder<reset>", "Master Builder", "<dark_gray>[<dark_aqua>Master Builder<dark_gray>]", NamedTextColor.DARK_AQUA),
DEV(1, "<aqua>a <dark_purple>Developer<reset>", "Developer", "<dark_gray>[<dark_purple>Developer<dark_gray>]", NamedTextColor.DARK_PURPLE),
OWNER(2, "<aqua>an <blue>Owner<reset>", "Owner", "<dark_gray>[<blue>Owner<dark_gray>]", NamedTextColor.BLUE);
MASTER_BUILDER(0, "<aqua>a <dark_aqua>Master Builder", "Master Builder", "<dark_gray>[<dark_aqua>Master Builder<dark_gray>]", NamedTextColor.DARK_AQUA),
DEV(1, "<aqua>a <dark_purple>Developer", "Developer", "<dark_gray>[<dark_purple>Developer<dark_gray>]", NamedTextColor.DARK_PURPLE),
OWNER(2, "<aqua>an <blue>Owner", "Owner", "<dark_gray>[<blue>Owner<dark_gray>]", NamedTextColor.BLUE);
private final int level;
@ -39,7 +39,7 @@ public enum Title
public Component getPrefix()
{
return PlexUtils.mmDeserialize(this.prefix);
return MiniMessage.miniMessage().deserialize(this.prefix);
}
public JSONObject toJSON()

View File

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

View File

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

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